@bkm016/basalt 0.1.12 → 0.1.14
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.
- package/README.md +3 -2
- package/chunk-03wzwnn6.js +2 -0
- package/{chunk-7jezts2n.js → chunk-06s9pr82.js} +2 -2
- package/{chunk-eyrtbbdd.js → chunk-0crbhhna.js} +1 -1
- package/{chunk-kpe7pnhy.js → chunk-0rasqm8y.js} +4 -4
- package/chunk-1w4nh5t6.js +5 -0
- package/{chunk-02d3x4mj.js → chunk-2eaehpp6.js} +3 -3
- package/{chunk-jj4hqbrx.js → chunk-30dxcr91.js} +3 -3
- package/{chunk-nw1xpt3s.js → chunk-343jsm46.js} +2 -2
- package/{chunk-bk4rpnm8.js → chunk-37ndxehw.js} +2 -2
- package/chunk-38g4jd6v.js +5 -0
- package/{chunk-0fc9apfn.js → chunk-39mh7h58.js} +23 -23
- package/{chunk-6mges89p.js → chunk-44a7f5ta.js} +5 -5
- package/chunk-44b9yx79.js +2 -0
- package/{chunk-jn5pqy5v.js → chunk-46vy2m29.js} +1 -1
- package/{chunk-2kxnw7vs.js → chunk-4f6p4n7k.js} +2 -2
- package/chunk-4w8j6n7z.js +2 -0
- package/{chunk-qs8zzg50.js → chunk-4yxd2kg1.js} +2 -2
- package/{chunk-ksk49hv0.js → chunk-59hg9a84.js} +1 -1
- package/chunk-62ebm0bn.js +2 -0
- package/chunk-6ef085c1.js +20 -0
- package/chunk-6hx9y86d.js +3 -0
- package/chunk-73t051r6.js +2 -0
- package/{chunk-1h34mzh7.js → chunk-7mgkpn94.js} +7 -7
- package/{chunk-w0rr66z7.js → chunk-81x8r8w4.js} +1 -1
- package/chunk-86yr2c0r.js +3 -0
- package/{chunk-ypqjfv3a.js → chunk-8np9b2y8.js} +2 -2
- package/{chunk-hbnmymaq.js → chunk-9ew8cap5.js} +2 -2
- package/chunk-9v3b7jjv.js +2 -0
- package/{chunk-01nve4qy.js → chunk-9vam83py.js} +1 -1
- package/chunk-9xjecw6c.js +2 -0
- package/{chunk-6sz5q3df.js → chunk-b2wpj81x.js} +2 -2
- package/chunk-b516bp7n.js +3 -0
- package/chunk-bjvv3403.js +2 -0
- package/{chunk-hc300148.js → chunk-c8g9jjqs.js} +2 -2
- package/chunk-cs91rmbf.js +18 -0
- package/chunk-drett6hb.js +2 -0
- package/{chunk-fy82qxa1.js → chunk-edcf97ka.js} +1 -1
- package/chunk-en7z6ne5.js +3 -0
- package/{chunk-p2pmdbt2.js → chunk-evnqkyt7.js} +12 -12
- package/{chunk-8mezk0cb.js → chunk-g2etemv5.js} +2 -2
- package/{chunk-n0ybj4h9.js → chunk-g5p9mj1r.js} +2 -2
- package/{chunk-eq4wqxzt.js → chunk-ge38dhv9.js} +2 -2
- package/chunk-hggam3je.js +2 -0
- package/chunk-k38jaz6c.js +7 -0
- package/{chunk-qfcr5g35.js → chunk-kcn05erf.js} +3 -3
- package/{chunk-rwks9zaw.js → chunk-m5km74eq.js} +2 -2
- package/{chunk-jpnf71q7.js → chunk-mfb3dgs8.js} +2 -2
- package/{chunk-vjne04dp.js → chunk-mh4bjtfs.js} +4 -4
- package/chunk-nysatg77.js +4161 -0
- package/chunk-p886jr17.js +25 -0
- package/{chunk-82v8jh1h.js → chunk-pdt65s31.js} +2 -2
- package/chunk-pjgt1bdx.js +3 -0
- package/{chunk-tvm4zmgj.js → chunk-pyj6avd5.js} +2 -2
- package/chunk-qd2enpr2.js +3 -0
- package/{chunk-cbgpymt4.js → chunk-qe76naq9.js} +1 -1
- package/{chunk-ntks40jd.js → chunk-qjnx4fsn.js} +5 -5
- package/{chunk-fhxy6y34.js → chunk-qs161f2q.js} +2 -2
- package/{chunk-v7wcchy2.js → chunk-rghqprav.js} +1 -1
- package/chunk-t33bm5aa.js +2 -0
- package/{chunk-nrsd810j.js → chunk-tfhp09nj.js} +2 -2
- package/chunk-vd5332ps.js +2 -0
- package/{chunk-3pf1d62g.js → chunk-vqm94hz2.js} +2 -2
- package/{chunk-85v69h91.js → chunk-w55cnj0f.js} +2 -2
- package/{chunk-1zj3zvw5.js → chunk-wnd3y4c0.js} +4 -4
- package/{chunk-stj493dn.js → chunk-xafx1p7z.js} +2 -2
- package/{chunk-9as0p561.js → chunk-xf7zw32f.js} +14 -14
- package/chunk-xk3t5ves.js +482 -0
- package/{chunk-5wnmbc1b.js → chunk-xq74x4gc.js} +2 -2
- package/chunk-y0274xr2.js +7 -0
- package/{chunk-ejjem0tc.js → chunk-z9p6s986.js} +6 -6
- package/chunk-zcwz44db.js +2 -0
- package/{chunk-w6f2r052.js → chunk-zhyzhekt.js} +1 -1
- package/compiled.js +85 -12
- package/package.json +1 -1
- package/ui-test-worker.js +65 -65
- package/web/chunk-15g9pnzy.js +1 -0
- package/web/{chunk-4f6a8dsk.js → chunk-17wwzrp4.js} +1 -1
- package/web/chunk-19tkjg9w.js +1 -0
- package/web/chunk-1y387f45.js +1 -0
- package/web/{chunk-30aeb767.js → chunk-25sn840r.js} +2 -2
- package/web/chunk-26sp6jre.js +1 -0
- package/web/{chunk-81s15c2e.js → chunk-2c7kxr4v.js} +2 -2
- package/web/{chunk-wvrs986a.js → chunk-2gsf89vs.js} +3 -3
- package/web/{chunk-3qxxrwsp.js → chunk-2gvz70wr.js} +10 -10
- package/web/chunk-2s3my1jn.js +1 -0
- package/web/{chunk-ar6jnhm5.js → chunk-32dh0hft.js} +1 -1
- package/web/{chunk-3rkkp6ed.js → chunk-3haw3wcw.js} +5 -5
- package/web/{chunk-hn8m1vsg.js → chunk-3rxhs9qm.js} +7 -7
- package/web/chunk-410qdvmv.js +1 -0
- package/web/chunk-4qehf2xx.js +2 -0
- package/web/{chunk-qdd3bx8q.js → chunk-51b8n5e1.js} +1 -1
- package/web/chunk-54mgncq3.js +1 -0
- package/web/{chunk-r6kk4vp1.js → chunk-59g6rrew.js} +4 -4
- package/web/{chunk-7tkgbbf9.js → chunk-5d9veaef.js} +2 -2
- package/web/chunk-6481wt3t.js +1 -0
- package/web/chunk-6ehecat3.js +1 -0
- package/web/chunk-6m8hq6ph.js +1 -0
- package/web/chunk-73941p08.js +1 -0
- package/web/{chunk-aeymdtm1.js → chunk-783s8jds.js} +3 -3
- package/web/{chunk-g4zm0crw.js → chunk-78m018ya.js} +1 -1
- package/web/chunk-797bh7z6.js +39 -0
- package/web/{chunk-hva7xyne.js → chunk-7hpqrfgg.js} +2 -2
- package/web/{chunk-enwfd8d5.js → chunk-7kywe73f.js} +2 -2
- package/web/chunk-7qq1ypvj.js +1 -0
- package/web/{chunk-xbyrgyy0.js → chunk-7wzszsf5.js} +2 -2
- package/web/{chunk-aa46mrgh.js → chunk-7zfqppsx.js} +2 -2
- package/web/{chunk-d73zkc4q.js → chunk-8sr9w61v.js} +3 -3
- package/web/{chunk-v34mr9ky.js → chunk-8ttp8fh3.js} +6 -6
- package/web/chunk-8zg89764.js +1 -0
- package/web/{chunk-2cyzaqjy.js → chunk-988e9wx6.js} +3 -3
- package/web/{chunk-k4dnjf8n.js → chunk-9h0f3gar.js} +3 -3
- package/web/chunk-9vr6hpmk.js +34 -0
- package/web/chunk-9vrp249f.js +2 -0
- package/web/{chunk-td83xf12.js → chunk-a205cj09.js} +2 -2
- package/web/{chunk-gkmaryr4.js → chunk-ahn2frbt.js} +1 -1
- package/web/{chunk-5g8md2wg.js → chunk-aknsydan.js} +5 -5
- package/web/chunk-at0xtfhy.js +1 -0
- package/web/chunk-bahccwb9.js +1 -0
- package/web/{chunk-rdr6wt22.js → chunk-c7fqrs8j.js} +4 -4
- package/web/chunk-d3hyf9yd.js +1 -0
- package/web/chunk-dcegr80c.js +1 -0
- package/web/{chunk-act3rr85.js → chunk-dwtatme7.js} +1 -1
- package/web/{chunk-5np514v5.js → chunk-ex8rmqn1.js} +12 -12
- package/web/{chunk-g488hxx0.js → chunk-faskbfjf.js} +3 -3
- package/web/chunk-feanedhx.js +1 -0
- package/web/{chunk-e94pd9rr.js → chunk-ffywf5w5.js} +10 -10
- package/web/chunk-fx3d48e6.js +1 -0
- package/web/{chunk-ncfzmf2g.js → chunk-g3szt4c4.js} +1 -1
- package/web/chunk-g7bcntpm.js +1 -0
- package/web/chunk-gr1tjqbd.js +1 -0
- package/web/{chunk-bygwbpvq.js → chunk-hbwxtbq3.js} +2 -2
- package/web/{chunk-gten0rpx.js → chunk-hdtvrh0f.js} +2 -2
- package/web/chunk-j031r08w.js +1 -0
- package/web/{chunk-d57fm7k0.js → chunk-j6wcszxq.js} +2 -2
- package/web/{chunk-885kpj14.js → chunk-jdx7qp2w.js} +2 -2
- package/web/chunk-jge7nn3s.js +1 -0
- package/web/chunk-jy8zat04.js +1 -0
- package/web/{chunk-7vgh17es.js → chunk-jzge034r.js} +1 -1
- package/web/{chunk-fj753yzt.js → chunk-k4qrqmdk.js} +2 -2
- package/web/chunk-k8s7kye3.js +1 -0
- package/web/{chunk-2jfesv7m.js → chunk-k9fyqrhp.js} +2 -2
- package/web/chunk-k9zn1n6d.js +1 -0
- package/web/chunk-kg3tksv7.js +1 -0
- package/web/chunk-kk5rw81s.js +2 -0
- package/web/{chunk-xpecre7w.js → chunk-kpmd893m.js} +4 -4
- package/web/chunk-md9j949p.js +1 -0
- package/web/{chunk-jeafmjsm.js → chunk-mn2wv9ye.js} +6 -6
- package/web/{chunk-dndd757x.js → chunk-mv7jgmnb.js} +3 -3
- package/web/{chunk-c3fty2c2.js → chunk-mvm68qtt.js} +7 -7
- package/web/chunk-nbcpbqq4.js +1 -0
- package/web/{chunk-b99k8q22.js → chunk-nfpff7yf.js} +8 -8
- package/web/chunk-nk7jkpam.js +1 -0
- package/web/chunk-nmvt1rn3.js +1 -0
- package/web/chunk-npw1s1h2.js +1 -0
- package/web/chunk-npyrdsf8.css +1 -0
- package/web/chunk-nzzxv84v.js +8 -0
- package/web/{chunk-n9v14vyd.js → chunk-p4pqtybm.js} +22 -22
- package/web/{chunk-jyf7a7yp.js → chunk-p79c7aak.js} +1 -1
- package/web/{chunk-6jb2zyp6.js → chunk-pafw34vg.js} +2 -2
- package/web/{chunk-y2rzeb4v.js → chunk-pf65cank.js} +2 -2
- package/web/{chunk-d1btrqmw.js → chunk-ppa21760.js} +1 -1
- package/web/{chunk-60mym60n.js → chunk-ptpkv0te.js} +1 -1
- package/web/{chunk-yjs6jmdb.js → chunk-qcdej581.js} +3 -3
- package/web/{chunk-q1zxvjhs.js → chunk-qftcdcps.js} +2 -2
- package/web/{chunk-4wwd3pfz.js → chunk-qv1w36ja.js} +2 -2
- package/web/chunk-r8p741qj.js +2 -0
- package/web/chunk-rcexbkjj.js +1 -0
- package/web/{chunk-kerfb21g.js → chunk-rjakb64x.js} +1 -1
- package/web/{chunk-k0cg4n2k.js → chunk-s0xy00v5.js} +2 -2
- package/web/{chunk-ym7kv2hs.js → chunk-s2ps0ct5.js} +1 -1
- package/web/{chunk-h24ybwp6.js → chunk-s45g7fp6.js} +1 -1
- package/web/{chunk-pjpre6de.js → chunk-s70aj1v5.js} +6 -6
- package/web/chunk-say8bvkc.js +1 -0
- package/web/{chunk-qh62nkem.js → chunk-sd3cdqcm.js} +2 -2
- package/web/{chunk-6f2sz84q.js → chunk-sgkevxdf.js} +2 -2
- package/web/chunk-sjffrcq9.js +1 -0
- package/web/{chunk-19zd0tye.js → chunk-snaepr87.js} +8 -8
- package/web/{chunk-3n9ypydh.js → chunk-tdzh6nsz.js} +2 -2
- package/web/{chunk-wqzbxzk3.js → chunk-tjd8qp87.js} +1 -1
- package/web/chunk-tncc9e57.js +1 -0
- package/web/chunk-ty2rmwda.js +1142 -0
- package/web/chunk-v22hp18w.js +1 -0
- package/web/chunk-ve9dz857.js +2 -0
- package/web/{chunk-80z8s8zb.js → chunk-vg346gxc.js} +2 -2
- package/web/{chunk-hqxc9m07.js → chunk-vpegzgzb.js} +10 -10
- package/web/{chunk-pzg25qqe.js → chunk-vvvd3grf.js} +2 -2
- package/web/{chunk-qp3tjhaq.js → chunk-vwv6pqy7.js} +1 -1
- package/web/{chunk-3psgr0q8.js → chunk-vxm7n7w6.js} +20 -20
- package/web/{chunk-h754ntg7.js → chunk-w5q7978e.js} +1 -1
- package/web/{chunk-xvfeq8v2.js → chunk-we4mhfmq.js} +12 -12
- package/web/{chunk-8539865x.js → chunk-wfgrdabk.js} +1 -1
- package/web/{chunk-sdr5wa4z.js → chunk-wkhj4hsw.js} +4 -4
- package/web/{chunk-7ksg3ccg.js → chunk-wspk8qbg.js} +2 -2
- package/web/{chunk-hxbfkdjd.js → chunk-xf1hnpme.js} +1 -1
- package/web/{chunk-v1hfbjz9.js → chunk-xhqvzmfj.js} +5 -5
- package/web/chunk-xq70hgre.js +1 -0
- package/web/chunk-xtss82z2.js +1 -0
- package/web/{chunk-yf8ykk4v.js → chunk-y3tb6410.js} +3 -3
- package/web/{chunk-7v85yvb2.js → chunk-y6mcxfm0.js} +1 -1
- package/web/{chunk-7adsmqv6.js → chunk-ya696bfe.js} +2 -2
- package/web/{chunk-w9gnqkez.js → chunk-ysw5fs45.js} +3 -3
- package/web/chunk-zkq1xknc.js +1 -0
- package/web/chunk-zkv025s5.js +1 -0
- package/web/{chunk-8cnjd0f2.js → chunk-zpzvz973.js} +28 -28
- package/web/{chunk-b5zf1hs3.js → chunk-zsat72qd.js} +120 -120
- package/web/chunk-zx3h7v72.js +1 -0
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-1xfv4bd7.js +0 -2
- package/chunk-2fyjph3f.js +0 -2
- package/chunk-37zystxb.js +0 -25
- package/chunk-3k627vf2.js +0 -3
- package/chunk-4gtgqcct.js +0 -5
- package/chunk-7er5pz7s.js +0 -479
- package/chunk-7g5smgjj.js +0 -2
- package/chunk-7m3jagqn.js +0 -2
- package/chunk-9c4gdg1q.js +0 -3
- package/chunk-b2bxqeb4.js +0 -2
- package/chunk-bpw6q7g0.js +0 -3
- package/chunk-bwawt15q.js +0 -3
- package/chunk-cdw03j4t.js +0 -20
- package/chunk-ch1r3ted.js +0 -2
- package/chunk-cmwdjes8.js +0 -18
- package/chunk-db7ws33a.js +0 -7
- package/chunk-e1x629v0.js +0 -5
- package/chunk-j64dc767.js +0 -3
- package/chunk-m4bg1apa.js +0 -7
- package/chunk-nhm9z3d8.js +0 -2
- package/chunk-pnspvnyd.js +0 -2
- package/chunk-qnkrrwmg.js +0 -2
- package/chunk-r4gm8ngh.js +0 -2
- package/chunk-rks90mh1.js +0 -2
- package/chunk-t7te60m7.js +0 -2
- package/chunk-tv52xajf.js +0 -2
- package/chunk-wqqjzsjt.js +0 -3983
- package/chunk-xef4642x.js +0 -3
- package/web/chunk-04drx71p.js +0 -1
- package/web/chunk-0mdf1qja.js +0 -1
- package/web/chunk-0rdgt4jb.css +0 -1
- package/web/chunk-1m0kp0g3.js +0 -8
- package/web/chunk-3j2tcphs.js +0 -1
- package/web/chunk-3k9h7a73.js +0 -1142
- package/web/chunk-3m1bb2fw.js +0 -1
- package/web/chunk-55nvm2mj.js +0 -1
- package/web/chunk-5dkqfnh7.js +0 -2
- package/web/chunk-7ky5nrrr.js +0 -1
- package/web/chunk-8sdjgv3k.js +0 -1
- package/web/chunk-9bxtzwtc.js +0 -1
- package/web/chunk-9jy8nc4r.js +0 -1
- package/web/chunk-aebrw6cv.js +0 -39
- package/web/chunk-bcjgzwef.js +0 -1
- package/web/chunk-bra33pt0.js +0 -2
- package/web/chunk-cxpnj495.js +0 -2
- package/web/chunk-d94t9z70.js +0 -1
- package/web/chunk-de29pe57.js +0 -1
- package/web/chunk-e68jw0bg.js +0 -1
- package/web/chunk-fr4fft89.js +0 -1
- package/web/chunk-gckmcef6.js +0 -1
- package/web/chunk-gnb09wmx.js +0 -1
- package/web/chunk-gx340asc.js +0 -1
- package/web/chunk-hrgqc1vr.js +0 -1
- package/web/chunk-j9c8fa82.js +0 -1
- package/web/chunk-jz5mmp64.js +0 -1
- package/web/chunk-kxeaj44h.js +0 -1
- package/web/chunk-m0136xav.js +0 -1
- package/web/chunk-m1rdyvb5.js +0 -1
- package/web/chunk-m6vyvgm5.js +0 -1
- package/web/chunk-mxkbmgcv.js +0 -2
- package/web/chunk-my0ec787.js +0 -1
- package/web/chunk-mzzaet63.js +0 -1
- package/web/chunk-nkpdd9hw.js +0 -1
- package/web/chunk-ny436sqg.js +0 -1
- package/web/chunk-pbp1p5ex.js +0 -1
- package/web/chunk-ph75hddv.js +0 -1
- package/web/chunk-phdfyqaa.js +0 -1
- package/web/chunk-phxa5krt.js +0 -1
- package/web/chunk-r4zbw4zj.js +0 -2
- package/web/chunk-ry4ycah9.js +0 -1
- package/web/chunk-sqm16fat.js +0 -1
- package/web/chunk-tj1fn8v2.js +0 -1
- package/web/chunk-v0wtk059.js +0 -34
- package/web/chunk-v1qt3gq4.js +0 -1
- package/web/chunk-v854w9yn.js +0 -1
- package/web/chunk-ve56gxq0.js +0 -1
- package/web/chunk-w573ym17.js +0 -1
- package/web/chunk-x0mjydtp.js +0 -1
- package/web/chunk-zhybh04p.js +0 -1
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ae}from"./chunk-3pf1d62g.js";import{fe,de,ge}from"./chunk-fhxy6y34.js";import{y}from"./chunk-3k627vf2.js";import{$t,Oe,G}from"./chunk-ejjem0tc.js";import{i,r,p}from"./chunk-bwawt15q.js";var oa=r(function(aN,ia){function tt(e,t){if(typeof t==="boolean")t={forever:t};if(this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.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)}ia.exports=tt;tt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};tt.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);if(this._timer)clearTimeout(this._timer);this._timeouts=[],this._cachedTimeouts=null};tt.prototype.retry=function(e){if(this._timeout)clearTimeout(this._timeout);if(!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);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 o=this;if(this._timer=setTimeout(function(){if(o._attempts++,o._operationTimeoutCb){if(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref)o._timeout.unref()}o._fn(o._attempts)},n),this._options.unref)this._timer.unref();return!0};tt.prototype.attempt=function(e,t){if(this._fn=e,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var n=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};tt.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};tt.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};tt.prototype.start=tt.prototype.try;tt.prototype.errors=function(){return this._errors};tt.prototype.attempts=function(){return this._attempts};tt.prototype.mainError=function(){if(this._errors.length===0)return null;var e={},t=null,n=0;for(var o=0;o<this._errors.length;o++){var s=this._errors[o],a=s.message,c=(e[a]||0)+1;if(e[a]=c,c>=n)t=s,n=c}return t}});var aa=r(function(zi){var O_=oa();zi.operation=function(e){var t=zi.timeouts(e);return new O_(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};zi.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var o=[];for(var s=0;s<t.retries;s++)o.push(this.createTimeout(s,t));if(e&&e.forever&&!o.length)o.push(this.createTimeout(s,t));return o.sort(function(a,c){return a-c}),o};zi.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,o=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return o=Math.min(o,t.maxTimeout),o};zi.wrap=function(e,t,n){if(t instanceof Array)n=t,t=null;if(!n){n=[];for(var o in e)if(typeof e[o]==="function")n.push(o)}for(var s=0;s<n.length;s++){var a=n[s],c=e[a];e[a]=function(f){var h=zi.operation(t),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){if(h.retry(_))return;if(_)arguments[0]=h.mainError();g.apply(this,arguments)}),h.attempt(function(){f.apply(e,m)})}.bind(e,c),e[a].options=t}}});var ca=r(function(uN,Pr){var la=aa(),B_=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class Qi extends Error{constructor(e){super();if(e instanceof Error)this.originalError=e,{message:e}=e;else this.originalError=Error(e),this.originalError.stack=this.stack;this.name="AbortError",this.message=e}}var $_=(e,t,n)=>{let o=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=o,e},J_=(e)=>B_.includes(e),ua=(e,t)=>new Promise((n,o)=>{t={onFailedAttempt:()=>{},retries:10,...t};let s=la.operation(t);s.attempt(async(a)=>{try{n(await e(a))}catch(c){if(!(c instanceof Error)){o(TypeError(`Non-error was thrown: "${c}". You should only throw errors.`));return}if(c instanceof Qi)s.stop(),o(c.originalError);else if(c instanceof TypeError&&!J_(c.message))s.stop(),o(c);else{$_(c,a,t);try{await t.onFailedAttempt(c)}catch(d){o(d);return}if(!s.retry(c))o(s.mainError())}}})});Pr.exports=ua;Pr.exports.default=ua;Pr.exports.AbortError=Qi});var Zi=r(function(cN,ya){var Nr=Object.prototype.hasOwnProperty,_a=Object.prototype.toString,{defineProperty:da,getOwnPropertyDescriptor:fa}=Object,pa=function(t){if(typeof Array.isArray==="function")return Array.isArray(t);return _a.call(t)==="[object Array]"},ha=function(t){if(!t||_a.call(t)!=="[object Object]")return!1;var n=Nr.call(t,"constructor"),o=t.constructor&&t.constructor.prototype&&Nr.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!o)return!1;var s;for(s in t);return typeof s>"u"||Nr.call(t,s)},ma=function(t,n){if(da&&n.name==="__proto__")da(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0});else t[n.name]=n.newValue},ga=function(t,n){if(n==="__proto__"){if(!Nr.call(t,n))return;else if(fa)return fa(t,n).value}return t[n]};ya.exports=function e(){var t,n,o,s,a,c,d=arguments[0],f=1,h=arguments.length,m=!1;if(typeof d==="boolean")m=d,d=arguments[1]||{},f=2;if(d==null||typeof d!=="object"&&typeof d!=="function")d={};for(;f<h;++f)if(t=arguments[f],t!=null){for(n in t)if(o=ga(d,n),s=ga(t,n),d!==s){if(m&&s&&(ha(s)||(a=pa(s)))){if(a)a=!1,c=o&&pa(o)?o:[];else c=o&&ha(o)?o:{};ma(d,{name:n,newValue:e(m,c,s)})}else if(typeof s<"u")ma(d,{name:n,newValue:s})}}return d}});var Ea=r(function(dN,X_){X_.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Ta=r(function(fN,va){var K_=Ea();va.exports={pkg:K_}});var to=r(function(nt){var Ca=nt&&nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nt,"__esModule",{value:!0});nt.GaxiosError=nt.GAXIOS_ERROR_SYMBOL=void 0;nt.defaultErrorRedactor=Sa;var Aa=Ca(Zi()),Y_=Ca(Ta()),ji=Y_.default.pkg;nt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${ji.name}-gaxios-error`);class eo extends Error{config;response;code;status;error;[nt.GAXIOS_ERROR_SYMBOL]=ji.version;static[Symbol.hasInstance](e){if(e&&typeof e==="object"&&nt.GAXIOS_ERROR_SYMBOL in e&&e[nt.GAXIOS_ERROR_SYMBOL]===ji.version)return!0;return Function.prototype[Symbol.hasInstance].call(eo,e)}constructor(e,t,n,o){super(e,{cause:o});if(this.config=t,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Aa.default)(!0,{},t),this.response)this.response.config=(0,Aa.default)(!0,{},this.response.config);if(this.response){try{this.response.data=W_(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(o instanceof DOMException)this.code=o.name;else if(o&&typeof o==="object"&&"code"in o&&(typeof o.code==="string"||typeof o.code==="number"))this.code=o.code}static extractAPIErrorFromResponse(e,t="The request failed"){let n=t;if(typeof e.data==="string")n=e.data;if(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"){n="message"in e.data.error&&typeof e.data.error.message==="string"?e.data.error.message:n;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 a=[];for(let c of e.data.error.errors)if(typeof c==="object"&&"message"in c&&typeof c.message==="string")a.push(c.message);return Object.assign({message:a.join(`
|
|
3
|
-
`)||n,code:s,status:o},e.data.error)}return Object.assign({message:n,code:s,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}}nt.GaxiosError=eo;function W_(e,t){switch(e){case"stream":return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text());default:return t}}function Sa(e){function n(a){if(!a)return;a.forEach((c,d)=>{if(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))a.set(d,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function o(a,c){if(typeof a==="object"&&a!==null&&typeof a[c]==="string"){let d=a[c];if(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))a[c]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function s(a){if(!a||typeof a!=="object")return;else if(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a)a.forEach((c,d)=>{if(["grant_type","assertion"].includes(d)||/secret/.test(d))a.set(d,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in a)a.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in a)a.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in a)a.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(e.config){if(n(e.config.headers),o(e.config,"data"),s(e.config.data),o(e.config,"body"),s(e.config.body),e.config.url.searchParams.has("token"))e.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(e.config.url.searchParams.has("client_secret"))e.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(e.response){if(Sa({config:e.response.config}),n(e.response.headers),e.response.bodyUsed)o(e.response,"data"),s(e.response.data)}return e}});var Ra=r(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});wa.getRetryConfig=z_;async function z_(e){let t=Ia(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};t=t||{},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:Number.MAX_SAFE_INTEGER,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(t.statusCodesToRetry=t.statusCodesToRetry||n,e.config.retryConfig=t,!await(t.shouldRetry||Q_)(e))return{shouldRetry:!1,config:e.config};let s=Z_(t);e.config.retryConfig.currentRetryAttempt+=1;let a=t.retryBackoff?t.retryBackoff(e,s):new Promise((c)=>{setTimeout(c,s)});if(t.onRetryAttempt)await t.onRetryAttempt(e);return await a,{shouldRetry:!0,config:e.config}}function Q_(e){let t=Ia(e);if(e.config.signal?.aborted&&e.code!=="TimeoutError"||e.code==="AbortError")return!1;if(!t||t.retry===0)return!1;if(!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries)return!1;if(!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let n=!1;for(let[o,s]of t.statusCodesToRetry){let a=e.response.status;if(a>=o&&a<=s){n=!0;break}}if(!n)return!1}if(t.currentRetryAttempt=t.currentRetryAttempt||0,t.currentRetryAttempt>=t.retry)return!1;return!0}function Ia(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig;return}function Z_(e){let n=(e.currentRetryAttempt?0:e.retryDelay??100)+(Math.pow(e.retryDelayMultiplier,e.currentRetryAttempt)-1)/2*1000,o=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(n,o,e.maxRetryDelay)}});var no=r(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});Na.GaxiosInterceptorManager=void 0;class Pa extends Set{}Na.GaxiosInterceptorManager=Pa});var Ma=r(function(An){var ey=An&&An.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Tn;Object.defineProperty(An,"__esModule",{value:!0});An.Gaxios=void 0;var ty=ey(Zi()),ka=p("https"),Ke=to(),Da=Ra(),kr=p("stream"),Dr=no(),ny=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),ry=204;class ro{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Dr.GaxiosInterceptorManager,response:new Dr.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],o=void 0,s=new Headers;if(typeof t==="string")o=new URL(t);else if(t instanceof URL)o=t;else if(t&&t.url)o=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)Tn.mergeHeaders(s,t.headers);if(n)Tn.mergeHeaders(s,new Headers(n.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...n,...t,headers:s,url:o});else return this.request({...n,headers:s,url:o})}async request(e={}){let t=await this.#r(e);return t=await this.#t(t),this.#n(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await Tn.#l(),n={...e};delete n.data;let o=await t(e.url,n),s=await this.getResponseData(e,o);if(!Object.getOwnPropertyDescriptor(o,"data")?.configurable)Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}});return Object.assign(o,{config:e,data:s})}async _request(e){try{let t;if(e.adapter)t=await e.adapter(e,this._defaultAdapter.bind(this));else t=await this._defaultAdapter(e);if(!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let s of t.data)o.push(s);t.data=Buffer.concat(o.map((s)=>typeof s==="string"?Buffer.from(s):s)).toString("utf8")}let n=Ke.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Ke.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;if(t instanceof Ke.GaxiosError)n=t;else if(t instanceof Error)n=new Ke.GaxiosError(t.message,e,void 0,t);else n=new Ke.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:s}=await Da.getRetryConfig(n);if(o&&s)return n.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#i(e),this._request(e);if(e.errorRedactor)e.errorRedactor(n);throw n}}async getResponseData(e,t){if(t.status===ry)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Ke.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let n=await t.text();try{return JSON.parse(n)}catch{return n}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let n=new URL(e),o=[...t],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(n.toString()))return!1}else if(a instanceof URL){if(a.origin===n.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(a===n.origin||a===n.hostname||a===n.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let n of this.interceptors.request.values())if(n)t=t.then(n.resolved,n.rejected);return t}async#n(e){let t=Promise.resolve(e);for(let n of this.interceptors.response.values())if(n)t=t.then(n.resolved,n.rejected);return t}async#r(e){let t=new Headers(this.defaults.headers);Tn.mergeHeaders(t,e.headers);let n=(0,ty.default)(!0,{},this.defaults,e);if(!n.url)throw Error("URL is required.");if(n.baseURL)n.url=new URL(n.url,n.baseURL);if(n.url=new URL(n.url),n.params)if(n.paramsSerializer){let a=n.paramsSerializer(n.params);if(a.startsWith("?"))a=a.slice(1);let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+a}else{let a=n.url instanceof URL?n.url:new URL(n.url);for(let[c,d]of new URLSearchParams(n.params))a.searchParams.append(c,d);n.url=a}if(typeof e.maxContentLength==="number")n.size=e.maxContentLength;if(typeof e.maxRedirects==="number")n.follow=e.maxRedirects;let o=typeof n.data==="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof kr.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let a=await ny();t.set("content-type",`multipart/related; boundary=${a}`),n.body=kr.Readable.from(this.getMultipartRequest(n.multipart,a))}else if(o)n.body=n.data;else if(typeof n.data==="object")if(t.get("Content-Type")==="application/x-www-form-urlencoded")n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data);else{if(!t.has("content-type"))t.set("content-type","application/json");n.body=JSON.stringify(n.data)}else if(n.data)n.body=n.data;if(n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!t.has("accept")&&n.responseType==="json")t.set("accept","application/json");let s=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(n.agent);else if(s&&this.#e(n.url,n.noProxy)){let a=await Tn.#a();if(this.agentCache.has(s))n.agent=this.agentCache.get(s);else n.agent=new a(s,{cert:n.cert,key:n.key}),this.agentCache.set(s,n.agent)}else if(n.cert&&n.key)if(this.agentCache.has(n.key))n.agent=this.agentCache.get(n.key);else n.agent=new ka.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent);if(typeof n.errorRedactor!=="function"&&n.errorRedactor!==!1)n.errorRedactor=Ke.defaultErrorRedactor;if(n.body&&!("duplex"in n))n.duplex="half";return this.#i(n),Object.assign(n,{headers:t,url:n.url instanceof URL?n.url:new URL(n.url)})}#i(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);if(e.signal&&!e.signal.aborted)e.signal=AbortSignal.any([e.signal,t]);else e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else if(t.match(/^text\//))return e.text();else return e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";if(yield`--${t}\r
|
|
4
|
-
Content-Type: ${
|
|
2
|
+
import{ue}from"./chunk-vqm94hz2.js";import{be,fe,Se}from"./chunk-qs161f2q.js";import{w}from"./chunk-b516bp7n.js";import{zt,Ue,K}from"./chunk-z9p6s986.js";import{a,r,p}from"./chunk-qd2enpr2.js";var oa=r(function(aN,ia){function tt(e,t){if(typeof t==="boolean")t={forever:t};if(this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.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)}ia.exports=tt;tt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};tt.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);if(this._timer)clearTimeout(this._timer);this._timeouts=[],this._cachedTimeouts=null};tt.prototype.retry=function(e){if(this._timeout)clearTimeout(this._timeout);if(!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);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;if(this._timer=setTimeout(function(){if(i._attempts++,i._operationTimeoutCb){if(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();return!0};tt.prototype.attempt=function(e,t){if(this._fn=e,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var n=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};tt.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};tt.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};tt.prototype.start=tt.prototype.try;tt.prototype.errors=function(){return this._errors};tt.prototype.attempts=function(){return this._attempts};tt.prototype.mainError=function(){if(this._errors.length===0)return null;var e={},t=null,n=0;for(var i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,c=(e[s]||0)+1;if(e[s]=c,c>=n)t=o,n=c}return t}});var aa=r(function(zi){var O_=oa();zi.operation=function(e){var t=zi.timeouts(e);return new O_(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};zi.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var i=[];for(var o=0;o<t.retries;o++)i.push(this.createTimeout(o,t));if(e&&e.forever&&!i.length)i.push(this.createTimeout(o,t));return i.sort(function(s,c){return s-c}),i};zi.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,i=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return i=Math.min(i,t.maxTimeout),i};zi.wrap=function(e,t,n){if(t instanceof Array)n=t,t=null;if(!n){n=[];for(var i in e)if(typeof e[i]==="function")n.push(i)}for(var o=0;o<n.length;o++){var s=n[o],c=e[s];e[s]=function(f){var h=zi.operation(t),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){if(h.retry(_))return;if(_)arguments[0]=h.mainError();g.apply(this,arguments)}),h.attempt(function(){f.apply(e,m)})}.bind(e,c),e[s].options=t}}});var ca=r(function(uN,Nr){var la=aa(),B_=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class Qi extends Error{constructor(e){super();if(e instanceof Error)this.originalError=e,{message:e}=e;else this.originalError=Error(e),this.originalError.stack=this.stack;this.name="AbortError",this.message=e}}var $_=(e,t,n)=>{let i=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e},J_=(e)=>B_.includes(e),ua=(e,t)=>new Promise((n,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};let o=la.operation(t);o.attempt(async(s)=>{try{n(await e(s))}catch(c){if(!(c instanceof Error)){i(TypeError(`Non-error was thrown: "${c}". You should only throw errors.`));return}if(c instanceof Qi)o.stop(),i(c.originalError);else if(c instanceof TypeError&&!J_(c.message))o.stop(),i(c);else{$_(c,s,t);try{await t.onFailedAttempt(c)}catch(d){i(d);return}if(!o.retry(c))i(o.mainError())}}})});Nr.exports=ua;Nr.exports.default=ua;Nr.exports.AbortError=Qi});var Zi=r(function(cN,ya){var xr=Object.prototype.hasOwnProperty,_a=Object.prototype.toString,{defineProperty:da,getOwnPropertyDescriptor:fa}=Object,pa=function(t){if(typeof Array.isArray==="function")return Array.isArray(t);return _a.call(t)==="[object Array]"},ha=function(t){if(!t||_a.call(t)!=="[object Object]")return!1;var n=xr.call(t,"constructor"),i=t.constructor&&t.constructor.prototype&&xr.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!i)return!1;var o;for(o in t);return typeof o>"u"||xr.call(t,o)},ma=function(t,n){if(da&&n.name==="__proto__")da(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0});else t[n.name]=n.newValue},ga=function(t,n){if(n==="__proto__"){if(!xr.call(t,n))return;else if(fa)return fa(t,n).value}return t[n]};ya.exports=function e(){var t,n,i,o,s,c,d=arguments[0],f=1,h=arguments.length,m=!1;if(typeof d==="boolean")m=d,d=arguments[1]||{},f=2;if(d==null||typeof d!=="object"&&typeof d!=="function")d={};for(;f<h;++f)if(t=arguments[f],t!=null){for(n in t)if(i=ga(d,n),o=ga(t,n),d!==o){if(m&&o&&(ha(o)||(s=pa(o)))){if(s)s=!1,c=i&&pa(i)?i:[];else c=i&&ha(i)?i:{};ma(d,{name:n,newValue:e(m,c,o)})}else if(typeof o<"u")ma(d,{name:n,newValue:o})}}return d}});var Ea=r(function(dN,X_){X_.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Ta=r(function(fN,va){var K_=Ea();va.exports={pkg:K_}});var to=r(function(nt){var Ca=nt&&nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nt,"__esModule",{value:!0});nt.GaxiosError=nt.GAXIOS_ERROR_SYMBOL=void 0;nt.defaultErrorRedactor=Sa;var Aa=Ca(Zi()),Y_=Ca(Ta()),ji=Y_.default.pkg;nt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${ji.name}-gaxios-error`);class eo extends Error{config;response;code;status;error;[nt.GAXIOS_ERROR_SYMBOL]=ji.version;static[Symbol.hasInstance](e){if(e&&typeof e==="object"&&nt.GAXIOS_ERROR_SYMBOL in e&&e[nt.GAXIOS_ERROR_SYMBOL]===ji.version)return!0;return Function.prototype[Symbol.hasInstance].call(eo,e)}constructor(e,t,n,i){super(e,{cause:i});if(this.config=t,this.response=n,this.error=i instanceof Error?i:void 0,this.config=(0,Aa.default)(!0,{},t),this.response)this.response.config=(0,Aa.default)(!0,{},this.response.config);if(this.response){try{this.response.data=W_(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(i instanceof DOMException)this.code=i.name;else if(i&&typeof i==="object"&&"code"in i&&(typeof i.code==="string"||typeof i.code==="number"))this.code=i.code}static extractAPIErrorFromResponse(e,t="The request failed"){let n=t;if(typeof e.data==="string")n=e.data;if(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"){n="message"in e.data.error&&typeof e.data.error.message==="string"?e.data.error.message:n;let i="status"in e.data.error&&typeof e.data.error.status==="string"?e.data.error.status:e.statusText,o="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 s=[];for(let c of e.data.error.errors)if(typeof c==="object"&&"message"in c&&typeof c.message==="string")s.push(c.message);return Object.assign({message:s.join(`
|
|
3
|
+
`)||n,code:o,status:i},e.data.error)}return Object.assign({message:n,code:o,status:i},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}}nt.GaxiosError=eo;function W_(e,t){switch(e){case"stream":return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text());default:return t}}function Sa(e){function n(s){if(!s)return;s.forEach((c,d)=>{if(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))s.set(d,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function i(s,c){if(typeof s==="object"&&s!==null&&typeof s[c]==="string"){let d=s[c];if(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))s[c]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function o(s){if(!s||typeof s!=="object")return;else if(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s)s.forEach((c,d)=>{if(["grant_type","assertion"].includes(d)||/secret/.test(d))s.set(d,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in s)s.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in s)s.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in s)s.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(e.config){if(n(e.config.headers),i(e.config,"data"),o(e.config.data),i(e.config,"body"),o(e.config.body),e.config.url.searchParams.has("token"))e.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(e.config.url.searchParams.has("client_secret"))e.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(e.response){if(Sa({config:e.response.config}),n(e.response.headers),e.response.bodyUsed)i(e.response,"data"),o(e.response.data)}return e}});var Ra=r(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});wa.getRetryConfig=z_;async function z_(e){let t=Ia(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};t=t||{},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:Number.MAX_SAFE_INTEGER,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(t.statusCodesToRetry=t.statusCodesToRetry||n,e.config.retryConfig=t,!await(t.shouldRetry||Q_)(e))return{shouldRetry:!1,config:e.config};let o=Z_(t);e.config.retryConfig.currentRetryAttempt+=1;let s=t.retryBackoff?t.retryBackoff(e,o):new Promise((c)=>{setTimeout(c,o)});if(t.onRetryAttempt)await t.onRetryAttempt(e);return await s,{shouldRetry:!0,config:e.config}}function Q_(e){let t=Ia(e);if(e.config.signal?.aborted&&e.code!=="TimeoutError"||e.code==="AbortError")return!1;if(!t||t.retry===0)return!1;if(!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries)return!1;if(!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let n=!1;for(let[i,o]of t.statusCodesToRetry){let s=e.response.status;if(s>=i&&s<=o){n=!0;break}}if(!n)return!1}if(t.currentRetryAttempt=t.currentRetryAttempt||0,t.currentRetryAttempt>=t.retry)return!1;return!0}function Ia(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig;return}function Z_(e){let n=(e.currentRetryAttempt?0:e.retryDelay??100)+(Math.pow(e.retryDelayMultiplier,e.currentRetryAttempt)-1)/2*1000,i=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(n,i,e.maxRetryDelay)}});var no=r(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});Na.GaxiosInterceptorManager=void 0;class Pa extends Set{}Na.GaxiosInterceptorManager=Pa});var Ma=r(function(An){var ey=An&&An.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Tn;Object.defineProperty(An,"__esModule",{value:!0});An.Gaxios=void 0;var ty=ey(Zi()),ka=p("https"),Ke=to(),Da=Ra(),Dr=p("stream"),Mr=no(),ny=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),ry=204;class ro{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Mr.GaxiosInterceptorManager,response:new Mr.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],i=void 0,o=new Headers;if(typeof t==="string")i=new URL(t);else if(t instanceof URL)i=t;else if(t&&t.url)i=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)Tn.mergeHeaders(o,t.headers);if(n)Tn.mergeHeaders(o,new Headers(n.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...n,...t,headers:o,url:i});else return this.request({...n,headers:o,url:i})}async request(e={}){let t=await this.#r(e);return t=await this.#t(t),this.#n(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await Tn.#l(),n={...e};delete n.data;let i=await t(e.url,n),o=await this.getResponseData(e,i);if(!Object.getOwnPropertyDescriptor(i,"data")?.configurable)Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}});return Object.assign(i,{config:e,data:o})}async _request(e){try{let t;if(e.adapter)t=await e.adapter(e,this._defaultAdapter.bind(this));else t=await this._defaultAdapter(e);if(!e.validateStatus(t.status)){if(e.responseType==="stream"){let i=[];for await(let o of t.data)i.push(o);t.data=Buffer.concat(i.map((o)=>typeof o==="string"?Buffer.from(o):o)).toString("utf8")}let n=Ke.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Ke.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;if(t instanceof Ke.GaxiosError)n=t;else if(t instanceof Error)n=new Ke.GaxiosError(t.message,e,void 0,t);else n=new Ke.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:i,config:o}=await Da.getRetryConfig(n);if(i&&o)return n.config.retryConfig.currentRetryAttempt=o.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#i(e),this._request(e);if(e.errorRedactor)e.errorRedactor(n);throw n}}async getResponseData(e,t){if(t.status===ry)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Ke.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let n=await t.text();try{return JSON.parse(n)}catch{return n}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let n=new URL(e),i=[...t],o=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let s of o)i.push(s.trim());for(let s of i)if(s instanceof RegExp){if(s.test(n.toString()))return!1}else if(s instanceof URL){if(s.origin===n.origin)return!1}else if(s.startsWith("*.")||s.startsWith(".")){let c=s.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(s===n.origin||s===n.hostname||s===n.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let n of this.interceptors.request.values())if(n)t=t.then(n.resolved,n.rejected);return t}async#n(e){let t=Promise.resolve(e);for(let n of this.interceptors.response.values())if(n)t=t.then(n.resolved,n.rejected);return t}async#r(e){let t=new Headers(this.defaults.headers);Tn.mergeHeaders(t,e.headers);let n=(0,ty.default)(!0,{},this.defaults,e);if(!n.url)throw Error("URL is required.");if(n.baseURL)n.url=new URL(n.url,n.baseURL);if(n.url=new URL(n.url),n.params)if(n.paramsSerializer){let s=n.paramsSerializer(n.params);if(s.startsWith("?"))s=s.slice(1);let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+s}else{let s=n.url instanceof URL?n.url:new URL(n.url);for(let[c,d]of new URLSearchParams(n.params))s.searchParams.append(c,d);n.url=s}if(typeof e.maxContentLength==="number")n.size=e.maxContentLength;if(typeof e.maxRedirects==="number")n.follow=e.maxRedirects;let i=typeof n.data==="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof Dr.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let s=await ny();t.set("content-type",`multipart/related; boundary=${s}`),n.body=Dr.Readable.from(this.getMultipartRequest(n.multipart,s))}else if(i)n.body=n.data;else if(typeof n.data==="object")if(t.get("Content-Type")==="application/x-www-form-urlencoded")n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data);else{if(!t.has("content-type"))t.set("content-type","application/json");n.body=JSON.stringify(n.data)}else if(n.data)n.body=n.data;if(n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!t.has("accept")&&n.responseType==="json")t.set("accept","application/json");let o=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(n.agent);else if(o&&this.#e(n.url,n.noProxy)){let s=await Tn.#a();if(this.agentCache.has(o))n.agent=this.agentCache.get(o);else n.agent=new s(o,{cert:n.cert,key:n.key}),this.agentCache.set(o,n.agent)}else if(n.cert&&n.key)if(this.agentCache.has(n.key))n.agent=this.agentCache.get(n.key);else n.agent=new ka.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent);if(typeof n.errorRedactor!=="function"&&n.errorRedactor!==!1)n.errorRedactor=Ke.defaultErrorRedactor;if(n.body&&!("duplex"in n))n.duplex="half";return this.#i(n),Object.assign(n,{headers:t,url:n.url instanceof URL?n.url:new URL(n.url)})}#i(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);if(e.signal&&!e.signal.aborted)e.signal=AbortSignal.any([e.signal,t]);else e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else if(t.match(/^text\//))return e.text();else return e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let i of e){let o=i.headers.get("Content-Type")||"application/octet-stream";if(yield`--${t}\r
|
|
4
|
+
Content-Type: ${o}\r
|
|
5
5
|
\r
|
|
6
|
-
`,typeof
|
|
7
|
-
`}yield n}static#o;static#s;static async#a(){return this.#o||=(await import("./chunk-02d3x4mj.js").then((m)=>i(m.default))).HttpsProxyAgent,this.#o}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("node-fetch")).default,this.#s}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}}An.Gaxios=ro;Tn=ro});var qe=r(function($e){var iy=$e&&$e.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),oy=$e&&$e.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))iy(t,e,n)};Object.defineProperty($e,"__esModule",{value:!0});$e.instance=$e.Gaxios=$e.GaxiosError=void 0;$e.request=ay;var Mr=Ma();Object.defineProperty($e,"Gaxios",{enumerable:!0,get:function(){return Mr.Gaxios}});var sy=to();Object.defineProperty($e,"GaxiosError",{enumerable:!0,get:function(){return sy.GaxiosError}});oy(no(),$e);$e.instance=new Mr.Gaxios;async function ay(e){return $e.instance.request(e)}});var io=r(function(Ua,Ur){(function(e){var t,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,{ceil:o,floor:s}=Math,a="[BigNumber Error] ",c=a+"Number primitive has more than 15 significant digits: ",d=100000000000000,f=14,h=9007199254740991,m=[1,10,100,1000,1e4,1e5,1e6,1e7,1e8,1e9,10000000000,100000000000,1000000000000,10000000000000],g=1e7,_=1e9;function v(D){var O,B,X,q=K.prototype={constructor:K,toString:null,valueOf:null},Y=new K(1),Z=20,ne=4,W=-7,V=21,oe=-1e7,se=1e7,xe=!1,Ue=1,Xe=0,be={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ze="0123456789abcdefghijklmnopqrstuvwxyz",Ji=!0;function K(C,I){var R,L,k,U,H,x,M,F,b=this;if(!(b instanceof K))return new K(C,I);if(I==null){if(C&&C._isBigNumber===!0){if(b.s=C.s,!C.c||C.e>se)b.c=b.e=null;else if(C.e<oe)b.c=[b.e=0];else b.e=C.e,b.c=C.c.slice();return}if((x=typeof C=="number")&&C*0==0){if(b.s=1/C<0?(C=-C,-1):1,C===~~C){for(U=0,H=C;H>=10;H/=10,U++);if(U>se)b.c=b.e=null;else b.e=U,b.c=[C];return}F=String(C)}else{if(!n.test(F=String(C)))return X(b,F,x);b.s=F.charCodeAt(0)==45?(F=F.slice(1),-1):1}if((U=F.indexOf("."))>-1)F=F.replace(".","");if((H=F.search(/e/i))>0){if(U<0)U=H;U+=+F.slice(H+1),F=F.substring(0,H)}else if(U<0)U=F.length}else{if(A(I,2,ze.length,"Base"),I==10&&Ji)return b=new K(C),je(b,Z+b.e+1,ne);if(F=String(C),x=typeof C=="number"){if(C*0!=0)return X(b,F,x,I);if(b.s=1/C<0?(F=F.slice(1),-1):1,K.DEBUG&&F.replace(/^0\.0*|\./,"").length>15)throw Error(c+C)}else b.s=F.charCodeAt(0)===45?(F=F.slice(1),-1):1;R=ze.slice(0,I),U=H=0;for(M=F.length;H<M;H++)if(R.indexOf(L=F.charAt(H))<0){if(L=="."){if(H>U){U=M;continue}}else if(!k){if(F==F.toUpperCase()&&(F=F.toLowerCase())||F==F.toLowerCase()&&(F=F.toUpperCase())){k=!0,H=-1,U=0;continue}}return X(b,String(C),x,I)}if(x=!1,F=B(F,I,10,b.s),(U=F.indexOf("."))>-1)F=F.replace(".","");else U=F.length}for(H=0;F.charCodeAt(H)===48;H++);for(M=F.length;F.charCodeAt(--M)===48;);if(F=F.slice(H,++M)){if(M-=H,x&&K.DEBUG&&M>15&&(C>h||C!==s(C)))throw Error(c+b.s*C);if((U=U-H-1)>se)b.c=b.e=null;else if(U<oe)b.c=[b.e=0];else{if(b.e=U,b.c=[],H=(U+1)%f,U<0)H+=f;if(H<M){if(H)b.c.push(+F.slice(0,H));for(M-=f;H<M;)b.c.push(+F.slice(H,H+=f));H=f-(F=F.slice(H)).length}else H-=M;for(;H--;F+="0");b.c.push(+F)}}else b.c=[b.e=0]}K.clone=v,K.ROUND_UP=0,K.ROUND_DOWN=1,K.ROUND_CEIL=2,K.ROUND_FLOOR=3,K.ROUND_HALF_UP=4,K.ROUND_HALF_DOWN=5,K.ROUND_HALF_EVEN=6,K.ROUND_HALF_CEIL=7,K.ROUND_HALF_FLOOR=8,K.EUCLID=9,K.config=K.set=function(C){var I,R;if(C!=null)if(typeof C=="object"){if(C.hasOwnProperty(I="DECIMAL_PLACES"))R=C[I],A(R,0,_,I),Z=R;if(C.hasOwnProperty(I="ROUNDING_MODE"))R=C[I],A(R,0,8,I),ne=R;if(C.hasOwnProperty(I="EXPONENTIAL_AT"))if(R=C[I],R&&R.pop)A(R[0],-_,0,I),A(R[1],0,_,I),W=R[0],V=R[1];else A(R,-_,_,I),W=-(V=R<0?-R:R);if(C.hasOwnProperty(I="RANGE"))if(R=C[I],R&&R.pop)A(R[0],-_,-1,I),A(R[1],1,_,I),oe=R[0],se=R[1];else if(A(R,-_,_,I),R)oe=-(se=R<0?-R:R);else throw Error(a+I+" cannot be zero: "+R);if(C.hasOwnProperty(I="CRYPTO"))if(R=C[I],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))xe=R;else throw xe=!R,Error(a+"crypto unavailable");else xe=R;else throw Error(a+I+" not true or false: "+R);if(C.hasOwnProperty(I="MODULO_MODE"))R=C[I],A(R,0,9,I),Ue=R;if(C.hasOwnProperty(I="POW_PRECISION"))R=C[I],A(R,0,_,I),Xe=R;if(C.hasOwnProperty(I="FORMAT"))if(R=C[I],typeof R=="object")be=R;else throw Error(a+I+" not an object: "+R);if(C.hasOwnProperty(I="ALPHABET"))if(R=C[I],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))Ji=R.slice(0,10)=="0123456789",ze=R;else throw Error(a+I+" invalid: "+R)}else throw Error(a+"Object expected: "+C);return{DECIMAL_PLACES:Z,ROUNDING_MODE:ne,EXPONENTIAL_AT:[W,V],RANGE:[oe,se],CRYPTO:xe,MODULO_MODE:Ue,POW_PRECISION:Xe,FORMAT:be,ALPHABET:ze}},K.isBigNumber=function(C){if(!C||C._isBigNumber!==!0)return!1;if(!K.DEBUG)return!0;var I,R,{c:L,e:k,s:U}=C;e:if({}.toString.call(L)=="[object Array]"){if((U===1||U===-1)&&k>=-_&&k<=_&&k===s(k)){if(L[0]===0){if(k===0&&L.length===1)return!0;break e}if(I=(k+1)%f,I<1)I+=f;if(String(L[0]).length==I){for(I=0;I<L.length;I++)if(R=L[I],R<0||R>=d||R!==s(R))break e;if(R!==0)return!0}}}else if(L===null&&k===null&&(U===null||U===1||U===-1))return!0;throw Error(a+"Invalid BigNumber: "+C)},K.maximum=K.max=function(){return ra(arguments,-1)},K.minimum=K.min=function(){return ra(arguments,1)},K.random=function(){var C=9007199254740992,I=Math.random()*C&2097151?function(){return s(Math.random()*C)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var L,k,U,H,x,M=0,F=[],b=new K(Y);if(R==null)R=Z;else A(R,0,_);if(H=o(R/f),xe)if(crypto.getRandomValues){L=crypto.getRandomValues(new Uint32Array(H*=2));for(;M<H;)if(x=L[M]*131072+(L[M+1]>>>11),x>=9000000000000000)k=crypto.getRandomValues(new Uint32Array(2)),L[M]=k[0],L[M+1]=k[1];else F.push(x%100000000000000),M+=2;M=H/2}else if(crypto.randomBytes){L=crypto.randomBytes(H*=7);for(;M<H;)if(x=(L[M]&31)*281474976710656+L[M+1]*1099511627776+L[M+2]*4294967296+L[M+3]*16777216+(L[M+4]<<16)+(L[M+5]<<8)+L[M+6],x>=9000000000000000)crypto.randomBytes(7).copy(L,M);else F.push(x%100000000000000),M+=7;M=H/7}else throw xe=!1,Error(a+"crypto unavailable");if(!xe){for(;M<H;)if(x=I(),x<9000000000000000)F[M++]=x%100000000000000}if(H=F[--M],R%=f,H&&R)x=m[f-R],F[M]=s(H/x)*x;for(;F[M]===0;F.pop(),M--);if(M<0)F=[U=0];else{for(U=-1;F[0]===0;F.splice(0,1),U-=f);for(M=1,x=F[0];x>=10;x/=10,M++);if(M<f)U-=f-M}return b.e=U,b.c=F,b}}(),K.sum=function(){var C=1,I=arguments,R=new K(I[0]);for(;C<I.length;)R=R.plus(I[C++]);return R},B=function(){var C="0123456789";function I(R,L,k,U){var H,x=[0],M,F=0,b=R.length;for(;F<b;){for(M=x.length;M--;x[M]*=L);x[0]+=U.indexOf(R.charAt(F++));for(H=0;H<x.length;H++)if(x[H]>k-1){if(x[H+1]==null)x[H+1]=0;x[H+1]+=x[H]/k|0,x[H]%=k}}return x.reverse()}return function(R,L,k,U,H){var x,M,F,b,J,j,ee,ce,ke=R.indexOf("."),Ge=Z,ue=ne;if(ke>=0)b=Xe,Xe=0,R=R.replace(".",""),ce=new K(L),j=ce.pow(R.length-ke),Xe=b,ce.c=I(N(T(j.c),j.e,"0"),10,k,C),ce.e=ce.c.length;ee=I(R,L,k,H?(x=ze,C):(x=C,ze)),F=b=ee.length;for(;ee[--b]==0;ee.pop());if(!ee[0])return x.charAt(0);if(ke<0)--F;else j.c=ee,j.e=F,j.s=U,j=O(j,ce,Ge,ue,k),ee=j.c,J=j.r,F=j.e;if(M=F+Ge+1,ke=ee[M],b=k/2,J=J||M<0||ee[M+1]!=null,J=ue<4?(ke!=null||J)&&(ue==0||ue==(j.s<0?3:2)):ke>b||ke==b&&(ue==4||J||ue==6&&ee[M-1]&1||ue==(j.s<0?8:7)),M<1||!ee[0])R=J?N(x.charAt(1),-Ge,x.charAt(0)):x.charAt(0);else{if(ee.length=M,J){for(--k;++ee[--M]>k;)if(ee[M]=0,!M)++F,ee=[1].concat(ee)}for(b=ee.length;!ee[--b];);for(ke=0,R="";ke<=b;R+=x.charAt(ee[ke++]));R=N(R,F,x.charAt(0))}return R}}(),O=function(){function C(L,k,U){var H,x,M,F,b=0,J=L.length,j=k%g,ee=k/g|0;for(L=L.slice();J--;)M=L[J]%g,F=L[J]/g|0,H=ee*M+F*j,x=j*M+H%g*g+b,b=(x/U|0)+(H/g|0)+ee*F,L[J]=x%U;if(b)L=[b].concat(L);return L}function I(L,k,U,H){var x,M;if(U!=H)M=U>H?1:-1;else for(x=M=0;x<U;x++)if(L[x]!=k[x]){M=L[x]>k[x]?1:-1;break}return M}function R(L,k,U,H){var x=0;for(;U--;)L[U]-=x,x=L[U]<k[U]?1:0,L[U]=x*H+L[U]-k[U];for(;!L[0]&&L.length>1;L.splice(0,1));}return function(L,k,U,H,x){var M,F,b,J,j,ee,ce,ke,Ge,ue,ye,He,Rr,Yi,Wi,Tt,jn,et=L.s==k.s?1:-1,Be=L.c,De=k.c;if(!Be||!Be[0]||!De||!De[0])return new K(!L.s||!k.s||(Be?De&&Be[0]==De[0]:!De)?NaN:Be&&Be[0]==0||!De?et*0:et/0);if(ke=new K(et),Ge=ke.c=[],F=L.e-k.e,et=U+F+1,!x)x=d,F=E(L.e/f)-E(k.e/f),et=et/f|0;for(b=0;De[b]==(Be[b]||0);b++);if(De[b]>(Be[b]||0))F--;if(et<0)Ge.push(1),J=!0;else{if(Yi=Be.length,Tt=De.length,b=0,et+=2,j=s(x/(De[0]+1)),j>1)De=C(De,j,x),Be=C(Be,j,x),Tt=De.length,Yi=Be.length;Rr=Tt,ue=Be.slice(0,Tt),ye=ue.length;for(;ye<Tt;ue[ye++]=0);if(jn=De.slice(),jn=[0].concat(jn),Wi=De[0],De[1]>=x/2)Wi++;do{if(j=0,M=I(De,ue,Tt,ye),M<0){if(He=ue[0],Tt!=ye)He=He*x+(ue[1]||0);if(j=s(He/Wi),j>1){if(j>=x)j=x-1;ee=C(De,j,x),ce=ee.length,ye=ue.length;while(I(ee,ue,ce,ye)==1)j--,R(ee,Tt<ce?jn:De,ce,x),ce=ee.length,M=1}else{if(j==0)M=j=1;ee=De.slice(),ce=ee.length}if(ce<ye)ee=[0].concat(ee);if(R(ue,ee,ye,x),ye=ue.length,M==-1)while(I(De,ue,Tt,ye)<1)j++,R(ue,Tt<ye?jn:De,ye,x),ye=ue.length}else if(M===0)j++,ue=[0];if(Ge[b++]=j,ue[0])ue[ye++]=Be[Rr]||0;else ue=[Be[Rr]],ye=1}while((Rr++<Yi||ue[0]!=null)&&et--);if(J=ue[0]!=null,!Ge[0])Ge.splice(0,1)}if(x==d){for(b=1,et=Ge[0];et>=10;et/=10,b++);je(ke,U+(ke.e=b+F*f-1)+1,H,J)}else ke.e=F,ke.r=+J;return ke}}();function Xi(C,I,R,L){var k,U,H,x,M;if(R==null)R=ne;else A(R,0,8);if(!C.c)return C.toString();if(k=C.c[0],H=C.e,I==null)M=T(C.c),M=L==1||L==2&&(H<=W||H>=V)?P(M,H):N(M,H,"0");else if(C=je(new K(C),I,R),U=C.e,M=T(C.c),x=M.length,L==1||L==2&&(I<=U||U<=W)){for(;x<I;M+="0",x++);M=P(M,U)}else if(I-=H+(L===2&&U>H),M=N(M,U,"0"),U+1>x){if(--I>0)for(M+=".";I--;M+="0");}else if(I+=U-x,I>0){if(U+1==x)M+=".";for(;I--;M+="0");}return C.s<0&&k?"-"+M:M}function ra(C,I){var R,L,k=1,U=new K(C[0]);for(;k<C.length;k++)if(L=new K(C[k]),!L.s||(R=S(U,L))===I||R===0&&U.s===I)U=L;return U}function Ki(C,I,R){var L=1,k=I.length;for(;!I[--k];I.pop());for(k=I[0];k>=10;k/=10,L++);if((R=L+R*f-1)>se)C.c=C.e=null;else if(R<oe)C.c=[C.e=0];else C.e=R,C.c=I;return C}X=function(){var C=/^(-?)0([xbo])(?=\w[\w.]*$)/i,I=/^([^.]+)\.$/,R=/^\.([^.]+)$/,L=/^-?(Infinity|NaN)$/,k=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(U,H,x,M){var F,b=x?H:H.replace(k,"");if(L.test(b))U.s=isNaN(b)?null:b<0?-1:1;else{if(!x){if(b=b.replace(C,function(J,j,ee){return F=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!M||M==F?j:J}),M)F=M,b=b.replace(I,"$1").replace(R,"0.$1");if(H!=b)return new K(b,F)}if(K.DEBUG)throw Error(a+"Not a"+(M?" base "+M:"")+" number: "+H);U.s=null}U.c=U.e=null}}();function je(C,I,R,L){var k,U,H,x,M,F,b,J=C.c,j=m;if(J){e:{for(k=1,x=J[0];x>=10;x/=10,k++);if(U=I-k,U<0)U+=f,H=I,M=J[F=0],b=s(M/j[k-H-1]%10);else if(F=o((U+1)/f),F>=J.length)if(L){for(;J.length<=F;J.push(0));M=b=0,k=1,U%=f,H=U-f+1}else break e;else{M=x=J[F];for(k=1;x>=10;x/=10,k++);U%=f,H=U-f+k,b=H<0?0:s(M/j[k-H-1]%10)}if(L=L||I<0||J[F+1]!=null||(H<0?M:M%j[k-H-1]),L=R<4?(b||L)&&(R==0||R==(C.s<0?3:2)):b>5||b==5&&(R==4||L||R==6&&(U>0?H>0?M/j[k-H]:0:J[F-1])%10&1||R==(C.s<0?8:7)),I<1||!J[0]){if(J.length=0,L)I-=C.e+1,J[0]=j[(f-I%f)%f],C.e=-I||0;else J[0]=C.e=0;return C}if(U==0)J.length=F,x=1,F--;else J.length=F+1,x=j[f-U],J[F]=H>0?s(M/j[k-H]%j[H])*x:0;if(L)for(;;)if(F==0){for(U=1,H=J[0];H>=10;H/=10,U++);H=J[0]+=x;for(x=1;H>=10;H/=10,x++);if(U!=x){if(C.e++,J[0]==d)J[0]=1}break}else{if(J[F]+=x,J[F]!=d)break;J[F--]=0,x=1}for(U=J.length;J[--U]===0;J.pop());}if(C.e>se)C.c=C.e=null;else if(C.e<oe)C.c=[C.e=0]}return C}function Dt(C){var I,R=C.e;if(R===null)return C.toString();return I=T(C.c),I=R<=W||R>=V?P(I,R):N(I,R,"0"),C.s<0?"-"+I:I}if(q.absoluteValue=q.abs=function(){var C=new K(this);if(C.s<0)C.s=1;return C},q.comparedTo=function(C,I){return S(this,new K(C,I))},q.decimalPlaces=q.dp=function(C,I){var R,L,k,U=this;if(C!=null){if(A(C,0,_),I==null)I=ne;else A(I,0,8);return je(new K(U),C+U.e+1,I)}if(!(R=U.c))return null;if(L=((k=R.length-1)-E(this.e/f))*f,k=R[k])for(;k%10==0;k/=10,L--);if(L<0)L=0;return L},q.dividedBy=q.div=function(C,I){return O(this,new K(C,I),Z,ne)},q.dividedToIntegerBy=q.idiv=function(C,I){return O(this,new K(C,I),0,1)},q.exponentiatedBy=q.pow=function(C,I){var R,L,k,U,H,x,M,F,b,J=this;if(C=new K(C),C.c&&!C.isInteger())throw Error(a+"Exponent not an integer: "+Dt(C));if(I!=null)I=new K(I);if(x=C.e>14,!J.c||!J.c[0]||J.c[0]==1&&!J.e&&J.c.length==1||!C.c||!C.c[0])return b=new K(Math.pow(+Dt(J),x?C.s*(2-w(C)):+Dt(C))),I?b.mod(I):b;if(M=C.s<0,I){if(I.c?!I.c[0]:!I.s)return new K(NaN);if(L=!M&&J.isInteger()&&I.isInteger(),L)J=J.mod(I)}else if(C.e>9&&(J.e>0||J.e<-1||(J.e==0?J.c[0]>1||x&&J.c[1]>=240000000:J.c[0]<80000000000000||x&&J.c[0]<=99999750000000))){if(U=J.s<0&&w(C)?-0:0,J.e>-1)U=1/U;return new K(M?1/U:U)}else if(Xe)U=o(Xe/f+2);if(x){if(R=new K(0.5),M)C.s=1;F=w(C)}else k=Math.abs(+Dt(C)),F=k%2;b=new K(Y);for(;;){if(F){if(b=b.times(J),!b.c)break;if(U){if(b.c.length>U)b.c.length=U}else if(L)b=b.mod(I)}if(k){if(k=s(k/2),k===0)break;F=k%2}else if(C=C.times(R),je(C,C.e+1,1),C.e>14)F=w(C);else{if(k=+Dt(C),k===0)break;F=k%2}if(J=J.times(J),U){if(J.c&&J.c.length>U)J.c.length=U}else if(L)J=J.mod(I)}if(L)return b;if(M)b=Y.div(b);return I?b.mod(I):U?je(b,Xe,ne,H):b},q.integerValue=function(C){var I=new K(this);if(C==null)C=ne;else A(C,0,8);return je(I,I.e+1,C)},q.isEqualTo=q.eq=function(C,I){return S(this,new K(C,I))===0},q.isFinite=function(){return!!this.c},q.isGreaterThan=q.gt=function(C,I){return S(this,new K(C,I))>0},q.isGreaterThanOrEqualTo=q.gte=function(C,I){return(I=S(this,new K(C,I)))===1||I===0},q.isInteger=function(){return!!this.c&&E(this.e/f)>this.c.length-2},q.isLessThan=q.lt=function(C,I){return S(this,new K(C,I))<0},q.isLessThanOrEqualTo=q.lte=function(C,I){return(I=S(this,new K(C,I)))===-1||I===0},q.isNaN=function(){return!this.s},q.isNegative=function(){return this.s<0},q.isPositive=function(){return this.s>0},q.isZero=function(){return!!this.c&&this.c[0]==0},q.minus=function(C,I){var R,L,k,U,H=this,x=H.s;if(C=new K(C,I),I=C.s,!x||!I)return new K(NaN);if(x!=I)return C.s=-I,H.plus(C);var M=H.e/f,F=C.e/f,b=H.c,J=C.c;if(!M||!F){if(!b||!J)return b?(C.s=-I,C):new K(J?H:NaN);if(!b[0]||!J[0])return J[0]?(C.s=-I,C):new K(b[0]?H:ne==3?-0:0)}if(M=E(M),F=E(F),b=b.slice(),x=M-F){if(U=x<0)x=-x,k=b;else F=M,k=J;k.reverse();for(I=x;I--;k.push(0));k.reverse()}else{L=(U=(x=b.length)<(I=J.length))?x:I;for(x=I=0;I<L;I++)if(b[I]!=J[I]){U=b[I]<J[I];break}}if(U)k=b,b=J,J=k,C.s=-C.s;if(I=(L=J.length)-(R=b.length),I>0)for(;I--;b[R++]=0);I=d-1;for(;L>x;){if(b[--L]<J[L]){for(R=L;R&&!b[--R];b[R]=I);--b[R],b[L]+=d}b[L]-=J[L]}for(;b[0]==0;b.splice(0,1),--F);if(!b[0])return C.s=ne==3?-1:1,C.c=[C.e=0],C;return Ki(C,b,F)},q.modulo=q.mod=function(C,I){var R,L,k=this;if(C=new K(C,I),!k.c||!C.s||C.c&&!C.c[0])return new K(NaN);else if(!C.c||k.c&&!k.c[0])return new K(k);if(Ue==9)L=C.s,C.s=1,R=O(k,C,0,3),C.s=L,R.s*=L;else R=O(k,C,0,Ue);if(C=k.minus(R.times(C)),!C.c[0]&&Ue==1)C.s=k.s;return C},q.multipliedBy=q.times=function(C,I){var R,L,k,U,H,x,M,F,b,J,j,ee,ce,ke,Ge,ue=this,ye=ue.c,He=(C=new K(C,I)).c;if(!ye||!He||!ye[0]||!He[0]){if(!ue.s||!C.s||ye&&!ye[0]&&!He||He&&!He[0]&&!ye)C.c=C.e=C.s=null;else if(C.s*=ue.s,!ye||!He)C.c=C.e=null;else C.c=[0],C.e=0;return C}if(L=E(ue.e/f)+E(C.e/f),C.s*=ue.s,M=ye.length,J=He.length,M<J)ce=ye,ye=He,He=ce,k=M,M=J,J=k;for(k=M+J,ce=[];k--;ce.push(0));ke=d,Ge=g;for(k=J;--k>=0;){R=0,j=He[k]%Ge,ee=He[k]/Ge|0;for(H=M,U=k+H;U>k;)F=ye[--H]%Ge,b=ye[H]/Ge|0,x=ee*F+b*j,F=j*F+x%Ge*Ge+ce[U]+R,R=(F/ke|0)+(x/Ge|0)+ee*b,ce[U--]=F%ke;ce[U]=R}if(R)++L;else ce.splice(0,1);return Ki(C,ce,L)},q.negated=function(){var C=new K(this);return C.s=-C.s||null,C},q.plus=function(C,I){var R,L=this,k=L.s;if(C=new K(C,I),I=C.s,!k||!I)return new K(NaN);if(k!=I)return C.s=-I,L.minus(C);var U=L.e/f,H=C.e/f,x=L.c,M=C.c;if(!U||!H){if(!x||!M)return new K(k/0);if(!x[0]||!M[0])return M[0]?C:new K(x[0]?L:k*0)}if(U=E(U),H=E(H),x=x.slice(),k=U-H){if(k>0)H=U,R=M;else k=-k,R=x;R.reverse();for(;k--;R.push(0));R.reverse()}if(k=x.length,I=M.length,k-I<0)R=M,M=x,x=R,I=k;for(k=0;I;)k=(x[--I]=x[I]+M[I]+k)/d|0,x[I]=d===x[I]?0:x[I]%d;if(k)x=[k].concat(x),++H;return Ki(C,x,H)},q.precision=q.sd=function(C,I){var R,L,k,U=this;if(C!=null&&C!==!!C){if(A(C,1,_),I==null)I=ne;else A(I,0,8);return je(new K(U),C,I)}if(!(R=U.c))return null;if(k=R.length-1,L=k*f+1,k=R[k]){for(;k%10==0;k/=10,L--);for(k=R[0];k>=10;k/=10,L++);}if(C&&U.e+1>L)L=U.e+1;return L},q.shiftedBy=function(C){return A(C,-h,h),this.times("1e"+C)},q.squareRoot=q.sqrt=function(){var C,I,R,L,k,U=this,{c:H,s:x,e:M}=U,F=Z+4,b=new K("0.5");if(x!==1||!H||!H[0])return new K(!x||x<0&&(!H||H[0])?NaN:H?U:1/0);if(x=Math.sqrt(+Dt(U)),x==0||x==1/0){if(I=T(H),(I.length+M)%2==0)I+="0";if(x=Math.sqrt(+I),M=E((M+1)/2)-(M<0||M%2),x==1/0)I="5e"+M;else I=x.toExponential(),I=I.slice(0,I.indexOf("e")+1)+M;R=new K(I)}else R=new K(x+"");if(R.c[0]){if(M=R.e,x=M+F,x<3)x=0;for(;;)if(k=R,R=b.times(k.plus(O(U,k,F,1))),T(k.c).slice(0,x)===(I=T(R.c)).slice(0,x)){if(R.e<M)--x;if(I=I.slice(x-3,x+1),I=="9999"||!L&&I=="4999"){if(!L){if(je(k,k.e+Z+2,0),k.times(k).eq(U)){R=k;break}}F+=4,x+=4,L=1}else{if(!+I||!+I.slice(1)&&I.charAt(0)=="5")je(R,R.e+Z+2,1),C=!R.times(R).eq(U);break}}}return je(R,R.e+Z+1,ne,C)},q.toExponential=function(C,I){if(C!=null)A(C,0,_),C++;return Xi(this,C,I,1)},q.toFixed=function(C,I){if(C!=null)A(C,0,_),C=C+this.e+1;return Xi(this,C,I)},q.toFormat=function(C,I,R){var L,k=this;if(R==null)if(C!=null&&I&&typeof I=="object")R=I,I=null;else if(C&&typeof C=="object")R=C,C=I=null;else R=be;else if(typeof R!="object")throw Error(a+"Argument not an object: "+R);if(L=k.toFixed(C,I),k.c){var U,H=L.split("."),x=+R.groupSize,M=+R.secondaryGroupSize,F=R.groupSeparator||"",b=H[0],J=H[1],j=k.s<0,ee=j?b.slice(1):b,ce=ee.length;if(M)U=x,x=M,M=U,ce-=U;if(x>0&&ce>0){U=ce%x||x,b=ee.substr(0,U);for(;U<ce;U+=x)b+=F+ee.substr(U,x);if(M>0)b+=F+ee.slice(U);if(j)b="-"+b}L=J?b+(R.decimalSeparator||"")+((M=+R.fractionGroupSize)?J.replace(new RegExp("\\d{"+M+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):J):b}return(R.prefix||"")+L+(R.suffix||"")},q.toFraction=function(C){var I,R,L,k,U,H,x,M,F,b,J,j,ee=this,ce=ee.c;if(C!=null){if(x=new K(C),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y))throw Error(a+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Dt(x))}if(!ce)return new K(ee);I=new K(Y),F=R=new K(Y),L=M=new K(Y),j=T(ce),U=I.e=j.length-ee.e-1,I.c[0]=m[(H=U%f)<0?f+H:H],C=!C||x.comparedTo(I)>0?U>0?I:F:x,H=se,se=1/0,x=new K(j),M.c[0]=0;for(;;){if(b=O(x,I,0,1),k=R.plus(b.times(L)),k.comparedTo(C)==1)break;R=L,L=k,F=M.plus(b.times(k=F)),M=k,I=x.minus(b.times(k=I)),x=k}return k=O(C.minus(R),L,0,1),M=M.plus(k.times(F)),R=R.plus(k.times(L)),M.s=F.s=ee.s,U=U*2,J=O(F,L,U,ne).minus(ee).abs().comparedTo(O(M,R,U,ne).minus(ee).abs())<1?[F,L]:[M,R],se=H,J},q.toNumber=function(){return+Dt(this)},q.toPrecision=function(C,I){if(C!=null)A(C,1,_);return Xi(this,C,I,2)},q.toString=function(C){var I,R=this,L=R.s,k=R.e;if(k===null)if(L){if(I="Infinity",L<0)I="-"+I}else I="NaN";else{if(C==null)I=k<=W||k>=V?P(T(R.c),k):N(T(R.c),k,"0");else if(C===10&&Ji)R=je(new K(R),Z+k+1,ne),I=N(T(R.c),R.e,"0");else A(C,2,ze.length,"Base"),I=B(N(T(R.c),k,"0"),10,C,L,!0);if(L<0&&R.c[0])I="-"+I}return I},q.valueOf=q.toJSON=function(){return Dt(this)},q._isBigNumber=!0,D!=null)K.set(D);return K}function E(D){var O=D|0;return D>0||D===O?O:O-1}function T(D){var O,B,X=1,q=D.length,Y=D[0]+"";for(;X<q;){O=D[X++]+"",B=f-O.length;for(;B--;O="0"+O);Y+=O}for(q=Y.length;Y.charCodeAt(--q)===48;);return Y.slice(0,q+1||1)}function S(D,O){var B,X,q=D.c,Y=O.c,Z=D.s,ne=O.s,W=D.e,V=O.e;if(!Z||!ne)return null;if(B=q&&!q[0],X=Y&&!Y[0],B||X)return B?X?0:-ne:Z;if(Z!=ne)return Z;if(B=Z<0,X=W==V,!q||!Y)return X?0:!q^B?1:-1;if(!X)return W>V^B?1:-1;ne=(W=q.length)<(V=Y.length)?W:V;for(Z=0;Z<ne;Z++)if(q[Z]!=Y[Z])return q[Z]>Y[Z]^B?1:-1;return W==V?0:W>V^B?1:-1}function A(D,O,B,X){if(D<O||D>B||D!==s(D))throw Error(a+(X||"Argument")+(typeof D=="number"?D<O||D>B?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function w(D){var O=D.c.length-1;return E(D.e/f)==O&&D.c[O]%2!=0}function P(D,O){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(O<0?"e":"e+")+O}function N(D,O,B){var X,q;if(O<0){for(q=B+".";++O;q+=B);D=q+D}else if(X=D.length,++O>X){for(q=B,O-=X;--O;q+=B);D+=q}else if(O<X)D=D.slice(0,O)+"."+D.slice(O);return D}if(t=v(),t.default=t.BigNumber=t,typeof define=="function"&&define.amd)define(function(){return t});else if(typeof Ur<"u"&&Ur.exports)Ur.exports=t;else{if(!e)e=typeof self<"u"&&self?self:window;e.BigNumber=t}})(Ua)});var qa=r(function(yN,La){var Ga=io(),ba=yN;(function(){function e(h){return h<10?"0"+h:h}var t=/[\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,o,s,a={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':"\\\"","\\":"\\\\"},c;function d(h){return n.lastIndex=0,n.test(h)?'"'+h.replace(n,function(m){var g=a[m];return typeof g==="string"?g:"\\u"+("0000"+m.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function f(h,m){var g,_,v,E,T=o,S,A=m[h],w=A!=null&&(A instanceof Ga||Ga.isBigNumber(A));if(A&&typeof A==="object"&&typeof A.toJSON==="function")A=A.toJSON(h);if(typeof c==="function")A=c.call(m,h,A);switch(typeof A){case"string":if(w)return A;else return d(A);case"number":return isFinite(A)?String(A):"null";case"boolean":case"null":case"bigint":return String(A);case"object":if(!A)return"null";if(o+=s,S=[],Object.prototype.toString.apply(A)==="[object Array]"){E=A.length;for(g=0;g<E;g+=1)S[g]=f(g,A)||"null";return v=S.length===0?"[]":o?`[
|
|
8
|
-
`+
|
|
9
|
-
`+
|
|
10
|
-
`+
|
|
11
|
-
`+
|
|
12
|
-
`+
|
|
13
|
-
`+
|
|
14
|
-
`,r:"\r",t:"\t"},a,c=function(T){throw{name:"SyntaxError",message:T,at:n,text:a}},d=function(T){if(T&&T!==o)c("Expected '"+T+"' instead of '"+o+"'");return o=a.charAt(n),n+=1,o},f=function(){var T,S="";if(o==="-")S="-",d("-");while(o>="0"&&o<="9")S+=o,d();if(o==="."){S+=".";while(d()&&o>="0"&&o<="9")S+=o}if(o==="e"||o==="E"){if(S+=o,d(),o==="-"||o==="+")S+=o,d();while(o>="0"&&o<="9")S+=o,d()}if(T=+S,!isFinite(T))c("Bad number");else{if(Gr==null)Gr=io();if(S.length>15)return t.storeAsString?S:t.useNativeBigInt?BigInt(S):new Gr(S);else return!t.alwaysParseAsBig?T:t.useNativeBigInt?BigInt(T):new Gr(T)}},h=function(){var T,S,A="",w;if(o==='"'){var P=n;while(d()){if(o==='"'){if(n-1>P)A+=a.substring(P,n-1);return d(),A}if(o==="\\"){if(n-1>P)A+=a.substring(P,n-1);if(d(),o==="u"){w=0;for(S=0;S<4;S+=1){if(T=parseInt(d(),16),!isFinite(T))break;w=w*16+T}A+=String.fromCharCode(w)}else if(typeof s[o]==="string")A+=s[o];else break;P=n}}}c("Bad string")},m=function(){while(o&&o<=" ")d()},g=function(){switch(o){case"t":return d("t"),d("r"),d("u"),d("e"),!0;case"f":return d("f"),d("a"),d("l"),d("s"),d("e"),!1;case"n":return d("n"),d("u"),d("l"),d("l"),null}c("Unexpected '"+o+"'")},_,v=function(){var T=[];if(o==="["){if(d("["),m(),o==="]")return d("]"),T;while(o){if(T.push(_()),m(),o==="]")return d("]"),T;d(","),m()}}c("Bad array")},E=function(){var T,S=Object.create(null);if(o==="{"){if(d("{"),m(),o==="}")return d("}"),S;while(o){if(T=h(),m(),d(":"),t.strict===!0&&Object.hasOwnProperty.call(S,T))c('Duplicate key "'+T+'"');if(ly.test(T)===!0)if(t.protoAction==="error")c("Object contains forbidden prototype property");else if(t.protoAction==="ignore")_();else S[T]=_();else if(uy.test(T)===!0)if(t.constructorAction==="error")c("Object contains forbidden constructor property");else if(t.constructorAction==="ignore")_();else S[T]=_();else S[T]=_();if(m(),o==="}")return d("}"),S;d(","),m()}}c("Bad object")};return _=function(){switch(m(),o){case"{":return E();case"[":return v();case'"':return h();case"-":return f();default:return o>="0"&&o<="9"?f():g()}},function(T,S){var A;if(a=T+"",n=0,o=" ",A=_(),m(),o)c("Syntax error");return typeof S==="function"?function w(P,N){var D,O,B=P[N];if(B&&typeof B==="object")Object.keys(B).forEach(function(X){if(O=w(B,X),O!==void 0)B[X]=O;else delete B[X]});return S.call(P,N,B)}({"":A},""):A}};Oa.exports=cy});var Ba=r(function(vN,Lr){var Ha=qa().stringify,Va=Fa();Lr.exports=function(e){return{parse:Va(e),stringify:Ha}};Lr.exports.parse=Va();Lr.exports.stringify=Ha});var oo=r(function(Ya){Object.defineProperty(Ya,"__esModule",{value:!0});Ya.GCE_LINUX_BIOS_PATHS=void 0;Ya.isGoogleCloudServerless=$a;Ya.isGoogleComputeEngineLinux=Ja;Ya.isGoogleComputeEngineMACAddress=Xa;Ya.isGoogleComputeEngine=Ka;Ya.detectGCPResidency=fy;var qr=p("fs"),Fr=p("os");Ya.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var dy=/^42:01/;function $a(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Ja(){if(Fr.platform()!=="linux")return!1;try{qr.statSync(Ya.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let e=qr.readFileSync(Ya.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(e)}catch{return!1}}function Xa(){let e=Fr.networkInterfaces();for(let t of Object.values(e)){if(!t)continue;for(let{mac:n}of t)if(dy.test(n))return!0}return!1}function Ka(){return Ja()||Xa()}function fy(){return $a()||Ka()}});var Qa=r(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});Wa.Colours=void 0;class le{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==="function"?e.getColorDepth()>2:!0)}static refresh(){if(le.enabled=le.isEnabled(process===null||process===void 0?void 0:process.stderr),!this.enabled)le.reset="",le.bright="",le.dim="",le.red="",le.green="",le.yellow="",le.blue="",le.magenta="",le.cyan="",le.white="",le.grey="";else le.reset="\x1B[0m",le.bright="\x1B[1m",le.dim="\x1B[2m",le.red="\x1B[31m",le.green="\x1B[32m",le.yellow="\x1B[33m",le.blue="\x1B[34m",le.magenta="\x1B[35m",le.cyan="\x1B[36m",le.white="\x1B[37m",le.grey="\x1B[90m"}}Wa.Colours=le;le.enabled=!1;le.reset="";le.bright="";le.dim="";le.red="";le.green="";le.yellow="";le.blue="";le.magenta="";le.cyan="";le.white="";le.grey="";le.refresh()});var ol=r(function(Ee){var yy=Ee&&Ee.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),Ey=Ee&&Ee.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Za=Ee&&Ee.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var o=[];for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))o[o.length]=s;return o},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null){for(var o=e(t),s=0;s<o.length;s++)if(o[s]!=="default")yy(n,t,o[s])}return Ey(n,t),n}}();Object.defineProperty(Ee,"__esModule",{value:!0});Ee.env=Ee.DebugLogBackendBase=Ee.placeholder=Ee.AdhocDebugLogger=Ee.LogSeverity=void 0;Ee.getNodeBackend=so;Ee.getDebugBackend=vy;Ee.getStructuredBackend=Ty;Ee.setBackend=Ay;Ee.log=il;var ja=p("events"),er=Za(p("process")),el=Za(p("util")),we=Qa(),ht;(function(e){e.DEFAULT="DEFAULT",e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR"})(ht||(Ee.LogSeverity=ht={}));class Hr extends ja.EventEmitter{constructor(e,t){super();this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(ht.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(ht.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(ht.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(ht.ERROR,...n),this.func.sublog=(n)=>il(n,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(n){}try{this.emit("log",e,t)}catch(n){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}Ee.AdhocDebugLogger=Hr;Ee.placeholder=new Hr("",()=>{}).func;class tr{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=er.env[Ee.env.nodeEnables])!==null&&e!==void 0?e:"*";if(t==="all")t="*";this.filters=t.split(",")}log(e,t,...n){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let o=this.cached.get(e);if(!o)o=this.makeLogger(e),this.cached.set(e,o);o(t,...n)}catch(o){console.error(o)}}}Ee.DebugLogBackendBase=tr;class tl extends tr{constructor(){super(...arguments);this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){if(!this.enabledRegexp.test(e))return()=>{};return(t,...n)=>{var o;let s=`${we.Colours.green}${e}${we.Colours.reset}`,a=`${we.Colours.yellow}${er.pid}${we.Colours.reset}`,c;switch(t.severity){case ht.ERROR:c=`${we.Colours.red}${t.severity}${we.Colours.reset}`;break;case ht.INFO:c=`${we.Colours.magenta}${t.severity}${we.Colours.reset}`;break;case ht.WARNING:c=`${we.Colours.yellow}${t.severity}${we.Colours.reset}`;break;default:c=(o=t.severity)!==null&&o!==void 0?o:ht.DEFAULT;break}let d=el.formatWithOptions({colors:we.Colours.enabled},...n),f=Object.assign({},t);delete f.severity;let h=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",m=h?`${we.Colours.grey}${h}${we.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,d,h?` ${m}`:"")}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}}function so(){return new tl}class nl extends tr{constructor(e){super();this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(n,...o)=>{t(o[0],...o.slice(1))}}setFilters(){var e;let t=(e=er.env.NODE_DEBUG)!==null&&e!==void 0?e:"";er.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}}function vy(e){return new nl(e)}class rl extends tr{constructor(e){var t;super();this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let n=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:ht.INFO,d=Object.assign({severity:c,message:el.format(...s)},o),f=JSON.stringify(d);if(n)n(o,f);else console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}}function Ty(e){return new rl(e)}Ee.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var ao=new Map,Qe=void 0;function Ay(e){Qe=e,ao.clear()}function il(e,t){if(!Qe){if(!er.env[Ee.env.nodeEnables])return Ee.placeholder}if(!e)return Ee.placeholder;if(t)e=`${t.instance.namespace}:${e}`;let n=ao.get(e);if(n)return n.func;if(Qe===null)return Ee.placeholder;else if(Qe===void 0)Qe=so();let o=(()=>{let s=void 0;return new Hr(e,(c,...d)=>{if(s!==Qe){if(Qe===null)return;else if(Qe===void 0)Qe=so();s=Qe}Qe===null||Qe===void 0||Qe.log(e,c,...d)})})();return ao.set(e,o),o.func}});var lo=r(function(gn){var Cy=gn&&gn.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),Sy=gn&&gn.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))Cy(t,e,n)};Object.defineProperty(gn,"__esModule",{value:!0});Sy(ol(),gn)});var rr=r(function(te){var al=te&&te.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),Iy=te&&te.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),wy=te&&te.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var o=[];for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))o[o.length]=s;return o},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null){for(var o=e(t),s=0;s<o.length;s++)if(o[s]!=="default")al(n,t,o[s])}return Iy(n,t),n}}(),Ry=te&&te.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))al(t,e,n)};Object.defineProperty(te,"__esModule",{value:!0});te.gcpResidencyCache=te.METADATA_SERVER_DETECTION=te.HEADERS=te.HEADER_VALUE=te.HEADER_NAME=te.SECONDARY_HOST_ADDRESS=te.HOST_ADDRESS=te.BASE_PATH=void 0;te.instance=ky;te.project=Dy;te.universe=My;te.bulk=Uy;te.isAvailable=by;te.resetIsAvailableCache=Ly;te.getGCPResidency=co;te.setGCPResidency=cl;te.requestTimeout=dl;var Cn=qe(),ll=Ba(),ul=oo(),Py=wy(lo());te.BASE_PATH="/computeMetadata/v1";te.HOST_ADDRESS="http://169.254.169.254";te.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";te.HEADER_NAME="Metadata-Flavor";te.HEADER_VALUE="Google";te.HEADERS=Object.freeze({[te.HEADER_NAME]:te.HEADER_VALUE});var sl=Py.log("gcp-metadata");te.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 uo(e){if(!e)e=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||te.HOST_ADDRESS;if(!/^https?:\/\//.test(e))e=`http://${e}`;return new URL(te.BASE_PATH,e).href}function Ny(e){Object.keys(e).forEach((t)=>{switch(t){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${t}' is not a valid configuration option.`)}})}async function nr(e,t={},n=3,o=!1){let s=new Headers(te.HEADERS),a="",c={};if(typeof e==="object"){let g=e;new Headers(g.headers).forEach((_,v)=>s.set(v,_)),a=g.metadataKey,c=g.params||c,n=g.noResponseRetries||n,o=g.fastFail||o}else a=e;if(typeof t==="string")a+=`/${t}`;else{if(Ny(t),t.property)a+=`/${t.property}`;new Headers(t.headers).forEach((g,_)=>s.set(_,g)),c=t.params||c}let d=o?xy:Cn.request,f={url:`${uo()}/${a}`,headers:s,retryConfig:{noResponseRetries:n},params:c,responseType:"text",timeout:dl()};sl.info("instance request %j",f);let h=await d(f);sl.info("instance metadata is %s",h.data);let m=h.headers.get(te.HEADER_NAME);if(m!==te.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${te.HEADER_NAME} header. Expected '${te.HEADER_VALUE}', got ${m?`'${m}'`:"no header"}`);if(typeof h.data==="string")try{return ll.parse(h.data)}catch{}return h.data}async function xy(e){let t={...e,url:e.url?.toString().replace(uo(),uo(te.SECONDARY_HOST_ADDRESS))},n=Cn.request(e),o=Cn.request(t);return Promise.any([n,o])}function ky(e){return nr("instance",e)}function Dy(e){return nr("project",e)}function My(e){return nr("universe",e)}async function Uy(e){let t={};return await Promise.all(e.map((n)=>(async()=>{let o=await nr(n),s=n.metadataKey;t[s]=o})())),t}function Gy(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Vr;async function by(){if(process.env.METADATA_SERVER_DETECTION){let e=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(e in te.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${e}\`, but it should be \`${Object.keys(te.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(e){case"assume-present":return!0;case"none":return!1;case"bios-only":return co();case"ping-only":}}try{if(Vr===void 0)Vr=nr("instance",void 0,Gy(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST));return await Vr,!0}catch(e){let t=e;if(process.env.DEBUG_AUTH)console.info(t);if(t.type==="request-timeout")return!1;if(t.response&&t.response.status===404)return!1;else{if(!(t.response&&t.response.status===404)&&(!t.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(t.code.toString()))){let n="UNKNOWN";if(t.code)n=t.code.toString();process.emitWarning(`received unexpected error = ${t.message} code = ${n}`,"MetadataLookupWarning")}return!1}}}function Ly(){Vr=void 0}te.gcpResidencyCache=null;function co(){if(te.gcpResidencyCache===null)cl();return te.gcpResidencyCache}function cl(e=null){te.gcpResidencyCache=e!==null?e:ul.detectGCPResidency()}function dl(){return co()?0:3000}Ry(oo(),te)});var pl=r(function(Jy){Jy.byteLength=Oy;Jy.toByteArray=Hy;Jy.fromByteArray=$y;var At=[],rt=[],qy=typeof Uint8Array<"u"?Uint8Array:Array,fo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ht=0,po=fo.length;Ht<po;++Ht)At[Ht]=fo[Ht],rt[fo.charCodeAt(Ht)]=Ht;var Ht,po;rt[45]=62;rt[95]=63;function fl(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");if(n===-1)n=t;var o=n===t?0:4-n%4;return[n,o]}function Oy(e){var t=fl(e),n=t[0],o=t[1];return(n+o)*3/4-o}function Fy(e,t,n){return(t+n)*3/4-n}function Hy(e){var t,n=fl(e),o=n[0],s=n[1],a=new qy(Fy(e,o,s)),c=0,d=s>0?o-4:o,f;for(f=0;f<d;f+=4)t=rt[e.charCodeAt(f)]<<18|rt[e.charCodeAt(f+1)]<<12|rt[e.charCodeAt(f+2)]<<6|rt[e.charCodeAt(f+3)],a[c++]=t>>16&255,a[c++]=t>>8&255,a[c++]=t&255;if(s===2)t=rt[e.charCodeAt(f)]<<2|rt[e.charCodeAt(f+1)]>>4,a[c++]=t&255;if(s===1)t=rt[e.charCodeAt(f)]<<10|rt[e.charCodeAt(f+1)]<<4|rt[e.charCodeAt(f+2)]>>2,a[c++]=t>>8&255,a[c++]=t&255;return a}function Vy(e){return At[e>>18&63]+At[e>>12&63]+At[e>>6&63]+At[e&63]}function By(e,t,n){var o,s=[];for(var a=t;a<n;a+=3)o=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),s.push(Vy(o));return s.join("")}function $y(e){var t,n=e.length,o=n%3,s=[],a=16383;for(var c=0,d=n-o;c<d;c+=a)s.push(By(e,c,c+a>d?d:c+a));if(o===1)t=e[n-1],s.push(At[t>>2]+At[t<<4&63]+"==");else if(o===2)t=(e[n-2]<<8)+e[n-1],s.push(At[t>>10]+At[t>>4&63]+At[t<<2&63]+"=");return s.join("")}});var ho=r(function(hl){Object.defineProperty(hl,"__esModule",{value:!0});hl.fromArrayBufferToHex=Wy;function Wy(e){return Array.from(new Uint8Array(e)).map((n)=>n.toString(16).padStart(2,"0")).join("")}});var yl=r(function(gl){Object.defineProperty(gl,"__esModule",{value:!0});gl.BrowserCrypto=void 0;var it=pl(),ml=ho();class Br{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return it.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),it.fromByteArray(t)}static padBase64(e){while(e.length%4!==0)e+="=";return e}async verify(e,t,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(t),a=it.toByteArray(Br.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,Buffer.from(a),s)}async sign(e,t){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(t),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),a=await window.crypto.subtle.sign(n,s,o);return it.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let t=it.toByteArray(Br.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return it.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return ml.fromArrayBufferToHex(n)}async signWithHmacSha256(e,t){let n=typeof e==="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(t))}}gl.BrowserCrypto=Br});var Al=r(function(vl){Object.defineProperty(vl,"__esModule",{value:!0});vl.NodeCrypto=void 0;var ot=p("crypto");class El{async sha256DigestBase64(e){return ot.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ot.randomBytes(e).toString("base64")}async verify(e,t,n){let o=ot.createVerify("RSA-SHA256");return o.update(t),o.end(),o.verify(e,n,"base64")}async sign(e,t){let n=ot.createSign("RSA-SHA256");return n.update(t),n.end(),n.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 ot.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let n=typeof e==="string"?e:Zy(e);return Qy(ot.createHmac("sha256",n).update(t).digest())}}vl.NodeCrypto=El;function Qy(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;++o)n[o]=e[o];return t}function Zy(e){return Buffer.from(e)}});var ir=r(function(Mt){var jy=Mt&&Mt.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),eE=Mt&&Mt.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))jy(t,e,n)};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.createCrypto=tE;Mt.hasBrowserCrypto=Il;var Cl=yl(),Sl=Al();eE(ho(),Mt);function tE(){if(Il())return new Cl.BrowserCrypto;return new Sl.NodeCrypto}function Il(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Sn=r(function(mo,Rl){/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var $r=p("buffer"),Ct=$r.Buffer;function wl(e,t){for(var n in e)t[n]=e[n]}if(Ct.from&&Ct.alloc&&Ct.allocUnsafe&&Ct.allocUnsafeSlow)Rl.exports=$r;else wl($r,mo),mo.Buffer=_n;function _n(e,t,n){return Ct(e,t,n)}_n.prototype=Object.create(Ct.prototype);wl(Ct,_n);_n.from=function(e,t,n){if(typeof e==="number")throw TypeError("Argument must not be a number");return Ct(e,t,n)};_n.alloc=function(e,t,n){if(typeof e!=="number")throw TypeError("Argument must be a number");var o=Ct(e);if(t!==void 0)if(typeof n==="string")o.fill(t,n);else o.fill(t);else o.fill(0);return o};_n.allocUnsafe=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return Ct(e)};_n.allocUnsafeSlow=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return $r.SlowBuffer(e)}});var Nl=r(function(kN,Pl){function go(e){var t=(e/8|0)+(e%8===0?0:1);return t}var nE={ES256:go(256),ES384:go(384),ES512:go(521)};function rE(e){var t=nE[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}Pl.exports=rE});var _o=r(function(DN,Gl){var Jr=Sn().Buffer,kl=Nl(),Xr=128,Dl=0,iE=32,oE=16,sE=2,Ml=oE|iE|Dl<<6,Kr=sE|Dl<<6;function aE(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ul(e){if(Jr.isBuffer(e))return e;else if(typeof e==="string")return Jr.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function lE(e,t){e=Ul(e);var n=kl(t),o=n+1,s=e.length,a=0;if(e[a++]!==Ml)throw Error('Could not find expected "seq"');var c=e[a++];if(c===(Xr|1))c=e[a++];if(s-a<c)throw Error('"seq" specified length of "'+c+'", only "'+(s-a)+'" remaining');if(e[a++]!==Kr)throw Error('Could not find expected "int" for "r"');var d=e[a++];if(s-a-2<d)throw Error('"r" specified length of "'+d+'", only "'+(s-a-2)+'" available');if(o<d)throw Error('"r" specified length of "'+d+'", max of "'+o+'" is acceptable');var f=a;if(a+=d,e[a++]!==Kr)throw Error('Could not find expected "int" for "s"');var h=e[a++];if(s-a!==h)throw Error('"s" specified length of "'+h+'", expected "'+(s-a)+'"');if(o<h)throw Error('"s" specified length of "'+h+'", max of "'+o+'" is acceptable');var m=a;if(a+=h,a!==s)throw Error('Expected to consume entire buffer, but "'+(s-a)+'" bytes remain');var g=n-d,_=n-h,v=Jr.allocUnsafe(g+d+_+h);for(a=0;a<g;++a)v[a]=0;e.copy(v,a,f+Math.max(-g,0),f+d),a=n;for(var E=a;a<E+_;++a)v[a]=0;return e.copy(v,a,m+Math.max(-_,0),m+h),v=v.toString("base64"),v=aE(v),v}function xl(e,t,n){var o=0;while(t+o<n&&e[t+o]===0)++o;var s=e[t+o]>=Xr;if(s)--o;return o}function uE(e,t){e=Ul(e);var n=kl(t),o=e.length;if(o!==n*2)throw TypeError('"'+t+'" signatures must be "'+n*2+'" bytes, saw "'+o+'"');var s=xl(e,0,n),a=xl(e,n,e.length),c=n-s,d=n-a,f=2+c+1+1+d,h=f<Xr,m=Jr.allocUnsafe((h?2:3)+f),g=0;if(m[g++]=Ml,h)m[g++]=f;else m[g++]=Xr|1,m[g++]=f&255;if(m[g++]=Kr,m[g++]=c,s<0)m[g++]=0,g+=e.copy(m,g,0,n);else g+=e.copy(m,g,s,n);if(m[g++]=Kr,m[g++]=d,a<0)m[g++]=0,e.copy(m,g,n);else e.copy(m,g,n+a);return m}Gl.exports={derToJose:lE,joseToDer:uE}});var mt=r(function(Hl){Object.defineProperty(Hl,"__esModule",{value:!0});Hl.LRUCache=void 0;Hl.snakeToCamel=Ol;Hl.originalOrCamelOptions=dE;Hl.removeUndefinedValuesInObject=fE;Hl.isValidFile=pE;Hl.getWellKnownCertificateConfigFileLocation=hE;var Ll=p("fs"),ql=p("os"),In=p("path"),cE="certificate_config.json",bl="gcloud";function Ol(e){return e.replace(/([_][^_])/g,(t)=>t.slice(1).toUpperCase())}function dE(e){function t(n){let o=e||{};return o[n]??o[Ol(n)]}return{get:t}}class Fl{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#n()}get(e){let t=this.#e.get(e);if(!t)return;return this.#t(e,t.value),this.#n(),t.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();while(!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed<e))this.#e.delete(t.value[0]),t=this.#e.entries().next()}}Hl.LRUCache=Fl;function fE(e){return Object.entries(e).forEach(([t,n])=>{if(n===void 0||n==="undefined")delete e[t]}),e}async function pE(e){try{return(await Ll.promises.lstat(e)).isFile()}catch(t){return!1}}function hE(){let e=process.env.CLOUDSDK_CONFIG||(mE()?In.join(process.env.APPDATA||"",bl):In.join(process.env.HOME||"",".config",bl));return In.join(e,cE)}function mE(){return ql.platform().startsWith("win")}});var Bl=r(function(UN,TE){TE.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var Eo=r(function(Jl){Object.defineProperty(Jl,"__esModule",{value:!0});Jl.USER_AGENT=Jl.PRODUCT_NAME=Jl.pkg=void 0;var yo=Bl();Jl.pkg=yo;var $l="google-api-nodejs-client";Jl.PRODUCT_NAME=$l;var AE=`${$l}/${yo.version}`;Jl.USER_AGENT=AE});var Ze=r(function(zl){Object.defineProperty(zl,"__esModule",{value:!0});zl.AuthClient=zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=zl.DEFAULT_UNIVERSE=void 0;var Kl=p("events"),wn=qe(),Yl=mt(),Wl=lo(),Rn=Eo();zl.DEFAULT_UNIVERSE="googleapis.com";zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300000;class Fe extends Kl.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=zl.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=Yl.originalOrCamelOptions(e);if(this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??zl.DEFAULT_UNIVERSE,this.transporter=e.transporter??new wn.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1)this.transporter.interceptors.request.add(Fe.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(Fe.DEFAULT_RESPONSE_INTERCEPTOR);if(e.eagerRefreshThresholdMillis)this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],o=void 0,s=new Headers;if(typeof t==="string")o=new URL(t);else if(t instanceof URL)o=t;else if(t&&t.url)o=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)wn.Gaxios.mergeHeaders(s,t.headers);if(n)wn.Gaxios.mergeHeaders(s,new Headers(n.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...n,...t,headers:s,url:o});else return this.request({...n,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){if(!e.has("x-goog-user-project")&&this.quotaProjectId)e.set("x-goog-user-project",this.quotaProjectId);return e}addUserProjectAndAuthHeaders(e,t){let n=t.get("x-goog-user-project"),o=t.get("authorization");if(n)e.set("x-goog-user-project",n);if(o)e.set("authorization",o);return e}static log=Wl.log("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async(e)=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let t=e.headers.get("User-Agent");if(!t)e.headers.set("User-Agent",Rn.USER_AGENT);else if(!t.includes(`${Rn.PRODUCT_NAME}/`))e.headers.set("User-Agent",`${t} ${Rn.USER_AGENT}`);try{let n=e,o=n[Fe.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1000)}`;n[Fe.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};if(o)Fe.log.info("%s [%s] request %j",o,s,a);else Fe.log.info("[%s] request %j",s,a)}catch(n){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async(e)=>{try{let t=e.config,n=t[Fe.RequestMethodNameSymbol],o=t[Fe.RequestLogIdSymbol];if(n)Fe.log.info("%s [%s] response %j",n,o,e.data);else Fe.log.info("[%s] response %j",o,e.data)}catch(t){}return e},rejected:async(e)=>{try{let t=e.config,n=t[Fe.RequestMethodNameSymbol],o=t[Fe.RequestLogIdSymbol];if(n)Fe.log.info("%s [%s] error %j",n,o,e.response?.data);else Fe.log.error("[%s] error %j",o,e.response?.data)}catch(t){}throw e}};static setMethodName(e,t){try{let n=e;n[Fe.RequestMethodNameSymbol]=t}catch(n){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}zl.AuthClient=Fe});var To=r(function(eu){Object.defineProperty(eu,"__esModule",{value:!0});eu.LoginTicket=void 0;class jl{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();if(e&&e.sub)return e.sub;return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}eu.LoginTicket=jl});var Bt=r(function(au){Object.defineProperty(au,"__esModule",{value:!0});au.OAuth2Client=au.ClientAuthentication=au.CertificateFormat=au.CodeChallengeMethod=void 0;var Yr=qe(),ru=p("querystring"),iu=p("stream"),ou=_o(),Wr=mt(),Pn=ir(),at=Ze(),su=To(),nu;(function(e){e.Plain="plain",e.S256="S256"})(nu||(au.CodeChallengeMethod=nu={}));var Ut;(function(e){e.PEM="PEM",e.JWK="JWK"})(Ut||(au.CertificateFormat=Ut={}));var or;(function(e){e.ClientSecretPost="ClientSecretPost",e.ClientSecretBasic="ClientSecretBasic",e.None="None"})(or||(au.ClientAuthentication=or={}));class st extends at.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ut.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e==="object"?e:{});if(typeof e!=="object")e={clientId:e,clientSecret:t,redirectUri:n};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||or.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 Error("If a code_challenge_method is provided, code_challenge must be included.");if(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(" ");return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+ru.stringify(e)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=Pn.createCrypto(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:s}}getToken(e,t){let n=typeof e==="string"?{code:e}:e;if(t)this.getTokenAsync(n).then((o)=>t(null,o.tokens,o.res),(o)=>t(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),n=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===or.ClientSecretBasic){let d=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${d.toString("base64")}`)}if(this.clientAuthentication===or.ClientSecretPost)o.client_secret=this._clientSecret;let s={...st.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(Wr.removeUndefinedValuesInObject(o)),headers:n};at.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;if(a.data&&a.data.expires_in)c.expiry_date=new Date().getTime()+a.data.expires_in*1000,delete c.expires_in;return this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then((n)=>(this.refreshTokenPromises.delete(e),n),(n)=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...st.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(Wr.removeUndefinedValuesInObject(n))};at.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){if(a instanceof Yr.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description))a.message=JSON.stringify(a.response.data);throw a}let s=o.data;if(o.data&&o.data.expires_in)s.expiry_date=new Date().getTime()+o.data.expires_in*1000,delete s.expires_in;return this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then((t)=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then((t)=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let c=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let d=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(d)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(t.refresh_token),o=n.tokens}catch(c){let d=c;if(d.response&&(d.response.status===403||d.response.status===404))d.message=`Could not refresh access token: ${d.message}`;throw d}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:n.res}}static getRevokeTokenUrl(e){return new st().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let n={...st.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(at.AuthClient.setMethodName(n,"revokeToken"),t)this.transporter.request(n).then((o)=>t(null,o),t);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then((t)=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);else throw Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let n=await this.getRequestMetadataAsync();if(e.headers=Yr.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey)e.headers.set("X-Goog-Api-Key",this.apiKey);return await this.transporter.request(e)}catch(n){let o=n.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,d=o.config.data instanceof iu.Readable,f=s===401||s===403;if(!t&&f&&!d&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);else if(!t&&f&&!d&&c){let h=await this.processAndValidateRefreshHandler();if(h?.access_token)this.setCredentials(h);return this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!=="function")throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then((n)=>t(null,n),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...st.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1000,scopes:t.scope.split(" ")},t);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then((t)=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=Pn.hasBrowserCrypto()?Ut.JWK:Ut.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===t)return{certs:this.certificateCache,format:t};let n,o;switch(t){case Ut.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ut.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${t}`)}try{let f={...st.RETRY_CONFIG,url:o};at.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),n=await this.transporter.request(f)}catch(f){if(f instanceof Error)f.message=`Failed to retrieve verification certificates: ${f.message}`;throw f}let s=n?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;if(f)a=Number(f)*1000}let c={};switch(t){case Ut.PEM:c=n.data;break;case Ut.JWK:for(let f of n.data.keys)c[f.kid]=f;break;default:throw Error(`Unsupported certificate format ${t}`)}let d=new Date;return this.certificateExpiry=a===-1?null:new Date(d.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=t,{certs:c,format:t,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then((t)=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...st.RETRY_CONFIG,url:t};at.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){if(n instanceof Error)n.message=`Failed to retrieve verification certificates: ${n.message}`;throw n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,n,o,s){let a=Pn.createCrypto();if(!s)s=st.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let c=e.split(".");if(c.length!==3)throw Error("Wrong number of segments in token: "+e);let d=c[0]+"."+c[1],f=c[2],h,m;try{h=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(w){if(w instanceof Error)w.message=`Can't parse token envelope: ${c[0]}': ${w.message}`;throw w}if(!h)throw Error("Can't parse token envelope: "+c[0]);try{m=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(w){if(w instanceof Error)w.message=`Can't parse token payload '${c[0]}`;throw w}if(!m)throw Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(t,h.kid))throw Error("No pem found for envelope: "+JSON.stringify(h));let g=t[h.kid];if(h.alg==="ES256")f=ou.joseToDer(f,"ES256").toString("base64");if(!await a.verify(g,d,f))throw Error("Invalid token signature: "+e);if(!m.iat)throw Error("No issue time in token: "+JSON.stringify(m));if(!m.exp)throw Error("No expiration time in token: "+JSON.stringify(m));let v=Number(m.iat);if(isNaN(v))throw Error("iat field using invalid format");let E=Number(m.exp);if(isNaN(E))throw Error("exp field using invalid format");let T=new Date().getTime()/1000;if(E>=T+s)throw Error("Expiration time too far in future: "+JSON.stringify(m));let S=v-st.CLOCK_SKEW_SECS_,A=E+st.CLOCK_SKEW_SECS_;if(T<S)throw Error("Token used too early, "+T+" < "+S+": "+JSON.stringify(m));if(T>A)throw Error("Token used too late, "+T+" > "+A+": "+JSON.stringify(m));if(o&&o.indexOf(m.iss)<0)throw Error("Invalid issuer, expected one of ["+o+"], but got "+m.iss);if(typeof n<"u"&&n!==null){let w=m.aud,P=!1;if(n.constructor===Array)P=n.indexOf(w)>-1;else P=w===n;if(!P)throw Error("Wrong recipient, payload audience != requiredAudience")}return new su.LoginTicket(h,m)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error("No access token is returned by the refreshHandler callback.");return e}return}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}au.OAuth2Client=st});var Ao=r(function(fu){Object.defineProperty(fu,"__esModule",{value:!0});fu.Compute=void 0;var uu=qe(),zr=rr(),cu=Bt();class du extends cu.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`,t;try{let o={property:e};if(this.scopes.length>0)o.params={scopes:this.scopes.join(",")};t=await zr.instance(o)}catch(o){if(o instanceof uu.GaxiosError)o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o);throw o}let n=t;if(t&&t.expires_in)n.expiry_date=new Date().getTime()+t.expires_in*1000,delete n.expires_in;return this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{n=await zr.instance({property:t})}catch(o){if(o instanceof Error)o.message=`Could not fetch ID token: ${o.message}`;throw o}return n}wrapError(e){let t=e.response;if(t&&t.status){if(e.status=t.status,t.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;else if(t.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}}}fu.Compute=du});var Co=r(function(gu){Object.defineProperty(gu,"__esModule",{value:!0});gu.IdTokenClient=void 0;var hu=Bt();class mu extends hu.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 t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1000}}gu.IdTokenClient=mu});var So=r(function(yu){Object.defineProperty(yu,"__esModule",{value:!0});yu.GCPEnv=void 0;yu.clear=PE;yu.getEnv=NE;var Qr=rr(),St;(function(e){e.APP_ENGINE="APP_ENGINE",e.KUBERNETES_ENGINE="KUBERNETES_ENGINE",e.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",e.COMPUTE_ENGINE="COMPUTE_ENGINE",e.CLOUD_RUN="CLOUD_RUN",e.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",e.NONE="NONE"})(St||(yu.GCPEnv=St={}));var sr;function PE(){sr=void 0}async function NE(){if(sr)return sr;return sr=xE(),sr}async function xE(){let e=St.NONE;if(kE())e=St.APP_ENGINE;else if(DE())e=St.CLOUD_FUNCTIONS;else if(await bE())if(await GE())e=St.KUBERNETES_ENGINE;else if(ME())e=St.CLOUD_RUN;else if(UE())e=St.CLOUD_RUN_JOBS;else e=St.COMPUTE_ENGINE;else e=St.NONE;return e}function kE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function DE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function ME(){return!!process.env.K_CONFIGURATION}function UE(){return!!process.env.CLOUD_RUN_JOB}async function GE(){try{return await Qr.instance("attributes/cluster-name"),!0}catch(e){return!1}}async function bE(){return Qr.isAvailable()}});var Io=r(function(VN,vu){var Zr=Sn().Buffer,OE=p("stream"),FE=p("util");function jr(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=Zr.alloc(0),this;if(typeof e.pipe==="function")return this.buffer=Zr.alloc(0),e.pipe(this),this;if(e.length||typeof e==="object")return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}FE.inherits(jr,OE);jr.prototype.write=function(t){this.buffer=Zr.concat([this.buffer,Zr.from(t)]),this.emit("data",t)};jr.prototype.end=function(t){if(t)this.write(t);this.emit("end",t),this.emit("close"),this.writable=!1,this.readable=!1};vu.exports=jr});var Au=r(function(BN,Tu){var ar=p("buffer").Buffer,wo=p("buffer").SlowBuffer;Tu.exports=ei;function ei(e,t){if(!ar.isBuffer(e)||!ar.isBuffer(t))return!1;if(e.length!==t.length)return!1;var n=0;for(var o=0;o<e.length;o++)n|=e[o]^t[o];return n===0}ei.install=function(){ar.prototype.equal=wo.prototype.equal=function(t){return ei(this,t)}};var HE=ar.prototype.equal,VE=wo.prototype.equal;ei.restore=function(){ar.prototype.equal=HE,wo.prototype.equal=VE}});var xo=r(function($N,ku){var xn=Sn().Buffer,lt=p("crypto"),Su=_o(),Cu=p("util"),BE=`"%s" is not a valid algorithm.
|
|
6
|
+
`,typeof i.content==="string")yield i.content;else yield*i.content;yield`\r
|
|
7
|
+
`}yield n}static#o;static#s;static async#a(){return this.#o||=(await import("./chunk-2eaehpp6.js").then((m)=>a(m.default))).HttpsProxyAgent,this.#o}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("node-fetch")).default,this.#s}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((o,s)=>{s==="set-cookie"?e.append(s,o):e.set(s,o)});return e}}An.Gaxios=ro;Tn=ro});var Oe=r(function($e){var iy=$e&&$e.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),oy=$e&&$e.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))iy(t,e,n)};Object.defineProperty($e,"__esModule",{value:!0});$e.instance=$e.Gaxios=$e.GaxiosError=void 0;$e.request=ay;var Ur=Ma();Object.defineProperty($e,"Gaxios",{enumerable:!0,get:function(){return Ur.Gaxios}});var sy=to();Object.defineProperty($e,"GaxiosError",{enumerable:!0,get:function(){return sy.GaxiosError}});oy(no(),$e);$e.instance=new Ur.Gaxios;async function ay(e){return $e.instance.request(e)}});var io=r(function(Ua,Gr){(function(e){var t,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,{ceil:i,floor:o}=Math,s="[BigNumber Error] ",c=s+"Number primitive has more than 15 significant digits: ",d=100000000000000,f=14,h=9007199254740991,m=[1,10,100,1000,1e4,1e5,1e6,1e7,1e8,1e9,10000000000,100000000000,1000000000000,10000000000000],g=1e7,_=1e9;function E(D){var q,V,J,L=X.prototype={constructor:X,toString:null,valueOf:null},Y=new X(1),Z=20,ne=4,W=-7,H=21,oe=-1e7,se=1e7,Ne=!1,Me=1,Xe=0,Le={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ze="0123456789abcdefghijklmnopqrstuvwxyz",Ji=!0;function X(A,S){var R,b,k,U,F,x,M,O,G=this;if(!(G instanceof X))return new X(A,S);if(S==null){if(A&&A._isBigNumber===!0){if(G.s=A.s,!A.c||A.e>se)G.c=G.e=null;else if(A.e<oe)G.c=[G.e=0];else G.e=A.e,G.c=A.c.slice();return}if((x=typeof A=="number")&&A*0==0){if(G.s=1/A<0?(A=-A,-1):1,A===~~A){for(U=0,F=A;F>=10;F/=10,U++);if(U>se)G.c=G.e=null;else G.e=U,G.c=[A];return}O=String(A)}else{if(!n.test(O=String(A)))return J(G,O,x);G.s=O.charCodeAt(0)==45?(O=O.slice(1),-1):1}if((U=O.indexOf("."))>-1)O=O.replace(".","");if((F=O.search(/e/i))>0){if(U<0)U=F;U+=+O.slice(F+1),O=O.substring(0,F)}else if(U<0)U=O.length}else{if(T(S,2,ze.length,"Base"),S==10&&Ji)return G=new X(A),je(G,Z+G.e+1,ne);if(O=String(A),x=typeof A=="number"){if(A*0!=0)return J(G,O,x,S);if(G.s=1/A<0?(O=O.slice(1),-1):1,X.DEBUG&&O.replace(/^0\.0*|\./,"").length>15)throw Error(c+A)}else G.s=O.charCodeAt(0)===45?(O=O.slice(1),-1):1;R=ze.slice(0,S),U=F=0;for(M=O.length;F<M;F++)if(R.indexOf(b=O.charAt(F))<0){if(b=="."){if(F>U){U=M;continue}}else if(!k){if(O==O.toUpperCase()&&(O=O.toLowerCase())||O==O.toLowerCase()&&(O=O.toUpperCase())){k=!0,F=-1,U=0;continue}}return J(G,String(A),x,S)}if(x=!1,O=V(O,S,10,G.s),(U=O.indexOf("."))>-1)O=O.replace(".","");else U=O.length}for(F=0;O.charCodeAt(F)===48;F++);for(M=O.length;O.charCodeAt(--M)===48;);if(O=O.slice(F,++M)){if(M-=F,x&&X.DEBUG&&M>15&&(A>h||A!==o(A)))throw Error(c+G.s*A);if((U=U-F-1)>se)G.c=G.e=null;else if(U<oe)G.c=[G.e=0];else{if(G.e=U,G.c=[],F=(U+1)%f,U<0)F+=f;if(F<M){if(F)G.c.push(+O.slice(0,F));for(M-=f;F<M;)G.c.push(+O.slice(F,F+=f));F=f-(O=O.slice(F)).length}else F-=M;for(;F--;O+="0");G.c.push(+O)}}else G.c=[G.e=0]}X.clone=E,X.ROUND_UP=0,X.ROUND_DOWN=1,X.ROUND_CEIL=2,X.ROUND_FLOOR=3,X.ROUND_HALF_UP=4,X.ROUND_HALF_DOWN=5,X.ROUND_HALF_EVEN=6,X.ROUND_HALF_CEIL=7,X.ROUND_HALF_FLOOR=8,X.EUCLID=9,X.config=X.set=function(A){var S,R;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(S="DECIMAL_PLACES"))R=A[S],T(R,0,_,S),Z=R;if(A.hasOwnProperty(S="ROUNDING_MODE"))R=A[S],T(R,0,8,S),ne=R;if(A.hasOwnProperty(S="EXPONENTIAL_AT"))if(R=A[S],R&&R.pop)T(R[0],-_,0,S),T(R[1],0,_,S),W=R[0],H=R[1];else T(R,-_,_,S),W=-(H=R<0?-R:R);if(A.hasOwnProperty(S="RANGE"))if(R=A[S],R&&R.pop)T(R[0],-_,-1,S),T(R[1],1,_,S),oe=R[0],se=R[1];else if(T(R,-_,_,S),R)oe=-(se=R<0?-R:R);else throw Error(s+S+" cannot be zero: "+R);if(A.hasOwnProperty(S="CRYPTO"))if(R=A[S],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ne=R;else throw Ne=!R,Error(s+"crypto unavailable");else Ne=R;else throw Error(s+S+" not true or false: "+R);if(A.hasOwnProperty(S="MODULO_MODE"))R=A[S],T(R,0,9,S),Me=R;if(A.hasOwnProperty(S="POW_PRECISION"))R=A[S],T(R,0,_,S),Xe=R;if(A.hasOwnProperty(S="FORMAT"))if(R=A[S],typeof R=="object")Le=R;else throw Error(s+S+" not an object: "+R);if(A.hasOwnProperty(S="ALPHABET"))if(R=A[S],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))Ji=R.slice(0,10)=="0123456789",ze=R;else throw Error(s+S+" invalid: "+R)}else throw Error(s+"Object expected: "+A);return{DECIMAL_PLACES:Z,ROUNDING_MODE:ne,EXPONENTIAL_AT:[W,H],RANGE:[oe,se],CRYPTO:Ne,MODULO_MODE:Me,POW_PRECISION:Xe,FORMAT:Le,ALPHABET:ze}},X.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!X.DEBUG)return!0;var S,R,{c:b,e:k,s:U}=A;e:if({}.toString.call(b)=="[object Array]"){if((U===1||U===-1)&&k>=-_&&k<=_&&k===o(k)){if(b[0]===0){if(k===0&&b.length===1)return!0;break e}if(S=(k+1)%f,S<1)S+=f;if(String(b[0]).length==S){for(S=0;S<b.length;S++)if(R=b[S],R<0||R>=d||R!==o(R))break e;if(R!==0)return!0}}}else if(b===null&&k===null&&(U===null||U===1||U===-1))return!0;throw Error(s+"Invalid BigNumber: "+A)},X.maximum=X.max=function(){return ra(arguments,-1)},X.minimum=X.min=function(){return ra(arguments,1)},X.random=function(){var A=9007199254740992,S=Math.random()*A&2097151?function(){return o(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var b,k,U,F,x,M=0,O=[],G=new X(Y);if(R==null)R=Z;else T(R,0,_);if(F=i(R/f),Ne)if(crypto.getRandomValues){b=crypto.getRandomValues(new Uint32Array(F*=2));for(;M<F;)if(x=b[M]*131072+(b[M+1]>>>11),x>=9000000000000000)k=crypto.getRandomValues(new Uint32Array(2)),b[M]=k[0],b[M+1]=k[1];else O.push(x%100000000000000),M+=2;M=F/2}else if(crypto.randomBytes){b=crypto.randomBytes(F*=7);for(;M<F;)if(x=(b[M]&31)*281474976710656+b[M+1]*1099511627776+b[M+2]*4294967296+b[M+3]*16777216+(b[M+4]<<16)+(b[M+5]<<8)+b[M+6],x>=9000000000000000)crypto.randomBytes(7).copy(b,M);else O.push(x%100000000000000),M+=7;M=F/7}else throw Ne=!1,Error(s+"crypto unavailable");if(!Ne){for(;M<F;)if(x=S(),x<9000000000000000)O[M++]=x%100000000000000}if(F=O[--M],R%=f,F&&R)x=m[f-R],O[M]=o(F/x)*x;for(;O[M]===0;O.pop(),M--);if(M<0)O=[U=0];else{for(U=-1;O[0]===0;O.splice(0,1),U-=f);for(M=1,x=O[0];x>=10;x/=10,M++);if(M<f)U-=f-M}return G.e=U,G.c=O,G}}(),X.sum=function(){var A=1,S=arguments,R=new X(S[0]);for(;A<S.length;)R=R.plus(S[A++]);return R},V=function(){var A="0123456789";function S(R,b,k,U){var F,x=[0],M,O=0,G=R.length;for(;O<G;){for(M=x.length;M--;x[M]*=b);x[0]+=U.indexOf(R.charAt(O++));for(F=0;F<x.length;F++)if(x[F]>k-1){if(x[F+1]==null)x[F+1]=0;x[F+1]+=x[F]/k|0,x[F]%=k}}return x.reverse()}return function(R,b,k,U,F){var x,M,O,G,B,j,ee,ce,xe=R.indexOf("."),Ge=Z,le=ne;if(xe>=0)G=Xe,Xe=0,R=R.replace(".",""),ce=new X(b),j=ce.pow(R.length-xe),Xe=G,ce.c=S(N(v(j.c),j.e,"0"),10,k,A),ce.e=ce.c.length;ee=S(R,b,k,F?(x=ze,A):(x=A,ze)),O=G=ee.length;for(;ee[--G]==0;ee.pop());if(!ee[0])return x.charAt(0);if(xe<0)--O;else j.c=ee,j.e=O,j.s=U,j=q(j,ce,Ge,le,k),ee=j.c,B=j.r,O=j.e;if(M=O+Ge+1,xe=ee[M],G=k/2,B=B||M<0||ee[M+1]!=null,B=le<4?(xe!=null||B)&&(le==0||le==(j.s<0?3:2)):xe>G||xe==G&&(le==4||B||le==6&&ee[M-1]&1||le==(j.s<0?8:7)),M<1||!ee[0])R=B?N(x.charAt(1),-Ge,x.charAt(0)):x.charAt(0);else{if(ee.length=M,B){for(--k;++ee[--M]>k;)if(ee[M]=0,!M)++O,ee=[1].concat(ee)}for(G=ee.length;!ee[--G];);for(xe=0,R="";xe<=G;R+=x.charAt(ee[xe++]));R=N(R,O,x.charAt(0))}return R}}(),q=function(){function A(b,k,U){var F,x,M,O,G=0,B=b.length,j=k%g,ee=k/g|0;for(b=b.slice();B--;)M=b[B]%g,O=b[B]/g|0,F=ee*M+O*j,x=j*M+F%g*g+G,G=(x/U|0)+(F/g|0)+ee*O,b[B]=x%U;if(G)b=[G].concat(b);return b}function S(b,k,U,F){var x,M;if(U!=F)M=U>F?1:-1;else for(x=M=0;x<U;x++)if(b[x]!=k[x]){M=b[x]>k[x]?1:-1;break}return M}function R(b,k,U,F){var x=0;for(;U--;)b[U]-=x,x=b[U]<k[U]?1:0,b[U]=x*F+b[U]-k[U];for(;!b[0]&&b.length>1;b.splice(0,1));}return function(b,k,U,F,x){var M,O,G,B,j,ee,ce,xe,Ge,le,ge,He,wr,Yi,Wi,Tt,jn,et=b.s==k.s?1:-1,Be=b.c,ke=k.c;if(!Be||!Be[0]||!ke||!ke[0])return new X(!b.s||!k.s||(Be?ke&&Be[0]==ke[0]:!ke)?NaN:Be&&Be[0]==0||!ke?et*0:et/0);if(xe=new X(et),Ge=xe.c=[],O=b.e-k.e,et=U+O+1,!x)x=d,O=y(b.e/f)-y(k.e/f),et=et/f|0;for(G=0;ke[G]==(Be[G]||0);G++);if(ke[G]>(Be[G]||0))O--;if(et<0)Ge.push(1),B=!0;else{if(Yi=Be.length,Tt=ke.length,G=0,et+=2,j=o(x/(ke[0]+1)),j>1)ke=A(ke,j,x),Be=A(Be,j,x),Tt=ke.length,Yi=Be.length;wr=Tt,le=Be.slice(0,Tt),ge=le.length;for(;ge<Tt;le[ge++]=0);if(jn=ke.slice(),jn=[0].concat(jn),Wi=ke[0],ke[1]>=x/2)Wi++;do{if(j=0,M=S(ke,le,Tt,ge),M<0){if(He=le[0],Tt!=ge)He=He*x+(le[1]||0);if(j=o(He/Wi),j>1){if(j>=x)j=x-1;ee=A(ke,j,x),ce=ee.length,ge=le.length;while(S(ee,le,ce,ge)==1)j--,R(ee,Tt<ce?jn:ke,ce,x),ce=ee.length,M=1}else{if(j==0)M=j=1;ee=ke.slice(),ce=ee.length}if(ce<ge)ee=[0].concat(ee);if(R(le,ee,ge,x),ge=le.length,M==-1)while(S(ke,le,Tt,ge)<1)j++,R(le,Tt<ge?jn:ke,ge,x),ge=le.length}else if(M===0)j++,le=[0];if(Ge[G++]=j,le[0])le[ge++]=Be[wr]||0;else le=[Be[wr]],ge=1}while((wr++<Yi||le[0]!=null)&&et--);if(B=le[0]!=null,!Ge[0])Ge.splice(0,1)}if(x==d){for(G=1,et=Ge[0];et>=10;et/=10,G++);je(xe,U+(xe.e=G+O*f-1)+1,F,B)}else xe.e=O,xe.r=+B;return xe}}();function Xi(A,S,R,b){var k,U,F,x,M;if(R==null)R=ne;else T(R,0,8);if(!A.c)return A.toString();if(k=A.c[0],F=A.e,S==null)M=v(A.c),M=b==1||b==2&&(F<=W||F>=H)?P(M,F):N(M,F,"0");else if(A=je(new X(A),S,R),U=A.e,M=v(A.c),x=M.length,b==1||b==2&&(S<=U||U<=W)){for(;x<S;M+="0",x++);M=P(M,U)}else if(S-=F+(b===2&&U>F),M=N(M,U,"0"),U+1>x){if(--S>0)for(M+=".";S--;M+="0");}else if(S+=U-x,S>0){if(U+1==x)M+=".";for(;S--;M+="0");}return A.s<0&&k?"-"+M:M}function ra(A,S){var R,b,k=1,U=new X(A[0]);for(;k<A.length;k++)if(b=new X(A[k]),!b.s||(R=C(U,b))===S||R===0&&U.s===S)U=b;return U}function Ki(A,S,R){var b=1,k=S.length;for(;!S[--k];S.pop());for(k=S[0];k>=10;k/=10,b++);if((R=b+R*f-1)>se)A.c=A.e=null;else if(R<oe)A.c=[A.e=0];else A.e=R,A.c=S;return A}J=function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,R=/^\.([^.]+)$/,b=/^-?(Infinity|NaN)$/,k=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(U,F,x,M){var O,G=x?F:F.replace(k,"");if(b.test(G))U.s=isNaN(G)?null:G<0?-1:1;else{if(!x){if(G=G.replace(A,function(B,j,ee){return O=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!M||M==O?j:B}),M)O=M,G=G.replace(S,"$1").replace(R,"0.$1");if(F!=G)return new X(G,O)}if(X.DEBUG)throw Error(s+"Not a"+(M?" base "+M:"")+" number: "+F);U.s=null}U.c=U.e=null}}();function je(A,S,R,b){var k,U,F,x,M,O,G,B=A.c,j=m;if(B){e:{for(k=1,x=B[0];x>=10;x/=10,k++);if(U=S-k,U<0)U+=f,F=S,M=B[O=0],G=o(M/j[k-F-1]%10);else if(O=i((U+1)/f),O>=B.length)if(b){for(;B.length<=O;B.push(0));M=G=0,k=1,U%=f,F=U-f+1}else break e;else{M=x=B[O];for(k=1;x>=10;x/=10,k++);U%=f,F=U-f+k,G=F<0?0:o(M/j[k-F-1]%10)}if(b=b||S<0||B[O+1]!=null||(F<0?M:M%j[k-F-1]),b=R<4?(G||b)&&(R==0||R==(A.s<0?3:2)):G>5||G==5&&(R==4||b||R==6&&(U>0?F>0?M/j[k-F]:0:B[O-1])%10&1||R==(A.s<0?8:7)),S<1||!B[0]){if(B.length=0,b)S-=A.e+1,B[0]=j[(f-S%f)%f],A.e=-S||0;else B[0]=A.e=0;return A}if(U==0)B.length=O,x=1,O--;else B.length=O+1,x=j[f-U],B[O]=F>0?o(M/j[k-F]%j[F])*x:0;if(b)for(;;)if(O==0){for(U=1,F=B[0];F>=10;F/=10,U++);F=B[0]+=x;for(x=1;F>=10;F/=10,x++);if(U!=x){if(A.e++,B[0]==d)B[0]=1}break}else{if(B[O]+=x,B[O]!=d)break;B[O--]=0,x=1}for(U=B.length;B[--U]===0;B.pop());}if(A.e>se)A.c=A.e=null;else if(A.e<oe)A.c=[A.e=0]}return A}function kt(A){var S,R=A.e;if(R===null)return A.toString();return S=v(A.c),S=R<=W||R>=H?P(S,R):N(S,R,"0"),A.s<0?"-"+S:S}if(L.absoluteValue=L.abs=function(){var A=new X(this);if(A.s<0)A.s=1;return A},L.comparedTo=function(A,S){return C(this,new X(A,S))},L.decimalPlaces=L.dp=function(A,S){var R,b,k,U=this;if(A!=null){if(T(A,0,_),S==null)S=ne;else T(S,0,8);return je(new X(U),A+U.e+1,S)}if(!(R=U.c))return null;if(b=((k=R.length-1)-y(this.e/f))*f,k=R[k])for(;k%10==0;k/=10,b--);if(b<0)b=0;return b},L.dividedBy=L.div=function(A,S){return q(this,new X(A,S),Z,ne)},L.dividedToIntegerBy=L.idiv=function(A,S){return q(this,new X(A,S),0,1)},L.exponentiatedBy=L.pow=function(A,S){var R,b,k,U,F,x,M,O,G,B=this;if(A=new X(A),A.c&&!A.isInteger())throw Error(s+"Exponent not an integer: "+kt(A));if(S!=null)S=new X(S);if(x=A.e>14,!B.c||!B.c[0]||B.c[0]==1&&!B.e&&B.c.length==1||!A.c||!A.c[0])return G=new X(Math.pow(+kt(B),x?A.s*(2-I(A)):+kt(A))),S?G.mod(S):G;if(M=A.s<0,S){if(S.c?!S.c[0]:!S.s)return new X(NaN);if(b=!M&&B.isInteger()&&S.isInteger(),b)B=B.mod(S)}else if(A.e>9&&(B.e>0||B.e<-1||(B.e==0?B.c[0]>1||x&&B.c[1]>=240000000:B.c[0]<80000000000000||x&&B.c[0]<=99999750000000))){if(U=B.s<0&&I(A)?-0:0,B.e>-1)U=1/U;return new X(M?1/U:U)}else if(Xe)U=i(Xe/f+2);if(x){if(R=new X(0.5),M)A.s=1;O=I(A)}else k=Math.abs(+kt(A)),O=k%2;G=new X(Y);for(;;){if(O){if(G=G.times(B),!G.c)break;if(U){if(G.c.length>U)G.c.length=U}else if(b)G=G.mod(S)}if(k){if(k=o(k/2),k===0)break;O=k%2}else if(A=A.times(R),je(A,A.e+1,1),A.e>14)O=I(A);else{if(k=+kt(A),k===0)break;O=k%2}if(B=B.times(B),U){if(B.c&&B.c.length>U)B.c.length=U}else if(b)B=B.mod(S)}if(b)return G;if(M)G=Y.div(G);return S?G.mod(S):U?je(G,Xe,ne,F):G},L.integerValue=function(A){var S=new X(this);if(A==null)A=ne;else T(A,0,8);return je(S,S.e+1,A)},L.isEqualTo=L.eq=function(A,S){return C(this,new X(A,S))===0},L.isFinite=function(){return!!this.c},L.isGreaterThan=L.gt=function(A,S){return C(this,new X(A,S))>0},L.isGreaterThanOrEqualTo=L.gte=function(A,S){return(S=C(this,new X(A,S)))===1||S===0},L.isInteger=function(){return!!this.c&&y(this.e/f)>this.c.length-2},L.isLessThan=L.lt=function(A,S){return C(this,new X(A,S))<0},L.isLessThanOrEqualTo=L.lte=function(A,S){return(S=C(this,new X(A,S)))===-1||S===0},L.isNaN=function(){return!this.s},L.isNegative=function(){return this.s<0},L.isPositive=function(){return this.s>0},L.isZero=function(){return!!this.c&&this.c[0]==0},L.minus=function(A,S){var R,b,k,U,F=this,x=F.s;if(A=new X(A,S),S=A.s,!x||!S)return new X(NaN);if(x!=S)return A.s=-S,F.plus(A);var M=F.e/f,O=A.e/f,G=F.c,B=A.c;if(!M||!O){if(!G||!B)return G?(A.s=-S,A):new X(B?F:NaN);if(!G[0]||!B[0])return B[0]?(A.s=-S,A):new X(G[0]?F:ne==3?-0:0)}if(M=y(M),O=y(O),G=G.slice(),x=M-O){if(U=x<0)x=-x,k=G;else O=M,k=B;k.reverse();for(S=x;S--;k.push(0));k.reverse()}else{b=(U=(x=G.length)<(S=B.length))?x:S;for(x=S=0;S<b;S++)if(G[S]!=B[S]){U=G[S]<B[S];break}}if(U)k=G,G=B,B=k,A.s=-A.s;if(S=(b=B.length)-(R=G.length),S>0)for(;S--;G[R++]=0);S=d-1;for(;b>x;){if(G[--b]<B[b]){for(R=b;R&&!G[--R];G[R]=S);--G[R],G[b]+=d}G[b]-=B[b]}for(;G[0]==0;G.splice(0,1),--O);if(!G[0])return A.s=ne==3?-1:1,A.c=[A.e=0],A;return Ki(A,G,O)},L.modulo=L.mod=function(A,S){var R,b,k=this;if(A=new X(A,S),!k.c||!A.s||A.c&&!A.c[0])return new X(NaN);else if(!A.c||k.c&&!k.c[0])return new X(k);if(Me==9)b=A.s,A.s=1,R=q(k,A,0,3),A.s=b,R.s*=b;else R=q(k,A,0,Me);if(A=k.minus(R.times(A)),!A.c[0]&&Me==1)A.s=k.s;return A},L.multipliedBy=L.times=function(A,S){var R,b,k,U,F,x,M,O,G,B,j,ee,ce,xe,Ge,le=this,ge=le.c,He=(A=new X(A,S)).c;if(!ge||!He||!ge[0]||!He[0]){if(!le.s||!A.s||ge&&!ge[0]&&!He||He&&!He[0]&&!ge)A.c=A.e=A.s=null;else if(A.s*=le.s,!ge||!He)A.c=A.e=null;else A.c=[0],A.e=0;return A}if(b=y(le.e/f)+y(A.e/f),A.s*=le.s,M=ge.length,B=He.length,M<B)ce=ge,ge=He,He=ce,k=M,M=B,B=k;for(k=M+B,ce=[];k--;ce.push(0));xe=d,Ge=g;for(k=B;--k>=0;){R=0,j=He[k]%Ge,ee=He[k]/Ge|0;for(F=M,U=k+F;U>k;)O=ge[--F]%Ge,G=ge[F]/Ge|0,x=ee*O+G*j,O=j*O+x%Ge*Ge+ce[U]+R,R=(O/xe|0)+(x/Ge|0)+ee*G,ce[U--]=O%xe;ce[U]=R}if(R)++b;else ce.splice(0,1);return Ki(A,ce,b)},L.negated=function(){var A=new X(this);return A.s=-A.s||null,A},L.plus=function(A,S){var R,b=this,k=b.s;if(A=new X(A,S),S=A.s,!k||!S)return new X(NaN);if(k!=S)return A.s=-S,b.minus(A);var U=b.e/f,F=A.e/f,x=b.c,M=A.c;if(!U||!F){if(!x||!M)return new X(k/0);if(!x[0]||!M[0])return M[0]?A:new X(x[0]?b:k*0)}if(U=y(U),F=y(F),x=x.slice(),k=U-F){if(k>0)F=U,R=M;else k=-k,R=x;R.reverse();for(;k--;R.push(0));R.reverse()}if(k=x.length,S=M.length,k-S<0)R=M,M=x,x=R,S=k;for(k=0;S;)k=(x[--S]=x[S]+M[S]+k)/d|0,x[S]=d===x[S]?0:x[S]%d;if(k)x=[k].concat(x),++F;return Ki(A,x,F)},L.precision=L.sd=function(A,S){var R,b,k,U=this;if(A!=null&&A!==!!A){if(T(A,1,_),S==null)S=ne;else T(S,0,8);return je(new X(U),A,S)}if(!(R=U.c))return null;if(k=R.length-1,b=k*f+1,k=R[k]){for(;k%10==0;k/=10,b--);for(k=R[0];k>=10;k/=10,b++);}if(A&&U.e+1>b)b=U.e+1;return b},L.shiftedBy=function(A){return T(A,-h,h),this.times("1e"+A)},L.squareRoot=L.sqrt=function(){var A,S,R,b,k,U=this,{c:F,s:x,e:M}=U,O=Z+4,G=new X("0.5");if(x!==1||!F||!F[0])return new X(!x||x<0&&(!F||F[0])?NaN:F?U:1/0);if(x=Math.sqrt(+kt(U)),x==0||x==1/0){if(S=v(F),(S.length+M)%2==0)S+="0";if(x=Math.sqrt(+S),M=y((M+1)/2)-(M<0||M%2),x==1/0)S="5e"+M;else S=x.toExponential(),S=S.slice(0,S.indexOf("e")+1)+M;R=new X(S)}else R=new X(x+"");if(R.c[0]){if(M=R.e,x=M+O,x<3)x=0;for(;;)if(k=R,R=G.times(k.plus(q(U,k,O,1))),v(k.c).slice(0,x)===(S=v(R.c)).slice(0,x)){if(R.e<M)--x;if(S=S.slice(x-3,x+1),S=="9999"||!b&&S=="4999"){if(!b){if(je(k,k.e+Z+2,0),k.times(k).eq(U)){R=k;break}}O+=4,x+=4,b=1}else{if(!+S||!+S.slice(1)&&S.charAt(0)=="5")je(R,R.e+Z+2,1),A=!R.times(R).eq(U);break}}}return je(R,R.e+Z+1,ne,A)},L.toExponential=function(A,S){if(A!=null)T(A,0,_),A++;return Xi(this,A,S,1)},L.toFixed=function(A,S){if(A!=null)T(A,0,_),A=A+this.e+1;return Xi(this,A,S)},L.toFormat=function(A,S,R){var b,k=this;if(R==null)if(A!=null&&S&&typeof S=="object")R=S,S=null;else if(A&&typeof A=="object")R=A,A=S=null;else R=Le;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(b=k.toFixed(A,S),k.c){var U,F=b.split("."),x=+R.groupSize,M=+R.secondaryGroupSize,O=R.groupSeparator||"",G=F[0],B=F[1],j=k.s<0,ee=j?G.slice(1):G,ce=ee.length;if(M)U=x,x=M,M=U,ce-=U;if(x>0&&ce>0){U=ce%x||x,G=ee.substr(0,U);for(;U<ce;U+=x)G+=O+ee.substr(U,x);if(M>0)G+=O+ee.slice(U);if(j)G="-"+G}b=B?G+(R.decimalSeparator||"")+((M=+R.fractionGroupSize)?B.replace(new RegExp("\\d{"+M+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):B):G}return(R.prefix||"")+b+(R.suffix||"")},L.toFraction=function(A){var S,R,b,k,U,F,x,M,O,G,B,j,ee=this,ce=ee.c;if(A!=null){if(x=new X(A),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+kt(x))}if(!ce)return new X(ee);S=new X(Y),O=R=new X(Y),b=M=new X(Y),j=v(ce),U=S.e=j.length-ee.e-1,S.c[0]=m[(F=U%f)<0?f+F:F],A=!A||x.comparedTo(S)>0?U>0?S:O:x,F=se,se=1/0,x=new X(j),M.c[0]=0;for(;;){if(G=q(x,S,0,1),k=R.plus(G.times(b)),k.comparedTo(A)==1)break;R=b,b=k,O=M.plus(G.times(k=O)),M=k,S=x.minus(G.times(k=S)),x=k}return k=q(A.minus(R),b,0,1),M=M.plus(k.times(O)),R=R.plus(k.times(b)),M.s=O.s=ee.s,U=U*2,B=q(O,b,U,ne).minus(ee).abs().comparedTo(q(M,R,U,ne).minus(ee).abs())<1?[O,b]:[M,R],se=F,B},L.toNumber=function(){return+kt(this)},L.toPrecision=function(A,S){if(A!=null)T(A,1,_);return Xi(this,A,S,2)},L.toString=function(A){var S,R=this,b=R.s,k=R.e;if(k===null)if(b){if(S="Infinity",b<0)S="-"+S}else S="NaN";else{if(A==null)S=k<=W||k>=H?P(v(R.c),k):N(v(R.c),k,"0");else if(A===10&&Ji)R=je(new X(R),Z+k+1,ne),S=N(v(R.c),R.e,"0");else T(A,2,ze.length,"Base"),S=V(N(v(R.c),k,"0"),10,A,b,!0);if(b<0&&R.c[0])S="-"+S}return S},L.valueOf=L.toJSON=function(){return kt(this)},L._isBigNumber=!0,D!=null)X.set(D);return X}function y(D){var q=D|0;return D>0||D===q?q:q-1}function v(D){var q,V,J=1,L=D.length,Y=D[0]+"";for(;J<L;){q=D[J++]+"",V=f-q.length;for(;V--;q="0"+q);Y+=q}for(L=Y.length;Y.charCodeAt(--L)===48;);return Y.slice(0,L+1||1)}function C(D,q){var V,J,L=D.c,Y=q.c,Z=D.s,ne=q.s,W=D.e,H=q.e;if(!Z||!ne)return null;if(V=L&&!L[0],J=Y&&!Y[0],V||J)return V?J?0:-ne:Z;if(Z!=ne)return Z;if(V=Z<0,J=W==H,!L||!Y)return J?0:!L^V?1:-1;if(!J)return W>H^V?1:-1;ne=(W=L.length)<(H=Y.length)?W:H;for(Z=0;Z<ne;Z++)if(L[Z]!=Y[Z])return L[Z]>Y[Z]^V?1:-1;return W==H?0:W>H^V?1:-1}function T(D,q,V,J){if(D<q||D>V||D!==o(D))throw Error(s+(J||"Argument")+(typeof D=="number"?D<q||D>V?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function I(D){var q=D.c.length-1;return y(D.e/f)==q&&D.c[q]%2!=0}function P(D,q){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(q<0?"e":"e+")+q}function N(D,q,V){var J,L;if(q<0){for(L=V+".";++q;L+=V);D=L+D}else if(J=D.length,++q>J){for(L=V,q-=J;--q;L+=V);D+=L}else if(q<J)D=D.slice(0,q)+"."+D.slice(q);return D}if(t=E(),t.default=t.BigNumber=t,typeof define=="function"&&define.amd)define(function(){return t});else if(typeof Gr<"u"&&Gr.exports)Gr.exports=t;else{if(!e)e=typeof self<"u"&&self?self:window;e.BigNumber=t}})(Ua)});var qa=r(function(yN,La){var Ga=io(),ba=yN;(function(){function e(h){return h<10?"0"+h:h}var t=/[\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":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':"\\\"","\\":"\\\\"},c;function d(h){return n.lastIndex=0,n.test(h)?'"'+h.replace(n,function(m){var g=s[m];return typeof g==="string"?g:"\\u"+("0000"+m.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function f(h,m){var g,_,E,y,v=i,C,T=m[h],I=T!=null&&(T instanceof Ga||Ga.isBigNumber(T));if(T&&typeof T==="object"&&typeof T.toJSON==="function")T=T.toJSON(h);if(typeof c==="function")T=c.call(m,h,T);switch(typeof T){case"string":if(I)return T;else return d(T);case"number":return isFinite(T)?String(T):"null";case"boolean":case"null":case"bigint":return String(T);case"object":if(!T)return"null";if(i+=o,C=[],Object.prototype.toString.apply(T)==="[object Array]"){y=T.length;for(g=0;g<y;g+=1)C[g]=f(g,T)||"null";return E=C.length===0?"[]":i?`[
|
|
8
|
+
`+i+C.join(`,
|
|
9
|
+
`+i)+`
|
|
10
|
+
`+v+"]":"["+C.join(",")+"]",i=v,E}if(c&&typeof c==="object"){y=c.length;for(g=0;g<y;g+=1)if(typeof c[g]==="string"){if(_=c[g],E=f(_,T),E)C.push(d(_)+(i?": ":":")+E)}}else Object.keys(T).forEach(function(P){var N=f(P,T);if(N)C.push(d(P)+(i?": ":":")+N)});return E=C.length===0?"{}":i?`{
|
|
11
|
+
`+i+C.join(`,
|
|
12
|
+
`+i)+`
|
|
13
|
+
`+v+"}":"{"+C.join(",")+"}",i=v,E}}if(typeof ba.stringify!=="function")ba.stringify=function(h,m,g){var _;if(i="",o="",typeof g==="number")for(_=0;_<g;_+=1)o+=" ";else if(typeof g==="string")o=g;if(c=m,m&&typeof m!=="function"&&(typeof m!=="object"||typeof m.length!=="number"))throw Error("JSON.stringify");return f("",{"":h})}})()});var Fa=r(function(EN,Oa){var br=null,ly=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,uy=/(?: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)/,cy=function(e){var t={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(e!==void 0&&e!==null){if(e.strict===!0)t.strict=!0;if(e.storeAsString===!0)t.storeAsString=!0;if(t.alwaysParseAsBig=e.alwaysParseAsBig===!0?e.alwaysParseAsBig:!1,t.useNativeBigInt=e.useNativeBigInt===!0?e.useNativeBigInt:!1,typeof e.constructorAction<"u")if(e.constructorAction==="error"||e.constructorAction==="ignore"||e.constructorAction==="preserve")t.constructorAction=e.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${e.constructorAction}`);if(typeof e.protoAction<"u")if(e.protoAction==="error"||e.protoAction==="ignore"||e.protoAction==="preserve")t.protoAction=e.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${e.protoAction}`)}var n,i,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
14
|
+
`,r:"\r",t:"\t"},s,c=function(v){throw{name:"SyntaxError",message:v,at:n,text:s}},d=function(v){if(v&&v!==i)c("Expected '"+v+"' instead of '"+i+"'");return i=s.charAt(n),n+=1,i},f=function(){var v,C="";if(i==="-")C="-",d("-");while(i>="0"&&i<="9")C+=i,d();if(i==="."){C+=".";while(d()&&i>="0"&&i<="9")C+=i}if(i==="e"||i==="E"){if(C+=i,d(),i==="-"||i==="+")C+=i,d();while(i>="0"&&i<="9")C+=i,d()}if(v=+C,!isFinite(v))c("Bad number");else{if(br==null)br=io();if(C.length>15)return t.storeAsString?C:t.useNativeBigInt?BigInt(C):new br(C);else return!t.alwaysParseAsBig?v:t.useNativeBigInt?BigInt(v):new br(v)}},h=function(){var v,C,T="",I;if(i==='"'){var P=n;while(d()){if(i==='"'){if(n-1>P)T+=s.substring(P,n-1);return d(),T}if(i==="\\"){if(n-1>P)T+=s.substring(P,n-1);if(d(),i==="u"){I=0;for(C=0;C<4;C+=1){if(v=parseInt(d(),16),!isFinite(v))break;I=I*16+v}T+=String.fromCharCode(I)}else if(typeof o[i]==="string")T+=o[i];else break;P=n}}}c("Bad string")},m=function(){while(i&&i<=" ")d()},g=function(){switch(i){case"t":return d("t"),d("r"),d("u"),d("e"),!0;case"f":return d("f"),d("a"),d("l"),d("s"),d("e"),!1;case"n":return d("n"),d("u"),d("l"),d("l"),null}c("Unexpected '"+i+"'")},_,E=function(){var v=[];if(i==="["){if(d("["),m(),i==="]")return d("]"),v;while(i){if(v.push(_()),m(),i==="]")return d("]"),v;d(","),m()}}c("Bad array")},y=function(){var v,C=Object.create(null);if(i==="{"){if(d("{"),m(),i==="}")return d("}"),C;while(i){if(v=h(),m(),d(":"),t.strict===!0&&Object.hasOwnProperty.call(C,v))c('Duplicate key "'+v+'"');if(ly.test(v)===!0)if(t.protoAction==="error")c("Object contains forbidden prototype property");else if(t.protoAction==="ignore")_();else C[v]=_();else if(uy.test(v)===!0)if(t.constructorAction==="error")c("Object contains forbidden constructor property");else if(t.constructorAction==="ignore")_();else C[v]=_();else C[v]=_();if(m(),i==="}")return d("}"),C;d(","),m()}}c("Bad object")};return _=function(){switch(m(),i){case"{":return y();case"[":return E();case'"':return h();case"-":return f();default:return i>="0"&&i<="9"?f():g()}},function(v,C){var T;if(s=v+"",n=0,i=" ",T=_(),m(),i)c("Syntax error");return typeof C==="function"?function I(P,N){var D,q,V=P[N];if(V&&typeof V==="object")Object.keys(V).forEach(function(J){if(q=I(V,J),q!==void 0)V[J]=q;else delete V[J]});return C.call(P,N,V)}({"":T},""):T}};Oa.exports=cy});var Ba=r(function(vN,Lr){var Ha=qa().stringify,Va=Fa();Lr.exports=function(e){return{parse:Va(e),stringify:Ha}};Lr.exports.parse=Va();Lr.exports.stringify=Ha});var oo=r(function(Ya){Object.defineProperty(Ya,"__esModule",{value:!0});Ya.GCE_LINUX_BIOS_PATHS=void 0;Ya.isGoogleCloudServerless=$a;Ya.isGoogleComputeEngineLinux=Ja;Ya.isGoogleComputeEngineMACAddress=Xa;Ya.isGoogleComputeEngine=Ka;Ya.detectGCPResidency=fy;var qr=p("fs"),Fr=p("os");Ya.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var dy=/^42:01/;function $a(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Ja(){if(Fr.platform()!=="linux")return!1;try{qr.statSync(Ya.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let e=qr.readFileSync(Ya.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(e)}catch{return!1}}function Xa(){let e=Fr.networkInterfaces();for(let t of Object.values(e)){if(!t)continue;for(let{mac:n}of t)if(dy.test(n))return!0}return!1}function Ka(){return Ja()||Xa()}function fy(){return $a()||Ka()}});var Qa=r(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});Wa.Colours=void 0;class ae{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==="function"?e.getColorDepth()>2:!0)}static refresh(){if(ae.enabled=ae.isEnabled(process===null||process===void 0?void 0:process.stderr),!this.enabled)ae.reset="",ae.bright="",ae.dim="",ae.red="",ae.green="",ae.yellow="",ae.blue="",ae.magenta="",ae.cyan="",ae.white="",ae.grey="";else ae.reset="\x1B[0m",ae.bright="\x1B[1m",ae.dim="\x1B[2m",ae.red="\x1B[31m",ae.green="\x1B[32m",ae.yellow="\x1B[33m",ae.blue="\x1B[34m",ae.magenta="\x1B[35m",ae.cyan="\x1B[36m",ae.white="\x1B[37m",ae.grey="\x1B[90m"}}Wa.Colours=ae;ae.enabled=!1;ae.reset="";ae.bright="";ae.dim="";ae.red="";ae.green="";ae.yellow="";ae.blue="";ae.magenta="";ae.cyan="";ae.white="";ae.grey="";ae.refresh()});var ol=r(function(_e){var yy=_e&&_e.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),Ey=_e&&_e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Za=_e&&_e.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var i=[];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))i[i.length]=o;return i},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null){for(var i=e(t),o=0;o<i.length;o++)if(i[o]!=="default")yy(n,t,i[o])}return Ey(n,t),n}}();Object.defineProperty(_e,"__esModule",{value:!0});_e.env=_e.DebugLogBackendBase=_e.placeholder=_e.AdhocDebugLogger=_e.LogSeverity=void 0;_e.getNodeBackend=so;_e.getDebugBackend=vy;_e.getStructuredBackend=Ty;_e.setBackend=Ay;_e.log=il;var ja=p("events"),er=Za(p("process")),el=Za(p("util")),Ie=Qa(),ht;(function(e){e.DEFAULT="DEFAULT",e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR"})(ht||(_e.LogSeverity=ht={}));class Hr extends ja.EventEmitter{constructor(e,t){super();this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,i)=>this.on(n,i)}),this.func.debug=(...n)=>this.invokeSeverity(ht.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(ht.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(ht.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(ht.ERROR,...n),this.func.sublog=(n)=>il(n,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(n){}try{this.emit("log",e,t)}catch(n){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}_e.AdhocDebugLogger=Hr;_e.placeholder=new Hr("",()=>{}).func;class tr{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=er.env[_e.env.nodeEnables])!==null&&e!==void 0?e:"*";if(t==="all")t="*";this.filters=t.split(",")}log(e,t,...n){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let i=this.cached.get(e);if(!i)i=this.makeLogger(e),this.cached.set(e,i);i(t,...n)}catch(i){console.error(i)}}}_e.DebugLogBackendBase=tr;class tl extends tr{constructor(){super(...arguments);this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){if(!this.enabledRegexp.test(e))return()=>{};return(t,...n)=>{var i;let o=`${Ie.Colours.green}${e}${Ie.Colours.reset}`,s=`${Ie.Colours.yellow}${er.pid}${Ie.Colours.reset}`,c;switch(t.severity){case ht.ERROR:c=`${Ie.Colours.red}${t.severity}${Ie.Colours.reset}`;break;case ht.INFO:c=`${Ie.Colours.magenta}${t.severity}${Ie.Colours.reset}`;break;case ht.WARNING:c=`${Ie.Colours.yellow}${t.severity}${Ie.Colours.reset}`;break;default:c=(i=t.severity)!==null&&i!==void 0?i:ht.DEFAULT;break}let d=el.formatWithOptions({colors:Ie.Colours.enabled},...n),f=Object.assign({},t);delete f.severity;let h=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",m=h?`${Ie.Colours.grey}${h}${Ie.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,c,d,h?` ${m}`:"")}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}}function so(){return new tl}class nl extends tr{constructor(e){super();this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(n,...i)=>{t(i[0],...i.slice(1))}}setFilters(){var e;let t=(e=er.env.NODE_DEBUG)!==null&&e!==void 0?e:"";er.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}}function vy(e){return new nl(e)}class rl extends tr{constructor(e){var t;super();this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let n=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(i,...o)=>{var s;let c=(s=i.severity)!==null&&s!==void 0?s:ht.INFO,d=Object.assign({severity:c,message:el.format(...o)},i),f=JSON.stringify(d);if(n)n(i,f);else console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}}function Ty(e){return new rl(e)}_e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var ao=new Map,Qe=void 0;function Ay(e){Qe=e,ao.clear()}function il(e,t){if(!Qe){if(!er.env[_e.env.nodeEnables])return _e.placeholder}if(!e)return _e.placeholder;if(t)e=`${t.instance.namespace}:${e}`;let n=ao.get(e);if(n)return n.func;if(Qe===null)return _e.placeholder;else if(Qe===void 0)Qe=so();let i=(()=>{let o=void 0;return new Hr(e,(c,...d)=>{if(o!==Qe){if(Qe===null)return;else if(Qe===void 0)Qe=so();o=Qe}Qe===null||Qe===void 0||Qe.log(e,c,...d)})})();return ao.set(e,i),i.func}});var lo=r(function(gn){var Cy=gn&&gn.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),Sy=gn&&gn.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))Cy(t,e,n)};Object.defineProperty(gn,"__esModule",{value:!0});Sy(ol(),gn)});var rr=r(function(te){var al=te&&te.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),Iy=te&&te.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),wy=te&&te.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var i=[];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))i[i.length]=o;return i},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null){for(var i=e(t),o=0;o<i.length;o++)if(i[o]!=="default")al(n,t,i[o])}return Iy(n,t),n}}(),Ry=te&&te.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))al(t,e,n)};Object.defineProperty(te,"__esModule",{value:!0});te.gcpResidencyCache=te.METADATA_SERVER_DETECTION=te.HEADERS=te.HEADER_VALUE=te.HEADER_NAME=te.SECONDARY_HOST_ADDRESS=te.HOST_ADDRESS=te.BASE_PATH=void 0;te.instance=ky;te.project=Dy;te.universe=My;te.bulk=Uy;te.isAvailable=by;te.resetIsAvailableCache=Ly;te.getGCPResidency=co;te.setGCPResidency=cl;te.requestTimeout=dl;var Cn=Oe(),ll=Ba(),ul=oo(),Py=wy(lo());te.BASE_PATH="/computeMetadata/v1";te.HOST_ADDRESS="http://169.254.169.254";te.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";te.HEADER_NAME="Metadata-Flavor";te.HEADER_VALUE="Google";te.HEADERS=Object.freeze({[te.HEADER_NAME]:te.HEADER_VALUE});var sl=Py.log("gcp-metadata");te.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 uo(e){if(!e)e=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||te.HOST_ADDRESS;if(!/^https?:\/\//.test(e))e=`http://${e}`;return new URL(te.BASE_PATH,e).href}function Ny(e){Object.keys(e).forEach((t)=>{switch(t){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${t}' is not a valid configuration option.`)}})}async function nr(e,t={},n=3,i=!1){let o=new Headers(te.HEADERS),s="",c={};if(typeof e==="object"){let g=e;new Headers(g.headers).forEach((_,E)=>o.set(E,_)),s=g.metadataKey,c=g.params||c,n=g.noResponseRetries||n,i=g.fastFail||i}else s=e;if(typeof t==="string")s+=`/${t}`;else{if(Ny(t),t.property)s+=`/${t.property}`;new Headers(t.headers).forEach((g,_)=>o.set(_,g)),c=t.params||c}let d=i?xy:Cn.request,f={url:`${uo()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:c,responseType:"text",timeout:dl()};sl.info("instance request %j",f);let h=await d(f);sl.info("instance metadata is %s",h.data);let m=h.headers.get(te.HEADER_NAME);if(m!==te.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${te.HEADER_NAME} header. Expected '${te.HEADER_VALUE}', got ${m?`'${m}'`:"no header"}`);if(typeof h.data==="string")try{return ll.parse(h.data)}catch{}return h.data}async function xy(e){let t={...e,url:e.url?.toString().replace(uo(),uo(te.SECONDARY_HOST_ADDRESS))},n=Cn.request(e),i=Cn.request(t);return Promise.any([n,i])}function ky(e){return nr("instance",e)}function Dy(e){return nr("project",e)}function My(e){return nr("universe",e)}async function Uy(e){let t={};return await Promise.all(e.map((n)=>(async()=>{let i=await nr(n),o=n.metadataKey;t[o]=i})())),t}function Gy(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Vr;async function by(){if(process.env.METADATA_SERVER_DETECTION){let e=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(e in te.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${e}\`, but it should be \`${Object.keys(te.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(e){case"assume-present":return!0;case"none":return!1;case"bios-only":return co();case"ping-only":}}try{if(Vr===void 0)Vr=nr("instance",void 0,Gy(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST));return await Vr,!0}catch(e){let t=e;if(process.env.DEBUG_AUTH)console.info(t);if(t.type==="request-timeout")return!1;if(t.response&&t.response.status===404)return!1;else{if(!(t.response&&t.response.status===404)&&(!t.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(t.code.toString()))){let n="UNKNOWN";if(t.code)n=t.code.toString();process.emitWarning(`received unexpected error = ${t.message} code = ${n}`,"MetadataLookupWarning")}return!1}}}function Ly(){Vr=void 0}te.gcpResidencyCache=null;function co(){if(te.gcpResidencyCache===null)cl();return te.gcpResidencyCache}function cl(e=null){te.gcpResidencyCache=e!==null?e:ul.detectGCPResidency()}function dl(){return co()?0:3000}Ry(oo(),te)});var pl=r(function(Jy){Jy.byteLength=Oy;Jy.toByteArray=Hy;Jy.fromByteArray=$y;var At=[],rt=[],qy=typeof Uint8Array<"u"?Uint8Array:Array,fo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ht=0,po=fo.length;Ht<po;++Ht)At[Ht]=fo[Ht],rt[fo.charCodeAt(Ht)]=Ht;var Ht,po;rt[45]=62;rt[95]=63;function fl(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");if(n===-1)n=t;var i=n===t?0:4-n%4;return[n,i]}function Oy(e){var t=fl(e),n=t[0],i=t[1];return(n+i)*3/4-i}function Fy(e,t,n){return(t+n)*3/4-n}function Hy(e){var t,n=fl(e),i=n[0],o=n[1],s=new qy(Fy(e,i,o)),c=0,d=o>0?i-4:i,f;for(f=0;f<d;f+=4)t=rt[e.charCodeAt(f)]<<18|rt[e.charCodeAt(f+1)]<<12|rt[e.charCodeAt(f+2)]<<6|rt[e.charCodeAt(f+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;if(o===2)t=rt[e.charCodeAt(f)]<<2|rt[e.charCodeAt(f+1)]>>4,s[c++]=t&255;if(o===1)t=rt[e.charCodeAt(f)]<<10|rt[e.charCodeAt(f+1)]<<4|rt[e.charCodeAt(f+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255;return s}function Vy(e){return At[e>>18&63]+At[e>>12&63]+At[e>>6&63]+At[e&63]}function By(e,t,n){var i,o=[];for(var s=t;s<n;s+=3)i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),o.push(Vy(i));return o.join("")}function $y(e){var t,n=e.length,i=n%3,o=[],s=16383;for(var c=0,d=n-i;c<d;c+=s)o.push(By(e,c,c+s>d?d:c+s));if(i===1)t=e[n-1],o.push(At[t>>2]+At[t<<4&63]+"==");else if(i===2)t=(e[n-2]<<8)+e[n-1],o.push(At[t>>10]+At[t>>4&63]+At[t<<2&63]+"=");return o.join("")}});var ho=r(function(hl){Object.defineProperty(hl,"__esModule",{value:!0});hl.fromArrayBufferToHex=Wy;function Wy(e){return Array.from(new Uint8Array(e)).map((n)=>n.toString(16).padStart(2,"0")).join("")}});var yl=r(function(gl){Object.defineProperty(gl,"__esModule",{value:!0});gl.BrowserCrypto=void 0;var it=pl(),ml=ho();class Br{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return it.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),it.fromByteArray(t)}static padBase64(e){while(e.length%4!==0)e+="=";return e}async verify(e,t,n){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(t),s=it.toByteArray(Br.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,c,Buffer.from(s),o)}async sign(e,t){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(t),o=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),s=await window.crypto.subtle.sign(n,o,i);return it.fromByteArray(new Uint8Array(s))}decodeBase64StringUtf8(e){let t=it.toByteArray(Br.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return it.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return ml.fromArrayBufferToHex(n)}async signWithHmacSha256(e,t){let n=typeof e==="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,o=await window.crypto.subtle.importKey("raw",i.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",o,i.encode(t))}}gl.BrowserCrypto=Br});var Al=r(function(vl){Object.defineProperty(vl,"__esModule",{value:!0});vl.NodeCrypto=void 0;var ot=p("crypto");class El{async sha256DigestBase64(e){return ot.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ot.randomBytes(e).toString("base64")}async verify(e,t,n){let i=ot.createVerify("RSA-SHA256");return i.update(t),i.end(),i.verify(e,n,"base64")}async sign(e,t){let n=ot.createSign("RSA-SHA256");return n.update(t),n.end(),n.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 ot.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let n=typeof e==="string"?e:Zy(e);return Qy(ot.createHmac("sha256",n).update(t).digest())}}vl.NodeCrypto=El;function Qy(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;++i)n[i]=e[i];return t}function Zy(e){return Buffer.from(e)}});var ir=r(function(Dt){var jy=Dt&&Dt.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),eE=Dt&&Dt.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))jy(t,e,n)};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.createCrypto=tE;Dt.hasBrowserCrypto=Il;var Cl=yl(),Sl=Al();eE(ho(),Dt);function tE(){if(Il())return new Cl.BrowserCrypto;return new Sl.NodeCrypto}function Il(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Sn=r(function(mo,Rl){/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var $r=p("buffer"),Ct=$r.Buffer;function wl(e,t){for(var n in e)t[n]=e[n]}if(Ct.from&&Ct.alloc&&Ct.allocUnsafe&&Ct.allocUnsafeSlow)Rl.exports=$r;else wl($r,mo),mo.Buffer=_n;function _n(e,t,n){return Ct(e,t,n)}_n.prototype=Object.create(Ct.prototype);wl(Ct,_n);_n.from=function(e,t,n){if(typeof e==="number")throw TypeError("Argument must not be a number");return Ct(e,t,n)};_n.alloc=function(e,t,n){if(typeof e!=="number")throw TypeError("Argument must be a number");var i=Ct(e);if(t!==void 0)if(typeof n==="string")i.fill(t,n);else i.fill(t);else i.fill(0);return i};_n.allocUnsafe=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return Ct(e)};_n.allocUnsafeSlow=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return $r.SlowBuffer(e)}});var Nl=r(function(kN,Pl){function go(e){var t=(e/8|0)+(e%8===0?0:1);return t}var nE={ES256:go(256),ES384:go(384),ES512:go(521)};function rE(e){var t=nE[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}Pl.exports=rE});var _o=r(function(DN,Gl){var Jr=Sn().Buffer,kl=Nl(),Xr=128,Dl=0,iE=32,oE=16,sE=2,Ml=oE|iE|Dl<<6,Kr=sE|Dl<<6;function aE(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ul(e){if(Jr.isBuffer(e))return e;else if(typeof e==="string")return Jr.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function lE(e,t){e=Ul(e);var n=kl(t),i=n+1,o=e.length,s=0;if(e[s++]!==Ml)throw Error('Could not find expected "seq"');var c=e[s++];if(c===(Xr|1))c=e[s++];if(o-s<c)throw Error('"seq" specified length of "'+c+'", only "'+(o-s)+'" remaining');if(e[s++]!==Kr)throw Error('Could not find expected "int" for "r"');var d=e[s++];if(o-s-2<d)throw Error('"r" specified length of "'+d+'", only "'+(o-s-2)+'" available');if(i<d)throw Error('"r" specified length of "'+d+'", max of "'+i+'" is acceptable');var f=s;if(s+=d,e[s++]!==Kr)throw Error('Could not find expected "int" for "s"');var h=e[s++];if(o-s!==h)throw Error('"s" specified length of "'+h+'", expected "'+(o-s)+'"');if(i<h)throw Error('"s" specified length of "'+h+'", max of "'+i+'" is acceptable');var m=s;if(s+=h,s!==o)throw Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var g=n-d,_=n-h,E=Jr.allocUnsafe(g+d+_+h);for(s=0;s<g;++s)E[s]=0;e.copy(E,s,f+Math.max(-g,0),f+d),s=n;for(var y=s;s<y+_;++s)E[s]=0;return e.copy(E,s,m+Math.max(-_,0),m+h),E=E.toString("base64"),E=aE(E),E}function xl(e,t,n){var i=0;while(t+i<n&&e[t+i]===0)++i;var o=e[t+i]>=Xr;if(o)--i;return i}function uE(e,t){e=Ul(e);var n=kl(t),i=e.length;if(i!==n*2)throw TypeError('"'+t+'" signatures must be "'+n*2+'" bytes, saw "'+i+'"');var o=xl(e,0,n),s=xl(e,n,e.length),c=n-o,d=n-s,f=2+c+1+1+d,h=f<Xr,m=Jr.allocUnsafe((h?2:3)+f),g=0;if(m[g++]=Ml,h)m[g++]=f;else m[g++]=Xr|1,m[g++]=f&255;if(m[g++]=Kr,m[g++]=c,o<0)m[g++]=0,g+=e.copy(m,g,0,n);else g+=e.copy(m,g,o,n);if(m[g++]=Kr,m[g++]=d,s<0)m[g++]=0,e.copy(m,g,n);else e.copy(m,g,n+s);return m}Gl.exports={derToJose:lE,joseToDer:uE}});var mt=r(function(Hl){Object.defineProperty(Hl,"__esModule",{value:!0});Hl.LRUCache=void 0;Hl.snakeToCamel=Ol;Hl.originalOrCamelOptions=dE;Hl.removeUndefinedValuesInObject=fE;Hl.isValidFile=pE;Hl.getWellKnownCertificateConfigFileLocation=hE;var Ll=p("fs"),ql=p("os"),In=p("path"),cE="certificate_config.json",bl="gcloud";function Ol(e){return e.replace(/([_][^_])/g,(t)=>t.slice(1).toUpperCase())}function dE(e){function t(n){let i=e||{};return i[n]??i[Ol(n)]}return{get:t}}class Fl{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#n()}get(e){let t=this.#e.get(e);if(!t)return;return this.#t(e,t.value),this.#n(),t.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();while(!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed<e))this.#e.delete(t.value[0]),t=this.#e.entries().next()}}Hl.LRUCache=Fl;function fE(e){return Object.entries(e).forEach(([t,n])=>{if(n===void 0||n==="undefined")delete e[t]}),e}async function pE(e){try{return(await Ll.promises.lstat(e)).isFile()}catch(t){return!1}}function hE(){let e=process.env.CLOUDSDK_CONFIG||(mE()?In.join(process.env.APPDATA||"",bl):In.join(process.env.HOME||"",".config",bl));return In.join(e,cE)}function mE(){return ql.platform().startsWith("win")}});var Bl=r(function(UN,TE){TE.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var Eo=r(function(Jl){Object.defineProperty(Jl,"__esModule",{value:!0});Jl.USER_AGENT=Jl.PRODUCT_NAME=Jl.pkg=void 0;var yo=Bl();Jl.pkg=yo;var $l="google-api-nodejs-client";Jl.PRODUCT_NAME=$l;var AE=`${$l}/${yo.version}`;Jl.USER_AGENT=AE});var Ze=r(function(zl){Object.defineProperty(zl,"__esModule",{value:!0});zl.AuthClient=zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=zl.DEFAULT_UNIVERSE=void 0;var Kl=p("events"),wn=Oe(),Yl=mt(),Wl=lo(),Rn=Eo();zl.DEFAULT_UNIVERSE="googleapis.com";zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300000;class Fe extends Kl.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=zl.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=zl.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=Yl.originalOrCamelOptions(e);if(this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??zl.DEFAULT_UNIVERSE,this.transporter=e.transporter??new wn.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1)this.transporter.interceptors.request.add(Fe.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(Fe.DEFAULT_RESPONSE_INTERCEPTOR);if(e.eagerRefreshThresholdMillis)this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],i=void 0,o=new Headers;if(typeof t==="string")i=new URL(t);else if(t instanceof URL)i=t;else if(t&&t.url)i=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)wn.Gaxios.mergeHeaders(o,t.headers);if(n)wn.Gaxios.mergeHeaders(o,new Headers(n.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...n,...t,headers:o,url:i});else return this.request({...n,headers:o,url:i})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){if(!e.has("x-goog-user-project")&&this.quotaProjectId)e.set("x-goog-user-project",this.quotaProjectId);return e}addUserProjectAndAuthHeaders(e,t){let n=t.get("x-goog-user-project"),i=t.get("authorization");if(n)e.set("x-goog-user-project",n);if(i)e.set("authorization",i);return e}static log=Wl.log("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async(e)=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let t=e.headers.get("User-Agent");if(!t)e.headers.set("User-Agent",Rn.USER_AGENT);else if(!t.includes(`${Rn.PRODUCT_NAME}/`))e.headers.set("User-Agent",`${t} ${Rn.USER_AGENT}`);try{let n=e,i=n[Fe.RequestMethodNameSymbol],o=`${Math.floor(Math.random()*1000)}`;n[Fe.RequestLogIdSymbol]=o;let s={url:e.url,headers:e.headers};if(i)Fe.log.info("%s [%s] request %j",i,o,s);else Fe.log.info("[%s] request %j",o,s)}catch(n){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async(e)=>{try{let t=e.config,n=t[Fe.RequestMethodNameSymbol],i=t[Fe.RequestLogIdSymbol];if(n)Fe.log.info("%s [%s] response %j",n,i,e.data);else Fe.log.info("[%s] response %j",i,e.data)}catch(t){}return e},rejected:async(e)=>{try{let t=e.config,n=t[Fe.RequestMethodNameSymbol],i=t[Fe.RequestLogIdSymbol];if(n)Fe.log.info("%s [%s] error %j",n,i,e.response?.data);else Fe.log.error("[%s] error %j",i,e.response?.data)}catch(t){}throw e}};static setMethodName(e,t){try{let n=e;n[Fe.RequestMethodNameSymbol]=t}catch(n){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}zl.AuthClient=Fe});var To=r(function(eu){Object.defineProperty(eu,"__esModule",{value:!0});eu.LoginTicket=void 0;class jl{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();if(e&&e.sub)return e.sub;return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}eu.LoginTicket=jl});var Vt=r(function(au){Object.defineProperty(au,"__esModule",{value:!0});au.OAuth2Client=au.ClientAuthentication=au.CertificateFormat=au.CodeChallengeMethod=void 0;var Yr=Oe(),ru=p("querystring"),iu=p("stream"),ou=_o(),Wr=mt(),Pn=ir(),at=Ze(),su=To(),nu;(function(e){e.Plain="plain",e.S256="S256"})(nu||(au.CodeChallengeMethod=nu={}));var Ut;(function(e){e.PEM="PEM",e.JWK="JWK"})(Ut||(au.CertificateFormat=Ut={}));var or;(function(e){e.ClientSecretPost="ClientSecretPost",e.ClientSecretBasic="ClientSecretBasic",e.None="None"})(or||(au.ClientAuthentication=or={}));class st extends at.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ut.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e==="object"?e:{});if(typeof e!=="object")e={clientId:e,clientSecret:t,redirectUri:n};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||or.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 Error("If a code_challenge_method is provided, code_challenge must be included.");if(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(" ");return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+ru.stringify(e)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=Pn.createCrypto(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),o=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:o}}getToken(e,t){let n=typeof e==="string"?{code:e}:e;if(t)this.getTokenAsync(n).then((i)=>t(null,i.tokens,i.res),(i)=>t(i,null,i.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,i={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===or.ClientSecretBasic){let d=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${d.toString("base64")}`)}if(this.clientAuthentication===or.ClientSecretPost)i.client_secret=this._clientSecret;let o={...st.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(Wr.removeUndefinedValuesInObject(i)),headers:n};at.AuthClient.setMethodName(o,"getTokenAsync");let s=await this.transporter.request(o),c=s.data;if(s.data&&s.data.expires_in)c.expiry_date=new Date().getTime()+s.data.expires_in*1000,delete c.expires_in;return this.emit("tokens",c),{tokens:c,res:s}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then((n)=>(this.refreshTokenPromises.delete(e),n),(n)=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},i;try{let s={...st.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(Wr.removeUndefinedValuesInObject(n))};at.AuthClient.setMethodName(s,"refreshTokenNoCache"),i=await this.transporter.request(s)}catch(s){if(s instanceof Yr.GaxiosError&&s.message==="invalid_grant"&&s.response?.data&&/ReAuth/i.test(s.response.data.error_description))s.message=JSON.stringify(s.response.data);throw s}let o=i.data;if(i.data&&i.data.expires_in)o.expiry_date=new Date().getTime()+i.data.expires_in*1000,delete o.expires_in;return this.emit("tokens",o),{tokens:o,res:i}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then((t)=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then((t)=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let c=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let d=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(d)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,i=null;try{n=await this.refreshToken(t.refresh_token),i=n.tokens}catch(c){let d=c;if(d.response&&(d.response.status===403||d.response.status===404))d.message=`Could not refresh access token: ${d.message}`;throw d}let o=this.credentials;o.token_type=o.token_type||"Bearer",i.refresh_token=o.refresh_token,this.credentials=i;let s=new Headers({authorization:o.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(s),res:n.res}}static getRevokeTokenUrl(e){return new st().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let n={...st.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(at.AuthClient.setMethodName(n,"revokeToken"),t)this.transporter.request(n).then((i)=>t(null,i),t);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then((t)=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);else throw Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let n=await this.getRequestMetadataAsync();if(e.headers=Yr.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey)e.headers.set("X-Goog-Api-Key",this.apiKey);return await this.transporter.request(e)}catch(n){let i=n.response;if(i){let o=i.status,s=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,d=i.config.data instanceof iu.Readable,f=o===401||o===403;if(!t&&f&&!d&&s)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);else if(!t&&f&&!d&&c){let h=await this.processAndValidateRefreshHandler();if(h?.access_token)this.setCredentials(h);return this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!=="function")throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then((n)=>t(null,n),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...st.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1000,scopes:t.scope.split(" ")},t);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then((t)=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=Pn.hasBrowserCrypto()?Ut.JWK:Ut.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===t)return{certs:this.certificateCache,format:t};let n,i;switch(t){case Ut.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ut.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${t}`)}try{let f={...st.RETRY_CONFIG,url:i};at.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),n=await this.transporter.request(f)}catch(f){if(f instanceof Error)f.message=`Failed to retrieve verification certificates: ${f.message}`;throw f}let o=n?.headers.get("cache-control"),s=-1;if(o){let f=/max-age=(?<maxAge>[0-9]+)/.exec(o)?.groups?.maxAge;if(f)s=Number(f)*1000}let c={};switch(t){case Ut.PEM:c=n.data;break;case Ut.JWK:for(let f of n.data.keys)c[f.kid]=f;break;default:throw Error(`Unsupported certificate format ${t}`)}let d=new Date;return this.certificateExpiry=s===-1?null:new Date(d.getTime()+s),this.certificateCache=c,this.certificateCacheFormat=t,{certs:c,format:t,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then((t)=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...st.RETRY_CONFIG,url:t};at.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){if(n instanceof Error)n.message=`Failed to retrieve verification certificates: ${n.message}`;throw n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,n,i,o){let s=Pn.createCrypto();if(!o)o=st.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let c=e.split(".");if(c.length!==3)throw Error("Wrong number of segments in token: "+e);let d=c[0]+"."+c[1],f=c[2],h,m;try{h=JSON.parse(s.decodeBase64StringUtf8(c[0]))}catch(I){if(I instanceof Error)I.message=`Can't parse token envelope: ${c[0]}': ${I.message}`;throw I}if(!h)throw Error("Can't parse token envelope: "+c[0]);try{m=JSON.parse(s.decodeBase64StringUtf8(c[1]))}catch(I){if(I instanceof Error)I.message=`Can't parse token payload '${c[0]}`;throw I}if(!m)throw Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(t,h.kid))throw Error("No pem found for envelope: "+JSON.stringify(h));let g=t[h.kid];if(h.alg==="ES256")f=ou.joseToDer(f,"ES256").toString("base64");if(!await s.verify(g,d,f))throw Error("Invalid token signature: "+e);if(!m.iat)throw Error("No issue time in token: "+JSON.stringify(m));if(!m.exp)throw Error("No expiration time in token: "+JSON.stringify(m));let E=Number(m.iat);if(isNaN(E))throw Error("iat field using invalid format");let y=Number(m.exp);if(isNaN(y))throw Error("exp field using invalid format");let v=new Date().getTime()/1000;if(y>=v+o)throw Error("Expiration time too far in future: "+JSON.stringify(m));let C=E-st.CLOCK_SKEW_SECS_,T=y+st.CLOCK_SKEW_SECS_;if(v<C)throw Error("Token used too early, "+v+" < "+C+": "+JSON.stringify(m));if(v>T)throw Error("Token used too late, "+v+" > "+T+": "+JSON.stringify(m));if(i&&i.indexOf(m.iss)<0)throw Error("Invalid issuer, expected one of ["+i+"], but got "+m.iss);if(typeof n<"u"&&n!==null){let I=m.aud,P=!1;if(n.constructor===Array)P=n.indexOf(I)>-1;else P=I===n;if(!P)throw Error("Wrong recipient, payload audience != requiredAudience")}return new su.LoginTicket(h,m)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error("No access token is returned by the refreshHandler callback.");return e}return}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}au.OAuth2Client=st});var Ao=r(function(fu){Object.defineProperty(fu,"__esModule",{value:!0});fu.Compute=void 0;var uu=Oe(),zr=rr(),cu=Vt();class du extends cu.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`,t;try{let i={property:e};if(this.scopes.length>0)i.params={scopes:this.scopes.join(",")};t=await zr.instance(i)}catch(i){if(i instanceof uu.GaxiosError)i.message=`Could not refresh access token: ${i.message}`,this.wrapError(i);throw i}let n=t;if(t&&t.expires_in)n.expiry_date=new Date().getTime()+t.expires_in*1000,delete n.expires_in;return this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{n=await zr.instance({property:t})}catch(i){if(i instanceof Error)i.message=`Could not fetch ID token: ${i.message}`;throw i}return n}wrapError(e){let t=e.response;if(t&&t.status){if(e.status=t.status,t.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;else if(t.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}}}fu.Compute=du});var Co=r(function(gu){Object.defineProperty(gu,"__esModule",{value:!0});gu.IdTokenClient=void 0;var hu=Vt();class mu extends hu.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 t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1000}}gu.IdTokenClient=mu});var So=r(function(yu){Object.defineProperty(yu,"__esModule",{value:!0});yu.GCPEnv=void 0;yu.clear=PE;yu.getEnv=NE;var Qr=rr(),St;(function(e){e.APP_ENGINE="APP_ENGINE",e.KUBERNETES_ENGINE="KUBERNETES_ENGINE",e.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",e.COMPUTE_ENGINE="COMPUTE_ENGINE",e.CLOUD_RUN="CLOUD_RUN",e.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",e.NONE="NONE"})(St||(yu.GCPEnv=St={}));var sr;function PE(){sr=void 0}async function NE(){if(sr)return sr;return sr=xE(),sr}async function xE(){let e=St.NONE;if(kE())e=St.APP_ENGINE;else if(DE())e=St.CLOUD_FUNCTIONS;else if(await bE())if(await GE())e=St.KUBERNETES_ENGINE;else if(ME())e=St.CLOUD_RUN;else if(UE())e=St.CLOUD_RUN_JOBS;else e=St.COMPUTE_ENGINE;else e=St.NONE;return e}function kE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function DE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function ME(){return!!process.env.K_CONFIGURATION}function UE(){return!!process.env.CLOUD_RUN_JOB}async function GE(){try{return await Qr.instance("attributes/cluster-name"),!0}catch(e){return!1}}async function bE(){return Qr.isAvailable()}});var Io=r(function(VN,vu){var Zr=Sn().Buffer,OE=p("stream"),FE=p("util");function jr(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=Zr.alloc(0),this;if(typeof e.pipe==="function")return this.buffer=Zr.alloc(0),e.pipe(this),this;if(e.length||typeof e==="object")return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}FE.inherits(jr,OE);jr.prototype.write=function(t){this.buffer=Zr.concat([this.buffer,Zr.from(t)]),this.emit("data",t)};jr.prototype.end=function(t){if(t)this.write(t);this.emit("end",t),this.emit("close"),this.writable=!1,this.readable=!1};vu.exports=jr});var Au=r(function(BN,Tu){var ar=p("buffer").Buffer,wo=p("buffer").SlowBuffer;Tu.exports=ei;function ei(e,t){if(!ar.isBuffer(e)||!ar.isBuffer(t))return!1;if(e.length!==t.length)return!1;var n=0;for(var i=0;i<e.length;i++)n|=e[i]^t[i];return n===0}ei.install=function(){ar.prototype.equal=wo.prototype.equal=function(t){return ei(this,t)}};var HE=ar.prototype.equal,VE=wo.prototype.equal;ei.restore=function(){ar.prototype.equal=HE,wo.prototype.equal=VE}});var xo=r(function($N,ku){var xn=Sn().Buffer,lt=p("crypto"),Su=_o(),Cu=p("util"),BE=`"%s" is not a valid algorithm.
|
|
15
15
|
Supported algorithms are:
|
|
16
|
-
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,lr="secret must be a string or buffer",Nn="key must be a string or a buffer",$E="key must be a string, a buffer or an object",Po=typeof lt.createPublicKey==="function";if(Po)Nn+=" or a KeyObject",lr+="or a KeyObject";function Iu(e){if(xn.isBuffer(e))return;if(typeof e==="string")return;if(!Po)throw gt(Nn);if(typeof e!=="object")throw gt(Nn);if(typeof e.type!=="string")throw gt(Nn);if(typeof e.asymmetricKeyType!=="string")throw gt(Nn);if(typeof e.export!=="function")throw gt(Nn)}function wu(e){if(xn.isBuffer(e))return;if(typeof e==="string")return;if(typeof e==="object")return;throw gt($E)}function JE(e){if(xn.isBuffer(e))return;if(typeof e==="string")return e;if(!Po)throw gt(lr);if(typeof e!=="object")throw gt(lr);if(e.type!=="secret")throw gt(lr);if(typeof e.export!=="function")throw gt(lr)}function No(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ru(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function gt(e){var t=[].slice.call(arguments,1),n=Cu.format.bind(Cu,e).apply(null,t);return TypeError(n)}function XE(e){return xn.isBuffer(e)||typeof e==="string"}function ur(e){if(!XE(e))e=JSON.stringify(e);return e}function Pu(e){return function(n,o){JE(o),n=ur(n);var s=lt.createHmac("sha"+e,o),a=(s.update(n),s.digest("base64"));return No(a)}}var Ro,KE="timingSafeEqual"in lt?function(t,n){if(t.byteLength!==n.byteLength)return!1;return lt.timingSafeEqual(t,n)}:function(t,n){if(!Ro)Ro=Au();return Ro(t,n)};function YE(e){return function(n,o,s){var a=Pu(e)(n,s);return KE(xn.from(o),xn.from(a))}}function Nu(e){return function(n,o){wu(o),n=ur(n);var s=lt.createSign("RSA-SHA"+e),a=(s.update(n),s.sign(o,"base64"));return No(a)}}function xu(e){return function(n,o,s){Iu(s),n=ur(n),o=Ru(o);var a=lt.createVerify("RSA-SHA"+e);return a.update(n),a.verify(s,o,"base64")}}function WE(e){return function(n,o){wu(o),n=ur(n);var s=lt.createSign("RSA-SHA"+e),a=(s.update(n),s.sign({key:o,padding:lt.constants.RSA_PKCS1_PSS_PADDING,saltLength:lt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return No(a)}}function zE(e){return function(n,o,s){Iu(s),n=ur(n),o=Ru(o);var a=lt.createVerify("RSA-SHA"+e);return a.update(n),a.verify({key:s,padding:lt.constants.RSA_PKCS1_PSS_PADDING,saltLength:lt.constants.RSA_PSS_SALTLEN_DIGEST},o,"base64")}}function QE(e){var t=Nu(e);return function(){var o=t.apply(null,arguments);return o=Su.derToJose(o,"ES"+e),o}}function ZE(e){var t=xu(e);return function(o,s,a){s=Su.joseToDer(s,"ES"+e).toString("base64");var c=t(o,s,a);return c}}function jE(){return function(){return""}}function ev(){return function(t,n){return n===""}}ku.exports=function(t){var n={hs:Pu,rs:Nu,ps:WE,es:QE,none:jE},o={hs:YE,rs:xu,ps:zE,es:ZE,none:ev},s=t.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw gt(BE,t);var a=(s[1]||s[3]).toLowerCase(),c=s[2];return{sign:n[a](c),verify:o[a](c)}}});var ko=r(function(JN,Du){var tv=p("buffer").Buffer;Du.exports=function(t){if(typeof t==="string")return t;if(typeof t==="number"||tv.isBuffer(t))return t.toString();return JSON.stringify(t)}});var qu=r(function(XN,Lu){var nv=Sn().Buffer,Mu=Io(),rv=xo(),iv=p("stream"),Uu=ko(),Do=p("util");function Gu(e,t){return nv.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ov(e,t,n){n=n||"utf8";var o=Gu(Uu(e),"binary"),s=Gu(Uu(t),n);return Do.format("%s.%s",o,s)}function bu(e){var{header:t,payload:n}=e,o=e.secret||e.privateKey,s=e.encoding,a=rv(t.alg),c=ov(t,n,s),d=a.sign(c,o);return Do.format("%s.%s",c,d)}function ti(e){var t=e.secret;if(t=t==null?e.privateKey:t,t=t==null?e.key:t,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var n=new Mu(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Mu(e.payload),this.secret.once("close",function(){if(!this.payload.writable&&this.readable)this.sign()}.bind(this)),this.payload.once("close",function(){if(!this.secret.writable&&this.readable)this.sign()}.bind(this))}Do.inherits(ti,iv);ti.prototype.sign=function(){try{var t=bu({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",t),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};ti.sign=bu;Lu.exports=ti});var Yu=r(function(KN,Ku){var Fu=Sn().Buffer,Ou=Io(),sv=xo(),av=p("stream"),Hu=ko(),lv=p("util"),uv=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function cv(e){return Object.prototype.toString.call(e)==="[object Object]"}function dv(e){if(cv(e))return e;try{return JSON.parse(e)}catch(t){return}}function Vu(e){var t=e.split(".",1)[0];return dv(Fu.from(t,"base64").toString("binary"))}function fv(e){return e.split(".",2).join(".")}function Bu(e){return e.split(".")[2]}function pv(e,t){t=t||"utf8";var n=e.split(".")[1];return Fu.from(n,"base64").toString(t)}function $u(e){return uv.test(e)&&!!Vu(e)}function Ju(e,t,n){if(!t){var o=Error("Missing algorithm parameter for jws.verify");throw o.code="MISSING_ALGORITHM",o}e=Hu(e);var s=Bu(e),a=fv(e),c=sv(t);return c.verify(a,s,n)}function Xu(e,t){if(t=t||{},e=Hu(e),!$u(e))return null;var n=Vu(e);if(!n)return null;var o=pv(e);if(n.typ==="JWT"||t.json)o=JSON.parse(o,t.encoding);return{header:n,payload:o,signature:Bu(e)}}function kn(e){e=e||{};var t=e.secret;if(t=t==null?e.publicKey:t,t=t==null?e.key:t,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var n=new Ou(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Ou(e.signature),this.secret.once("close",function(){if(!this.signature.writable&&this.readable)this.verify()}.bind(this)),this.signature.once("close",function(){if(!this.secret.writable&&this.readable)this.verify()}.bind(this))}lv.inherits(kn,av);kn.prototype.verify=function(){try{var t=Ju(this.signature.buffer,this.algorithm,this.key.buffer),n=Xu(this.signature.buffer,this.encoding);return this.emit("done",t,n),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(o){this.readable=!1,this.emit("error",o),this.emit("close")}};kn.decode=Xu;kn.isValid=$u;kn.verify=Ju;Ku.exports=kn});var Mo=r(function(mv){var Wu=qu(),ni=Yu(),hv=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];mv.ALGORITHMS=hv;mv.sign=Wu.sign;mv.verify=ni.verify;mv.decode=ni.decode;mv.isValid=ni.isValid;mv.createSign=function(t){return new Wu(t)};mv.createVerify=function(t){return new ni(t)}});var ju=r(function(Zu){Object.defineProperty(Zu,"__esModule",{value:!0});Zu.buildPayloadForJwsSign=Qu;Zu.getJwsSign=Iv;var zu=Mo(),Cv="RS256",Sv="https://oauth2.googleapis.com/token";function Qu(e){let t=Math.floor(new Date().getTime()/1000);return{iss:e.iss,scope:e.scope,aud:Sv,exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}function Iv(e){let t=Qu(e);return zu.sign({header:{alg:Cv},payload:t,secret:e.key})}});var nc=r(function(tc){Object.defineProperty(tc,"__esModule",{value:!0});tc.getToken=kv;var ec=ju(),Pv="https://oauth2.googleapis.com/token",Nv="urn:ietf:params:oauth:grant-type:jwt-bearer",xv=(e)=>({method:"POST",url:Pv,data:new URLSearchParams({grant_type:Nv,assertion:ec.getJwsSign(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function kv(e){if(!e.transporter)throw Error("No transporter set.");try{let t=xv(e);return(await e.transporter.request(t)).data}catch(t){let n=t,o=n.response?.data;if(o?.error)n.message=`${o.error}: ${o.error_description}`;throw n}}});var sc=r(function(ic){Object.defineProperty(ic,"__esModule",{value:!0});ic.ErrorWithCode=void 0;class rc extends Error{code;constructor(e,t){super(e);this.code=t}}ic.ErrorWithCode=rc});var Uo=r(function(hc){Object.defineProperty(hc,"__esModule",{value:!0});hc.getCredentials=Mv;var ac=p("path"),ri=p("fs"),lc=p("util"),Xt=sc(),uc=ri.readFile?lc.promisify(ri.readFile):async()=>{throw new Xt.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Jt;(function(e){e.JSON=".json",e.DER=".der",e.CRT=".crt",e.PEM=".pem",e.P12=".p12",e.PFX=".pfx"})(Jt||(Jt={}));class cc{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await uc(this.keyFilePath,"utf8"),t;try{t=JSON.parse(e)}catch(s){throw Error(`Invalid JSON key file: ${s.message}`)}let n=t.private_key,o=t.client_email;if(!n||!o)throw new Xt.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:n,clientEmail:o}}}class dc{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await uc(this.keyFilePath,"utf8")}}}class fc{async getCredentials(){throw new Xt.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")}}class pc{static create(e){switch(ac.extname(e)){case Jt.JSON:return new cc(e);case Jt.DER:case Jt.CRT:case Jt.PEM:return new dc(e);case Jt.P12:case Jt.PFX:return new fc;default:throw new Xt.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function Mv(e){return pc.create(e).getCredentials()}});var vc=r(function(yc){Object.defineProperty(yc,"__esModule",{value:!0});yc.TokenHandler=void 0;var mc=nc(),gc=Uo();class _c{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await gc.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(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){let e=new Date().getTime();if(this.token&&this.tokenExpiresAt)return new Date().getTime()>=this.tokenExpiresAt;return!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=mc.getToken(this.tokenOptions);let t=await this.inFlightRequest;return this.token=t,this.tokenExpiresAt=new Date().getTime()+(t.expires_in??0)*1000,t}finally{this.inFlightRequest=void 0}}}yc.TokenHandler=_c});var Ac=r(function(Tc){Object.defineProperty(Tc,"__esModule",{value:!0});Tc.revokeToken=Lv;var Gv="https://oauth2.googleapis.com/revoke?token=",bv=!0;async function Lv(e,t){let n=Gv+e;return await t.request({url:n,retry:bv})}});var Go=r(function(wc){Object.defineProperty(wc,"__esModule",{value:!0});wc.GoogleToken=void 0;var Cc=qe(),ii=vc(),Sc=Ac();class Ic{tokenOptions;tokenHandler;constructor(e){if(this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:(t)=>Cc.request(t)},!this.tokenOptions.iss)this.tokenOptions.iss=this.tokenOptions.email;if(typeof this.tokenOptions.scope==="object")this.tokenOptions.scope=this.tokenOptions.scope.join(" ");this.tokenHandler=new ii.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,t={forceRefresh:!1}){let n;if(typeof e==="function")n=e;else if(typeof e==="object")t=e;let o=this.tokenHandler.getToken(t.forceRefresh??!1);if(n)o.then((s)=>n(null,s),n);return o}revokeToken(e){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let t=Sc.revokeToken(this.accessToken,this.tokenOptions.transporter);if(e)t.then(()=>e(),e);this.tokenHandler=new ii.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}wc.GoogleToken=Ic});var Lo=r(function(kc){Object.defineProperty(kc,"__esModule",{value:!0});kc.JWTAccess=void 0;var Nc=Mo(),xc=mt(),Pc={alg:"RS256",typ:"JWT"};class bo{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new xc.LRUCache({capacity:500,maxAge:3600000});constructor(e,t,n,o){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=o??300000}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length)n=e?`${e}_${t.join("_")}`:`${t.join("_")}`;else if(typeof t==="string")n=e?`${e}_${t}`:t;if(!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,t,n){let o=this.getCachedKey(e,n),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1000),d=bo.getExpirationTime(c),f;if(Array.isArray(n))n=n.join(" ");if(n)f={iss:this.email,sub:this.email,scope:n,exp:d,iat:c};else f={iss:this.email,sub:this.email,aud:e,exp:d,iat:c};if(t){for(let v in f)if(t[v])throw Error(`The '${v}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let h=this.keyId?{...Pc,kid:this.keyId}:Pc,m=Object.assign(f,t),g=Nc.sign({header:h,payload:m,secret:this.key}),_=new Headers({authorization:`Bearer ${g}`});return this.cache.set(o,{expiration:d*1000,headers:_}),_}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)n(Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",(s)=>o+=s).on("error",n).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),t()}catch(s){n(s)}})})}}kc.JWTAccess=bo});var Oo=r(function(bc){Object.defineProperty(bc,"__esModule",{value:!0});bc.JWT=void 0;var oi=Go(),Mc=Uo(),Uc=Lo(),Gc=Bt(),Yt=Ze();class qo extends Gc.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 t=new qo(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Yt.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Yt.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Yt.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{if(!this.access)this.access=new Uc.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let n;if(this.hasUserScopes())n=this.scopes;else if(!e)n=this.defaultScopes;let o=this.useJWTAccessWithScope||this.universeDomain!==Yt.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(e);else return{headers:new Headers}}async fetchIdToken(e){let t=new oi.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 t.getToken({forceRefresh:!0}),!t.idToken)throw Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){if(!this.scopes)return!1;return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return!0;if(this.defaultScopes&&this.defaultScopes.length>0)return!0;return!1}authorize(e){if(e)this.authorizeAsync().then((t)=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw 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(),n={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",n),{res:null,tokens:n}}createGToken(){if(!this.gtoken)this.gtoken=new oi.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter});return this.gtoken}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",(s)=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),t()}catch(s){n(s)}})})}fromAPIKey(e){if(typeof e!=="string")throw Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};else if(this.keyFile){let e=this.createGToken(),t=await Mc.getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}bc.JWT=qo});var Fo=r(function(Fc){Object.defineProperty(Fc,"__esModule",{value:!0});Fc.UserRefreshClient=Fc.USER_REFRESH_ACCOUNT_TYPE=void 0;var qc=Bt(),Oc=Ze();Fc.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class si extends qc.OAuth2Client{_refreshToken;constructor(e,t,n,o,s){let a=e&&typeof e==="object"?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a);this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...si.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 Oc.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",(s)=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),t()}catch(s){return n(s)}})})}static fromJSON(e){let t=new si;return t.fromJSON(e),t}}Fc.UserRefreshClient=si});var Ho=r(function($c){Object.defineProperty($c,"__esModule",{value:!0});$c.Impersonated=$c.IMPERSONATED_ACCOUNT_TYPE=void 0;var ai=Bt(),Vc=qe(),Bc=mt();$c.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class cr extends ai.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e);if(this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new ai.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!Bc.originalOrCamelOptions(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw 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 t=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${t}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...cr.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...cr.RETRY_CONFIG,url:t,data:n,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 t=0,n="";if(e instanceof Vc.GaxiosError)t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message;if(t&&n)throw e.message=`${t}: unable to impersonate: ${n}`,e;else throw e.message=`unable to impersonate: ${e}`,e}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...cr.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}}$c.Impersonated=cr});var Vo=r(function(Yc){Object.defineProperty(Yc,"__esModule",{value:!0});Yc.OAuthClientAuthHandler=void 0;Yc.getErrorFromOAuthErrorResponse=Vv;var ut=qe(),Xc=ir(),Hv=["PUT","POST","PATCH"];class Kc{#e=Xc.createCrypto();#t;transporter;constructor(e){if(e&&"clientId"in e)this.#t=e,this.transporter=new ut.Gaxios;else this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ut.Gaxios}applyClientAuthenticationOptions(e,t){if(e.headers=ut.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),!t)this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=ut.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ut.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${n}:${o}`);ut.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!Hv.includes(t))throw Error(`${t} 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 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"]}}}}Yc.OAuthClientAuthHandler=Kc;function Vv(e,t){let{error:n,error_description:o,error_uri:s}=e,a=`Error code ${n}`;if(typeof o<"u")a+=`: ${o}`;if(typeof s<"u")a+=` - ${s}`;let c=Error(a);if(t){let d=Object.keys(t);if(t.stack)d.push("stack");d.forEach((f)=>{if(f!=="message")Object.defineProperty(c,f,{value:t[f],writable:!1,enumerable:!0})})}return c}});var ui=r(function(jc){Object.defineProperty(jc,"__esModule",{value:!0});jc.StsCredentials=void 0;var zc=qe(),Qc=Ze(),li=Vo(),Zc=mt();class Bo extends li.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){if(typeof e!=="object"||e instanceof URL)e={tokenExchangeEndpoint:e,clientAuthentication:t};super(e);this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,n){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:n&&JSON.stringify(n)},s={...Bo.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams(Zc.removeUndefinedValuesInObject(o)),responseType:"json"};Qc.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){if(a instanceof zc.GaxiosError&&a.response)throw li.getErrorFromOAuthErrorResponse(a.response.data,a);throw a}}}jc.StsCredentials=Bo});var Wt=r(function(od){Object.defineProperty(od,"__esModule",{value:!0});od.BaseExternalAccountClient=od.CLOUD_RESOURCE_MANAGER=od.EXTERNAL_ACCOUNT_TYPE=od.EXPIRATION_TIME_OFFSET=void 0;var td=qe(),nd=p("stream"),Dn=Ze(),rd=ui(),ci=mt(),id=Eo(),$v="urn:ietf:params:oauth:grant-type:token-exchange",Jv="urn:ietf:params:oauth:token-type:access_token",$o="https://www.googleapis.com/auth/cloud-platform",Xv=3600;od.EXPIRATION_TIME_OFFSET=300000;od.EXTERNAL_ACCOUNT_TYPE="external_account";od.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Kv="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Yv="https://sts.{universeDomain}/v1/token";class di extends Dn.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=ci.originalOrCamelOptions(e),n=t.get("type");if(n&&n!==od.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${od.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=t.get("client_id"),s=t.get("client_secret");this.tokenUrl=t.get("token_url")??Yv.replace("{universeDomain}",this.universeDomain);let a=t.get("subject_token_type"),c=t.get("workforce_pool_user_project"),d=t.get("service_account_impersonation_url"),f=t.get("service_account_impersonation"),h=ci.originalOrCamelOptions(f).get("token_lifetime_seconds");if(this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o)this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s};this.stsCredential=new rd.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[$o],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let m=new RegExp(Kv);if(this.workforcePoolUserProject&&!this.audience.match(m))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");if(this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=h,this.serviceAccountImpersonationLifetime)this.configLifetimeRequested=!0;else this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Xv;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 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(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;else if(e){let t=await this.getRequestHeaders(),n={...di.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Dn.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=td.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof nd.Readable;if(!t&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:$v,audience:this.audience,requestedTokenType:Jv,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[$o]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(t,o,n);if(this.serviceAccountImpersonationUrl)this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token);else if(s.expires_in)this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1000,res:s.res};else this.cachedAccessToken={access_token:s.access_token,res:s.res};return 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 t=e.match(/\/projects\/([^/]+)/);if(!t)return null;return t[1]}async getImpersonatedAccessToken(e){let t={...di.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"};Dn.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let n=await this.transporter.request(t),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){if(typeof this.scopes==="string")return[this.scopes];return this.scopes||[$o]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${id.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}od.BaseExternalAccountClient=di});var cd=r(function(ld){Object.defineProperty(ld,"__esModule",{value:!0});ld.FileSubjectTokenSupplier=void 0;var Mn=p("util"),Un=p("fs"),Qv=Mn.promisify(Un.readFile??(()=>{})),Zv=Mn.promisify(Un.realpath??(()=>{})),jv=Mn.promisify(Un.lstat??(()=>{}));class ad{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 Zv(e),!(await jv(e)).isFile())throw Error()}catch(o){if(o instanceof Error)o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`;throw o}let t,n=await Qv(e,{encoding:"utf8"});if(this.formatType==="text")t=n;else if(this.formatType==="json"&&this.subjectTokenFieldName)t=JSON.parse(n)[this.subjectTokenFieldName];if(!t)throw Error("Unable to parse the subject_token from the credential_source file");return t}}ld.FileSubjectTokenSupplier=ad});var md=r(function(pd){Object.defineProperty(pd,"__esModule",{value:!0});pd.UrlSubjectTokenSupplier=void 0;var dd=Ze();class fd{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 t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};dd.AuthClient.setMethodName(t,"getSubjectToken");let n;if(this.formatType==="text")n=(await e.transporter.request(t)).data;else if(this.formatType==="json"&&this.subjectTokenFieldName)n=(await e.transporter.request(t)).data[this.subjectTokenFieldName];if(!n)throw Error("Unable to parse the subject_token from the credential_source URL");return n}}pd.UrlSubjectTokenSupplier=fd});var vd=r(function(yd){Object.defineProperty(yd,"__esModule",{value:!0});yd.CertificateSubjectTokenSupplier=yd.InvalidConfigurationError=yd.CertificateSourceUnavailableError=yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Qt=mt(),Zt=p("fs"),en=p("crypto"),gd=p("https");yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class Gt extends Error{constructor(e){super(e);this.name="CertificateSourceUnavailableError"}}yd.CertificateSourceUnavailableError=Gt;class _t extends Error{constructor(e){super(e);this.name="InvalidConfigurationError"}}yd.InvalidConfigurationError=_t;class _d{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new _t("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new _t("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new _t("Cannot create mTLS Agent with missing certificate or key");return new gd.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,t),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await Qt.isValidFile(e))return e;throw new Gt(`Provided certificate config path is invalid: ${e}`)}let t=process.env[yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await Qt.isValidFile(t))return t;throw new Gt(`Path from environment variable "${yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let n=Qt.getWellKnownCertificateConfigFileLocation();if(await Qt.isValidFile(n))return n;throw new Gt(`Could not find certificate configuration file. Searched override path, the "${yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await Zt.promises.readFile(e,"utf8")}catch(n){throw new Gt(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),o=n?.cert_configs?.workload?.cert_path,s=n?.cert_configs?.workload?.key_path;if(!o||!s)throw new _t(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(n){if(n instanceof _t)throw n;throw new _t(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#n(e,t){let n,o;try{n=await Zt.promises.readFile(e),new en.X509Certificate(n)}catch(s){let a=s instanceof Error?s.message:String(s);throw new Gt(`Failed to read certificate file at ${e}: ${a}`)}try{o=await Zt.promises.readFile(t),en.createPrivateKey(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new Gt(`Failed to read private key file at ${t}: ${a}`)}return{cert:n,key:o}}async#r(e){let t=new en.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let s=((await Zt.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((d,f)=>{try{return new en.X509Certificate(d)}catch(h){let m=h instanceof Error?h.message:String(h);throw new _t(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${m}`)}}),a=s.findIndex((d)=>t.raw.equals(d.raw)),c;if(a===-1)c=[t,...s];else if(a===0)c=s;else throw new _t(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map((d)=>d.raw.toString("base64")))}catch(n){if(n instanceof _t)throw n;let o=n instanceof Error?n.message:String(n);throw new Gt(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}}yd.CertificateSubjectTokenSupplier=_d});var Ko=r(function(Id){Object.defineProperty(Id,"__esModule",{value:!0});Id.IdentityPoolClient=void 0;var Td=Wt(),Gn=mt(),Ad=cd(),Cd=md(),pi=vd(),Sd=ui(),hi=qe();class Xo extends Td.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=Gn.originalOrCamelOptions(e),n=t.get("credential_source"),o=t.get("subject_token_supplier");if(!n&&!o)throw Error("A credential source or subject token supplier must be specified.");if(n&&o)throw Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=Gn.originalOrCamelOptions(n),a=Gn.originalOrCamelOptions(s.get("format")),c=a.get("type")||"text",d=a.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!d)throw Error("Missing subject_token_field_name for JSON credential_source format");let f=s.get("file"),h=s.get("url"),m=s.get("certificate"),g=s.get("headers");if(f&&h||h&&m||f&&m)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');else if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new Ad.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:d});else if(h)this.credentialSourceType="url",this.subjectTokenSupplier=new Cd.UrlSubjectTokenSupplier({url:h,formatType:c,subjectTokenFieldName:d,headers:g,additionalGaxiosOptions:Xo.RETRY_CONFIG});else if(m){this.credentialSourceType="certificate";let _=new pi.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:m.use_default_certificate_config,certificateConfigLocation:m.certificate_config_location,trustChainPath:m.trust_chain_path});this.subjectTokenSupplier=_}else throw 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 pi.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Sd.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new hi.Gaxios({agent:t})}),this.transporter=new hi.Gaxios({...this.transporter.defaults||{},agent:t})}return e}}Id.IdentityPoolClient=Xo});var Yo=r(function(Nd){Object.defineProperty(Nd,"__esModule",{value:!0});Nd.AwsRequestSigner=void 0;var tn=qe(),mi=ir(),Rd="AWS4-HMAC-SHA256",nT="aws4_request";class Pd{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=mi.createCrypto()}async getRequestOptions(e){if(!e.url)throw RangeError('"url" is required in "amzOptions"');let t=typeof e.data==="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",s=e.body||t,a=e.headers,c=await this.getCredentials(),d=new URL(n);if(typeof s!=="string"&&s!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await iT({crypto:this.crypto,host:d.host,canonicalUri:d.pathname,canonicalQuerystring:d.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),h=tn.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:d.host},a||{});if(c.token)tn.Gaxios.mergeHeaders(h,{"x-amz-security-token":c.token});let m={url:n,method:o,headers:h};if(s!==void 0)m.body=s;return m}}Nd.AwsRequestSigner=Pd;async function dr(e,t,n){return await e.signWithHmacSha256(t,n)}async function rT(e,t,n,o,s){let a=await dr(e,`AWS4${t}`,n),c=await dr(e,a,o),d=await dr(e,c,s);return await dr(e,d,"aws4_request")}async function iT(e){let t=tn.Gaxios.mergeHeaders(e.additionalAmzHeaders),n=e.requestPayload||"",o=e.host.split(".")[0],s=new Date,a=s.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),c=s.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(e.securityCredentials.token)t.set("x-amz-security-token",e.securityCredentials.token);let d=tn.Gaxios.mergeHeaders({host:e.host},t.has("date")?{}:{"x-amz-date":a},t),f="",h=[...d.keys()].sort();h.forEach((w)=>{f+=`${w}:${d.get(w)}
|
|
16
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,lr="secret must be a string or buffer",Nn="key must be a string or a buffer",$E="key must be a string, a buffer or an object",Po=typeof lt.createPublicKey==="function";if(Po)Nn+=" or a KeyObject",lr+="or a KeyObject";function Iu(e){if(xn.isBuffer(e))return;if(typeof e==="string")return;if(!Po)throw gt(Nn);if(typeof e!=="object")throw gt(Nn);if(typeof e.type!=="string")throw gt(Nn);if(typeof e.asymmetricKeyType!=="string")throw gt(Nn);if(typeof e.export!=="function")throw gt(Nn)}function wu(e){if(xn.isBuffer(e))return;if(typeof e==="string")return;if(typeof e==="object")return;throw gt($E)}function JE(e){if(xn.isBuffer(e))return;if(typeof e==="string")return e;if(!Po)throw gt(lr);if(typeof e!=="object")throw gt(lr);if(e.type!=="secret")throw gt(lr);if(typeof e.export!=="function")throw gt(lr)}function No(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ru(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function gt(e){var t=[].slice.call(arguments,1),n=Cu.format.bind(Cu,e).apply(null,t);return TypeError(n)}function XE(e){return xn.isBuffer(e)||typeof e==="string"}function ur(e){if(!XE(e))e=JSON.stringify(e);return e}function Pu(e){return function(n,i){JE(i),n=ur(n);var o=lt.createHmac("sha"+e,i),s=(o.update(n),o.digest("base64"));return No(s)}}var Ro,KE="timingSafeEqual"in lt?function(t,n){if(t.byteLength!==n.byteLength)return!1;return lt.timingSafeEqual(t,n)}:function(t,n){if(!Ro)Ro=Au();return Ro(t,n)};function YE(e){return function(n,i,o){var s=Pu(e)(n,o);return KE(xn.from(i),xn.from(s))}}function Nu(e){return function(n,i){wu(i),n=ur(n);var o=lt.createSign("RSA-SHA"+e),s=(o.update(n),o.sign(i,"base64"));return No(s)}}function xu(e){return function(n,i,o){Iu(o),n=ur(n),i=Ru(i);var s=lt.createVerify("RSA-SHA"+e);return s.update(n),s.verify(o,i,"base64")}}function WE(e){return function(n,i){wu(i),n=ur(n);var o=lt.createSign("RSA-SHA"+e),s=(o.update(n),o.sign({key:i,padding:lt.constants.RSA_PKCS1_PSS_PADDING,saltLength:lt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return No(s)}}function zE(e){return function(n,i,o){Iu(o),n=ur(n),i=Ru(i);var s=lt.createVerify("RSA-SHA"+e);return s.update(n),s.verify({key:o,padding:lt.constants.RSA_PKCS1_PSS_PADDING,saltLength:lt.constants.RSA_PSS_SALTLEN_DIGEST},i,"base64")}}function QE(e){var t=Nu(e);return function(){var i=t.apply(null,arguments);return i=Su.derToJose(i,"ES"+e),i}}function ZE(e){var t=xu(e);return function(i,o,s){o=Su.joseToDer(o,"ES"+e).toString("base64");var c=t(i,o,s);return c}}function jE(){return function(){return""}}function ev(){return function(t,n){return n===""}}ku.exports=function(t){var n={hs:Pu,rs:Nu,ps:WE,es:QE,none:jE},i={hs:YE,rs:xu,ps:zE,es:ZE,none:ev},o=t.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw gt(BE,t);var s=(o[1]||o[3]).toLowerCase(),c=o[2];return{sign:n[s](c),verify:i[s](c)}}});var ko=r(function(JN,Du){var tv=p("buffer").Buffer;Du.exports=function(t){if(typeof t==="string")return t;if(typeof t==="number"||tv.isBuffer(t))return t.toString();return JSON.stringify(t)}});var qu=r(function(XN,Lu){var nv=Sn().Buffer,Mu=Io(),rv=xo(),iv=p("stream"),Uu=ko(),Do=p("util");function Gu(e,t){return nv.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ov(e,t,n){n=n||"utf8";var i=Gu(Uu(e),"binary"),o=Gu(Uu(t),n);return Do.format("%s.%s",i,o)}function bu(e){var{header:t,payload:n}=e,i=e.secret||e.privateKey,o=e.encoding,s=rv(t.alg),c=ov(t,n,o),d=s.sign(c,i);return Do.format("%s.%s",c,d)}function ti(e){var t=e.secret;if(t=t==null?e.privateKey:t,t=t==null?e.key:t,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var n=new Mu(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Mu(e.payload),this.secret.once("close",function(){if(!this.payload.writable&&this.readable)this.sign()}.bind(this)),this.payload.once("close",function(){if(!this.secret.writable&&this.readable)this.sign()}.bind(this))}Do.inherits(ti,iv);ti.prototype.sign=function(){try{var t=bu({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",t),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};ti.sign=bu;Lu.exports=ti});var Yu=r(function(KN,Ku){var Fu=Sn().Buffer,Ou=Io(),sv=xo(),av=p("stream"),Hu=ko(),lv=p("util"),uv=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function cv(e){return Object.prototype.toString.call(e)==="[object Object]"}function dv(e){if(cv(e))return e;try{return JSON.parse(e)}catch(t){return}}function Vu(e){var t=e.split(".",1)[0];return dv(Fu.from(t,"base64").toString("binary"))}function fv(e){return e.split(".",2).join(".")}function Bu(e){return e.split(".")[2]}function pv(e,t){t=t||"utf8";var n=e.split(".")[1];return Fu.from(n,"base64").toString(t)}function $u(e){return uv.test(e)&&!!Vu(e)}function Ju(e,t,n){if(!t){var i=Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}e=Hu(e);var o=Bu(e),s=fv(e),c=sv(t);return c.verify(s,o,n)}function Xu(e,t){if(t=t||{},e=Hu(e),!$u(e))return null;var n=Vu(e);if(!n)return null;var i=pv(e);if(n.typ==="JWT"||t.json)i=JSON.parse(i,t.encoding);return{header:n,payload:i,signature:Bu(e)}}function kn(e){e=e||{};var t=e.secret;if(t=t==null?e.publicKey:t,t=t==null?e.key:t,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var n=new Ou(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Ou(e.signature),this.secret.once("close",function(){if(!this.signature.writable&&this.readable)this.verify()}.bind(this)),this.signature.once("close",function(){if(!this.secret.writable&&this.readable)this.verify()}.bind(this))}lv.inherits(kn,av);kn.prototype.verify=function(){try{var t=Ju(this.signature.buffer,this.algorithm,this.key.buffer),n=Xu(this.signature.buffer,this.encoding);return this.emit("done",t,n),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(i){this.readable=!1,this.emit("error",i),this.emit("close")}};kn.decode=Xu;kn.isValid=$u;kn.verify=Ju;Ku.exports=kn});var Mo=r(function(mv){var Wu=qu(),ni=Yu(),hv=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];mv.ALGORITHMS=hv;mv.sign=Wu.sign;mv.verify=ni.verify;mv.decode=ni.decode;mv.isValid=ni.isValid;mv.createSign=function(t){return new Wu(t)};mv.createVerify=function(t){return new ni(t)}});var ju=r(function(Zu){Object.defineProperty(Zu,"__esModule",{value:!0});Zu.buildPayloadForJwsSign=Qu;Zu.getJwsSign=Iv;var zu=Mo(),Cv="RS256",Sv="https://oauth2.googleapis.com/token";function Qu(e){let t=Math.floor(new Date().getTime()/1000);return{iss:e.iss,scope:e.scope,aud:Sv,exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}function Iv(e){let t=Qu(e);return zu.sign({header:{alg:Cv},payload:t,secret:e.key})}});var nc=r(function(tc){Object.defineProperty(tc,"__esModule",{value:!0});tc.getToken=kv;var ec=ju(),Pv="https://oauth2.googleapis.com/token",Nv="urn:ietf:params:oauth:grant-type:jwt-bearer",xv=(e)=>({method:"POST",url:Pv,data:new URLSearchParams({grant_type:Nv,assertion:ec.getJwsSign(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function kv(e){if(!e.transporter)throw Error("No transporter set.");try{let t=xv(e);return(await e.transporter.request(t)).data}catch(t){let n=t,i=n.response?.data;if(i?.error)n.message=`${i.error}: ${i.error_description}`;throw n}}});var sc=r(function(ic){Object.defineProperty(ic,"__esModule",{value:!0});ic.ErrorWithCode=void 0;class rc extends Error{code;constructor(e,t){super(e);this.code=t}}ic.ErrorWithCode=rc});var Uo=r(function(hc){Object.defineProperty(hc,"__esModule",{value:!0});hc.getCredentials=Mv;var ac=p("path"),ri=p("fs"),lc=p("util"),$t=sc(),uc=ri.readFile?lc.promisify(ri.readFile):async()=>{throw new $t.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Bt;(function(e){e.JSON=".json",e.DER=".der",e.CRT=".crt",e.PEM=".pem",e.P12=".p12",e.PFX=".pfx"})(Bt||(Bt={}));class cc{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await uc(this.keyFilePath,"utf8"),t;try{t=JSON.parse(e)}catch(o){throw Error(`Invalid JSON key file: ${o.message}`)}let n=t.private_key,i=t.client_email;if(!n||!i)throw new $t.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:n,clientEmail:i}}}class dc{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await uc(this.keyFilePath,"utf8")}}}class fc{async getCredentials(){throw new $t.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")}}class pc{static create(e){switch(ac.extname(e)){case Bt.JSON:return new cc(e);case Bt.DER:case Bt.CRT:case Bt.PEM:return new dc(e);case Bt.P12:case Bt.PFX:return new fc;default:throw new $t.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function Mv(e){return pc.create(e).getCredentials()}});var vc=r(function(yc){Object.defineProperty(yc,"__esModule",{value:!0});yc.TokenHandler=void 0;var mc=nc(),gc=Uo();class _c{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await gc.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(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){let e=new Date().getTime();if(this.token&&this.tokenExpiresAt)return new Date().getTime()>=this.tokenExpiresAt;return!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=mc.getToken(this.tokenOptions);let t=await this.inFlightRequest;return this.token=t,this.tokenExpiresAt=new Date().getTime()+(t.expires_in??0)*1000,t}finally{this.inFlightRequest=void 0}}}yc.TokenHandler=_c});var Ac=r(function(Tc){Object.defineProperty(Tc,"__esModule",{value:!0});Tc.revokeToken=Lv;var Gv="https://oauth2.googleapis.com/revoke?token=",bv=!0;async function Lv(e,t){let n=Gv+e;return await t.request({url:n,retry:bv})}});var Go=r(function(wc){Object.defineProperty(wc,"__esModule",{value:!0});wc.GoogleToken=void 0;var Cc=Oe(),ii=vc(),Sc=Ac();class Ic{tokenOptions;tokenHandler;constructor(e){if(this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:(t)=>Cc.request(t)},!this.tokenOptions.iss)this.tokenOptions.iss=this.tokenOptions.email;if(typeof this.tokenOptions.scope==="object")this.tokenOptions.scope=this.tokenOptions.scope.join(" ");this.tokenHandler=new ii.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,t={forceRefresh:!1}){let n;if(typeof e==="function")n=e;else if(typeof e==="object")t=e;let i=this.tokenHandler.getToken(t.forceRefresh??!1);if(n)i.then((o)=>n(null,o),n);return i}revokeToken(e){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let t=Sc.revokeToken(this.accessToken,this.tokenOptions.transporter);if(e)t.then(()=>e(),e);this.tokenHandler=new ii.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}wc.GoogleToken=Ic});var Lo=r(function(kc){Object.defineProperty(kc,"__esModule",{value:!0});kc.JWTAccess=void 0;var Nc=Mo(),xc=mt(),Pc={alg:"RS256",typ:"JWT"};class bo{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new xc.LRUCache({capacity:500,maxAge:3600000});constructor(e,t,n,i){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=i??300000}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length)n=e?`${e}_${t.join("_")}`:`${t.join("_")}`;else if(typeof t==="string")n=e?`${e}_${t}`:t;if(!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,t,n){let i=this.getCachedKey(e,n),o=this.cache.get(i),s=Date.now();if(o&&o.expiration-s>this.eagerRefreshThresholdMillis)return new Headers(o.headers);let c=Math.floor(Date.now()/1000),d=bo.getExpirationTime(c),f;if(Array.isArray(n))n=n.join(" ");if(n)f={iss:this.email,sub:this.email,scope:n,exp:d,iat:c};else f={iss:this.email,sub:this.email,aud:e,exp:d,iat:c};if(t){for(let E in f)if(t[E])throw Error(`The '${E}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let h=this.keyId?{...Pc,kid:this.keyId}:Pc,m=Object.assign(f,t),g=Nc.sign({header:h,payload:m,secret:this.key}),_=new Headers({authorization:`Bearer ${g}`});return this.cache.set(i,{expiration:d*1000,headers:_}),_}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)n(Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",(o)=>i+=o).on("error",n).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),t()}catch(o){n(o)}})})}}kc.JWTAccess=bo});var Oo=r(function(bc){Object.defineProperty(bc,"__esModule",{value:!0});bc.JWT=void 0;var oi=Go(),Mc=Uo(),Uc=Lo(),Gc=Vt(),Kt=Ze();class qo extends Gc.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 t=new qo(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Kt.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Kt.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Kt.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{if(!this.access)this.access=new Uc.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let n;if(this.hasUserScopes())n=this.scopes;else if(!e)n=this.defaultScopes;let i=this.useJWTAccessWithScope||this.universeDomain!==Kt.DEFAULT_UNIVERSE,o=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?n:void 0);return{headers:this.addSharedMetadataHeaders(o)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(e);else return{headers:new Headers}}async fetchIdToken(e){let t=new oi.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 t.getToken({forceRefresh:!0}),!t.idToken)throw Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){if(!this.scopes)return!1;return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return!0;if(this.defaultScopes&&this.defaultScopes.length>0)return!0;return!1}authorize(e){if(e)this.authorizeAsync().then((t)=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw 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(),n={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",n),{res:null,tokens:n}}createGToken(){if(!this.gtoken)this.gtoken=new oi.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter});return this.gtoken}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw Error("Must pass in a stream containing the service account auth settings.");let i="";e.setEncoding("utf8").on("error",n).on("data",(o)=>i+=o).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),t()}catch(o){n(o)}})})}fromAPIKey(e){if(typeof e!=="string")throw Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};else if(this.keyFile){let e=this.createGToken(),t=await Mc.getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}bc.JWT=qo});var Fo=r(function(Fc){Object.defineProperty(Fc,"__esModule",{value:!0});Fc.UserRefreshClient=Fc.USER_REFRESH_ACCOUNT_TYPE=void 0;var qc=Vt(),Oc=Ze();Fc.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class si extends qc.OAuth2Client{_refreshToken;constructor(e,t,n,i,o){let s=e&&typeof e==="object"?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:o};super(s);this._refreshToken=s.refreshToken,this.credentials.refresh_token=s.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...si.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 Oc.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw 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,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(Error("Must pass in a stream containing the user refresh token."));let i="";e.setEncoding("utf8").on("error",n).on("data",(o)=>i+=o).on("end",()=>{try{let o=JSON.parse(i);return this.fromJSON(o),t()}catch(o){return n(o)}})})}static fromJSON(e){let t=new si;return t.fromJSON(e),t}}Fc.UserRefreshClient=si});var Ho=r(function($c){Object.defineProperty($c,"__esModule",{value:!0});$c.Impersonated=$c.IMPERSONATED_ACCOUNT_TYPE=void 0;var ai=Vt(),Vc=Oe(),Bc=mt();$c.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class cr extends ai.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e);if(this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new ai.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!Bc.originalOrCamelOptions(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw 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 t=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${t}:signBlob`,i={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...cr.RETRY_CONFIG,url:n,data:i,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},i=await this.sourceClient.request({...cr.RETRY_CONFIG,url:t,data:n,method:"POST"}),o=i.data;return this.credentials.access_token=o.accessToken,this.credentials.expiry_date=Date.parse(o.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";if(e instanceof Vc.GaxiosError)t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message;if(t&&n)throw e.message=`${t}: unable to impersonate: ${n}`,e;else throw e.message=`unable to impersonate: ${e}`,e}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${n}:generateIdToken`,o={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...cr.RETRY_CONFIG,url:i,data:o,method:"POST"})).data.token}}$c.Impersonated=cr});var Vo=r(function(Yc){Object.defineProperty(Yc,"__esModule",{value:!0});Yc.OAuthClientAuthHandler=void 0;Yc.getErrorFromOAuthErrorResponse=Vv;var ut=Oe(),Xc=ir(),Hv=["PUT","POST","PATCH"];class Kc{#e=Xc.createCrypto();#t;transporter;constructor(e){if(e&&"clientId"in e)this.#t=e,this.transporter=new ut.Gaxios;else this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ut.Gaxios}applyClientAuthenticationOptions(e,t){if(e.headers=ut.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),!t)this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=ut.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ut.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,i=this.#t.clientSecret||"",o=this.#e.encodeBase64StringUtf8(`${n}:${i}`);ut.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${o}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!Hv.includes(t))throw Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let i=new Headers(e.headers).get("content-type");if(i?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let o=new URLSearchParams(e.data??"");o.append("client_id",this.#t.clientId),o.append("client_secret",this.#t.clientSecret||""),e.data=o}else if(i?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw Error(`${i} 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"]}}}}Yc.OAuthClientAuthHandler=Kc;function Vv(e,t){let{error:n,error_description:i,error_uri:o}=e,s=`Error code ${n}`;if(typeof i<"u")s+=`: ${i}`;if(typeof o<"u")s+=` - ${o}`;let c=Error(s);if(t){let d=Object.keys(t);if(t.stack)d.push("stack");d.forEach((f)=>{if(f!=="message")Object.defineProperty(c,f,{value:t[f],writable:!1,enumerable:!0})})}return c}});var ui=r(function(jc){Object.defineProperty(jc,"__esModule",{value:!0});jc.StsCredentials=void 0;var zc=Oe(),Qc=Ze(),li=Vo(),Zc=mt();class Bo extends li.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){if(typeof e!=="object"||e instanceof URL)e={tokenExchangeEndpoint:e,clientAuthentication:t};super(e);this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,n){let i={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:n&&JSON.stringify(n)},o={...Bo.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams(Zc.removeUndefinedValuesInObject(i)),responseType:"json"};Qc.AuthClient.setMethodName(o,"exchangeToken"),this.applyClientAuthenticationOptions(o);try{let s=await this.transporter.request(o),c=s.data;return c.res=s,c}catch(s){if(s instanceof zc.GaxiosError&&s.response)throw li.getErrorFromOAuthErrorResponse(s.response.data,s);throw s}}}jc.StsCredentials=Bo});var Wt=r(function(od){Object.defineProperty(od,"__esModule",{value:!0});od.BaseExternalAccountClient=od.CLOUD_RESOURCE_MANAGER=od.EXTERNAL_ACCOUNT_TYPE=od.EXPIRATION_TIME_OFFSET=void 0;var td=Oe(),nd=p("stream"),Dn=Ze(),rd=ui(),ci=mt(),id=Eo(),$v="urn:ietf:params:oauth:grant-type:token-exchange",Jv="urn:ietf:params:oauth:token-type:access_token",$o="https://www.googleapis.com/auth/cloud-platform",Xv=3600;od.EXPIRATION_TIME_OFFSET=300000;od.EXTERNAL_ACCOUNT_TYPE="external_account";od.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Kv="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Yv="https://sts.{universeDomain}/v1/token";class di extends Dn.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=ci.originalOrCamelOptions(e),n=t.get("type");if(n&&n!==od.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${od.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=t.get("client_id"),o=t.get("client_secret");this.tokenUrl=t.get("token_url")??Yv.replace("{universeDomain}",this.universeDomain);let s=t.get("subject_token_type"),c=t.get("workforce_pool_user_project"),d=t.get("service_account_impersonation_url"),f=t.get("service_account_impersonation"),h=ci.originalOrCamelOptions(f).get("token_lifetime_seconds");if(this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i)this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:o};this.stsCredential=new rd.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[$o],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=s,this.workforcePoolUserProject=c;let m=new RegExp(Kv);if(this.workforcePoolUserProject&&!this.audience.match(m))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");if(this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=h,this.serviceAccountImpersonationLifetime)this.configLifetimeRequested=!0;else this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Xv;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 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(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;else if(e){let t=await this.getRequestHeaders(),n={...di.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Dn.AuthClient.setMethodName(n,"getProjectId");let i=await this.transporter.request(n);return this.projectId=i.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let n;try{let i=await this.getRequestHeaders();e.headers=td.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),n=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let s=o.status,c=o.config.data instanceof nd.Readable;if(!t&&(s===401||s===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:$v,audience:this.audience,requestedTokenType:Jv,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[$o]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),o=await this.stsCredential.exchangeToken(t,i,n);if(this.serviceAccountImpersonationUrl)this.cachedAccessToken=await this.getImpersonatedAccessToken(o.access_token);else if(o.expires_in)this.cachedAccessToken={access_token:o.access_token,expiry_date:new Date().getTime()+o.expires_in*1000,res:o.res};else this.cachedAccessToken={access_token:o.access_token,res:o.res};return 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 t=e.match(/\/projects\/([^/]+)/);if(!t)return null;return t[1]}async getImpersonatedAccessToken(e){let t={...di.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"};Dn.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let n=await this.transporter.request(t),i=n.data;return{access_token:i.accessToken,expiry_date:new Date(i.expireTime).getTime(),res:n}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){if(typeof this.scopes==="string")return[this.scopes];return this.scopes||[$o]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${id.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}od.BaseExternalAccountClient=di});var cd=r(function(ld){Object.defineProperty(ld,"__esModule",{value:!0});ld.FileSubjectTokenSupplier=void 0;var Mn=p("util"),Un=p("fs"),Qv=Mn.promisify(Un.readFile??(()=>{})),Zv=Mn.promisify(Un.realpath??(()=>{})),jv=Mn.promisify(Un.lstat??(()=>{}));class ad{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 Zv(e),!(await jv(e)).isFile())throw Error()}catch(i){if(i instanceof Error)i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`;throw i}let t,n=await Qv(e,{encoding:"utf8"});if(this.formatType==="text")t=n;else if(this.formatType==="json"&&this.subjectTokenFieldName)t=JSON.parse(n)[this.subjectTokenFieldName];if(!t)throw Error("Unable to parse the subject_token from the credential_source file");return t}}ld.FileSubjectTokenSupplier=ad});var md=r(function(pd){Object.defineProperty(pd,"__esModule",{value:!0});pd.UrlSubjectTokenSupplier=void 0;var dd=Ze();class fd{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 t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};dd.AuthClient.setMethodName(t,"getSubjectToken");let n;if(this.formatType==="text")n=(await e.transporter.request(t)).data;else if(this.formatType==="json"&&this.subjectTokenFieldName)n=(await e.transporter.request(t)).data[this.subjectTokenFieldName];if(!n)throw Error("Unable to parse the subject_token from the credential_source URL");return n}}pd.UrlSubjectTokenSupplier=fd});var vd=r(function(yd){Object.defineProperty(yd,"__esModule",{value:!0});yd.CertificateSubjectTokenSupplier=yd.InvalidConfigurationError=yd.CertificateSourceUnavailableError=yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Qt=mt(),jt=p("fs"),en=p("crypto"),gd=p("https");yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class Gt extends Error{constructor(e){super(e);this.name="CertificateSourceUnavailableError"}}yd.CertificateSourceUnavailableError=Gt;class _t extends Error{constructor(e){super(e);this.name="InvalidConfigurationError"}}yd.InvalidConfigurationError=_t;class _d{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new _t("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new _t("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new _t("Cannot create mTLS Agent with missing certificate or key");return new gd.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,t),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await Qt.isValidFile(e))return e;throw new Gt(`Provided certificate config path is invalid: ${e}`)}let t=process.env[yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await Qt.isValidFile(t))return t;throw new Gt(`Path from environment variable "${yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let n=Qt.getWellKnownCertificateConfigFileLocation();if(await Qt.isValidFile(n))return n;throw new Gt(`Could not find certificate configuration file. Searched override path, the "${yd.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await jt.promises.readFile(e,"utf8")}catch(n){throw new Gt(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),i=n?.cert_configs?.workload?.cert_path,o=n?.cert_configs?.workload?.key_path;if(!i||!o)throw new _t(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:o}}catch(n){if(n instanceof _t)throw n;throw new _t(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#n(e,t){let n,i;try{n=await jt.promises.readFile(e),new en.X509Certificate(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Gt(`Failed to read certificate file at ${e}: ${s}`)}try{i=await jt.promises.readFile(t),en.createPrivateKey(i)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Gt(`Failed to read private key file at ${t}: ${s}`)}return{cert:n,key:i}}async#r(e){let t=new en.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let o=((await jt.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((d,f)=>{try{return new en.X509Certificate(d)}catch(h){let m=h instanceof Error?h.message:String(h);throw new _t(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${m}`)}}),s=o.findIndex((d)=>t.raw.equals(d.raw)),c;if(s===-1)c=[t,...o];else if(s===0)c=o;else throw new _t(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${s}).`);return JSON.stringify(c.map((d)=>d.raw.toString("base64")))}catch(n){if(n instanceof _t)throw n;let i=n instanceof Error?n.message:String(n);throw new Gt(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}}yd.CertificateSubjectTokenSupplier=_d});var Ko=r(function(Id){Object.defineProperty(Id,"__esModule",{value:!0});Id.IdentityPoolClient=void 0;var Td=Wt(),Gn=mt(),Ad=cd(),Cd=md(),pi=vd(),Sd=ui(),hi=Oe();class Xo extends Td.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=Gn.originalOrCamelOptions(e),n=t.get("credential_source"),i=t.get("subject_token_supplier");if(!n&&!i)throw Error("A credential source or subject token supplier must be specified.");if(n&&i)throw Error("Only one of credential source or subject token supplier can be specified.");if(i)this.subjectTokenSupplier=i,this.credentialSourceType="programmatic";else{let o=Gn.originalOrCamelOptions(n),s=Gn.originalOrCamelOptions(o.get("format")),c=s.get("type")||"text",d=s.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!d)throw Error("Missing subject_token_field_name for JSON credential_source format");let f=o.get("file"),h=o.get("url"),m=o.get("certificate"),g=o.get("headers");if(f&&h||h&&m||f&&m)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');else if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new Ad.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:d});else if(h)this.credentialSourceType="url",this.subjectTokenSupplier=new Cd.UrlSubjectTokenSupplier({url:h,formatType:c,subjectTokenFieldName:d,headers:g,additionalGaxiosOptions:Xo.RETRY_CONFIG});else if(m){this.credentialSourceType="certificate";let _=new pi.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:m.use_default_certificate_config,certificateConfigLocation:m.certificate_config_location,trustChainPath:m.trust_chain_path});this.subjectTokenSupplier=_}else throw 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 pi.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Sd.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new hi.Gaxios({agent:t})}),this.transporter=new hi.Gaxios({...this.transporter.defaults||{},agent:t})}return e}}Id.IdentityPoolClient=Xo});var Yo=r(function(Nd){Object.defineProperty(Nd,"__esModule",{value:!0});Nd.AwsRequestSigner=void 0;var tn=Oe(),mi=ir(),Rd="AWS4-HMAC-SHA256",nT="aws4_request";class Pd{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=mi.createCrypto()}async getRequestOptions(e){if(!e.url)throw RangeError('"url" is required in "amzOptions"');let t=typeof e.data==="object"?JSON.stringify(e.data):e.data,n=e.url,i=e.method||"GET",o=e.body||t,s=e.headers,c=await this.getCredentials(),d=new URL(n);if(typeof o!=="string"&&o!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${o}`);let f=await iT({crypto:this.crypto,host:d.host,canonicalUri:d.pathname,canonicalQuerystring:d.search.slice(1),method:i,region:this.region,securityCredentials:c,requestPayload:o,additionalAmzHeaders:s}),h=tn.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:d.host},s||{});if(c.token)tn.Gaxios.mergeHeaders(h,{"x-amz-security-token":c.token});let m={url:n,method:i,headers:h};if(o!==void 0)m.body=o;return m}}Nd.AwsRequestSigner=Pd;async function dr(e,t,n){return await e.signWithHmacSha256(t,n)}async function rT(e,t,n,i,o){let s=await dr(e,`AWS4${t}`,n),c=await dr(e,s,i),d=await dr(e,c,o);return await dr(e,d,"aws4_request")}async function iT(e){let t=tn.Gaxios.mergeHeaders(e.additionalAmzHeaders),n=e.requestPayload||"",i=e.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),c=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(e.securityCredentials.token)t.set("x-amz-security-token",e.securityCredentials.token);let d=tn.Gaxios.mergeHeaders({host:e.host},t.has("date")?{}:{"x-amz-date":s},t),f="",h=[...d.keys()].sort();h.forEach((I)=>{f+=`${I}:${d.get(I)}
|
|
17
17
|
`});let m=h.join(";"),g=await e.crypto.sha256DigestHex(n),_=`${e.method.toUpperCase()}
|
|
18
18
|
${e.canonicalUri}
|
|
19
19
|
${e.canonicalQuerystring}
|
|
20
20
|
${f}
|
|
21
21
|
${m}
|
|
22
|
-
${g}`,
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
`+await e.crypto.sha256DigestHex(_),T=await rT(e.crypto,e.securityCredentials.secretAccessKey,c,e.region,o),S=await dr(e.crypto,T,E),A=`${Rd} Credential=${e.securityCredentials.accessKeyId}/${v}, SignedHeaders=${m}, Signature=${mi.fromArrayBufferToHex(S)}`;return{amzDate:t.has("date")?void 0:a,authorizationHeader:A,canonicalQuerystring:e.canonicalQuerystring}}});var Ud=r(function(Dd){Object.defineProperty(Dd,"__esModule",{value:!0});Dd.DefaultAwsSecurityCredentialsSupplier=void 0;var nn=Ze();class kd{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.#r)return this.#r;let t=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));if(!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:t};nn.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let t=new Headers;if(this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(t,e.transporter),o=await this.#n(n,t,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return nn.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return nn.AuthClient.setMethodName(n,"#getAwsRoleName"),(await t.request(n)).data}async#n(e,t,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t,responseType:"json"};return nn.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)return{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN};return null}}Dd.DefaultAwsSecurityCredentialsSupplier=kd});var Wo=r(function(Od){Object.defineProperty(Od,"__esModule",{value:!0});Od.AwsClient=void 0;var Gd=Yo(),bd=Wt(),Ld=Ud(),gi=mt(),qd=qe();class _i extends bd.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 t=gi.originalOrCamelOptions(e),n=t.get("credential_source"),o=t.get("aws_security_credentials_supplier");if(!n&&!o)throw Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=_i.#e,this.credentialSourceType="programmatic";else{let s=gi.originalOrCamelOptions(n);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),d=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Ld.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:d}),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 Error('No valid AWS "credential_source" provided');else if(parseInt(e[2],10)!==1)throw Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){if(!this.awsRequestSigner)this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Gd.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region);let e=await this.awsRequestSigner.getRequestOptions({..._i.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return qd.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>t.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}}Od.AwsClient=_i});var rs=r(function(Bd){Object.defineProperty(Bd,"__esModule",{value:!0});Bd.InvalidSubjectTokenError=Bd.InvalidMessageFieldError=Bd.InvalidCodeFieldError=Bd.InvalidTokenTypeFieldError=Bd.InvalidExpirationTimeFieldError=Bd.InvalidSuccessFieldError=Bd.InvalidVersionFieldError=Bd.ExecutableResponseError=Bd.ExecutableResponse=void 0;var yi="urn:ietf:params:oauth:token-type:saml2",zo="urn:ietf:params:oauth:token-type:id_token",Qo="urn:ietf:params:oauth:token-type:jwt";class Hd{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Zo("Executable response must contain a 'version' field.");if(e.success===void 0)throw new jo("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!==yi&&this.tokenType!==zo&&this.tokenType!==Qo)throw new es(`Executable response must contain a 'token_type' field when successful and it must be one of ${zo}, ${Qo}, or ${yi}.`);if(this.tokenType===yi){if(!e.saml_response)throw new Ei(`Executable response must contain a 'saml_response' field when token_type=${yi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ei(`Executable response must contain a 'id_token' field when token_type=${zo} or ${Qo}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ts("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ns("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()/1000)}}Bd.ExecutableResponse=Hd;class bt extends Error{constructor(e){super(e);Object.setPrototypeOf(this,new.target.prototype)}}Bd.ExecutableResponseError=bt;class Zo extends bt{}Bd.InvalidVersionFieldError=Zo;class jo extends bt{}Bd.InvalidSuccessFieldError=jo;class Vd extends bt{}Bd.InvalidExpirationTimeFieldError=Vd;class es extends bt{}Bd.InvalidTokenTypeFieldError=es;class ts extends bt{}Bd.InvalidCodeFieldError=ts;class ns extends bt{}Bd.InvalidMessageFieldError=ns;class Ei extends bt{}Bd.InvalidSubjectTokenError=Ei});var ss=r(function(Xd){Object.defineProperty(Xd,"__esModule",{value:!0});Xd.PluggableAuthHandler=Xd.ExecutableError=void 0;var Ye=rs(),Jd=p("child_process"),bn=p("fs");class is extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`);this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}Xd.ExecutableError=is;class os{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw Error("No command provided.");if(this.commandComponents=os.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,n)=>{let o=Jd.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",(c)=>{if(clearTimeout(a),c===0)try{let d=JSON.parse(s),f=new Ye.ExecutableResponse(d);return t(f)}catch(d){if(d instanceof Ye.ExecutableResponseError)return n(d);return n(new Ye.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return n(new is(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await bn.promises.realpath(this.outputFile)}catch{return}if(!(await bn.promises.lstat(e)).isFile())return;let t=await bn.promises.readFile(e,{encoding:"utf8"});if(t==="")return;try{let n=JSON.parse(t);if(new Ye.ExecutableResponse(n).isValid())return new Ye.ExecutableResponse(n);return}catch(n){if(n instanceof Ye.ExecutableResponseError)throw n;throw new Ye.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<t.length;n++)if(t[n][0]==='"'&&t[n].slice(-1)==='"')t[n]=t[n].slice(1,-1);return t}}Xd.PluggableAuthHandler=os});var ls=r(function(as){Object.defineProperty(as,"__esModule",{value:!0});as.PluggableAuthClient=as.ExecutableError=void 0;var Qd=Wt(),Zd=rs(),vi=ss(),hT=ss();Object.defineProperty(as,"ExecutableError",{enumerable:!0,get:function(){return hT.ExecutableError}});var mT=30000,Yd=5000,Wd=120000,gT="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",zd=1;class jd extends Qd.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){super(e);if(!e.credential_source.executable)throw Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=mT;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Yd||this.timeoutMillis>Wd)throw Error(`Timeout must be between ${Yd} and ${Wd} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new vi.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[gT]!=="1")throw 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=void 0;if(this.outputFile)e=await this.handler.retrieveCachedResponse();if(!e){let t=new Map;if(t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile)t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();if(n)t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n);e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>zd)throw Error(`Version of executable is not currently supported, maximum supported version is ${zd}.`);if(!e.success)throw new vi.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile){if(!e.expirationTime)throw new Zd.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 Error("Executable response is expired.");return e.subjectToken}}as.PluggableAuthClient=jd});var us=r(function(af){Object.defineProperty(af,"__esModule",{value:!0});af.ExternalAccountClient=void 0;var tf=Wt(),nf=Ko(),rf=Wo(),of=ls();class sf{constructor(){throw 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){if(e&&e.type===tf.EXTERNAL_ACCOUNT_TYPE)if(e.credential_source?.environment_id)return new rf.AwsClient(e);else if(e.credential_source?.executable)return new of.PluggableAuthClient(e);else return new nf.IdentityPoolClient(e);else return null}}af.ExternalAccountClient=sf});var ds=r(function(ff){Object.defineProperty(ff,"__esModule",{value:!0});ff.ExternalAccountAuthorizedUserClient=ff.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Ai=Ze(),Ti=Vo(),Ci=qe(),uf=p("stream"),cf=Wt();ff.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var _T="https://sts.{universeDomain}/v1/oauthtoken";class cs extends Ti.OAuthClientAuthHandler{#e;constructor(e){super(e);this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let n={...cs.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};Ai.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),s=o.data;return s.res=o,s}catch(o){if(o instanceof Ci.GaxiosError&&o.response)throw Ti.getErrorFromOAuthErrorResponse(o.response.data,o);throw o}}}class df extends Ai.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e);if(e.universe_domain)this.universeDomain=e.universe_domain;this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};if(this.externalAccountAuthorizedUserHandler=new cs({tokenRefreshEndpoint:e.token_url??_T.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!=="number")this.eagerRefreshThresholdMillis=cf.EXPIRATION_TIME_OFFSET;else this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Ci.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof uf.Readable;if(!t&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);if(this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1000,res:e.res},e.refresh_token!==void 0)this.refreshToken=e.refresh_token;return this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}ff.ExternalAccountAuthorizedUserClient=df});var hs=r(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.GdchClient=yf.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var hf=p("crypto"),mf=p("fs"),gf=p("https"),_f=Bt(),ET=3600;yf.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";class ps extends _f.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300000;constructor(e={}){super(e);this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||ET,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw Error("Audience cannot be null or empty for GDCH service account credentials.");return new ps({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==yf.GDCH_SERVICE_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${yf.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw Error("Only format version 1 is supported.");if(!e.project)throw Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),t={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},n={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:t,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath)n.agent=await this.getCaAgent();try{let o=await this.transporter.request(n),s=o.data;if(!s.access_token)throw Error("Token response did not contain an access_token.");if(!s.expires_in)throw Error("Token response did not contain an expires_in field.");let a={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1000};return this.emit("tokens",a),{res:o,tokens:a}}catch(o){if(o&&o.config&&o.config.data)try{if(typeof o.config.data==="string"){let s=JSON.parse(o.config.data);if(s.subject_token)s.subject_token="***REDACTED***",o.config.data=JSON.stringify(s)}else if(typeof o.config.data==="object"&&o.config.data.subject_token)o.config.data.subject_token="***REDACTED***"}catch{}if(o instanceof Error)o.message=`Error getting access token for GDCH service account: ${o.message}, iss: ${this.serviceIdentityName}`;throw o}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},t=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,n=Math.floor(Date.now()/1000),o={iss:t,sub:t,iat:n,exp:n+this.lifetime,aud:this.tokenServerUri},s=this.base64UrlEncode(JSON.stringify(e)),a=this.base64UrlEncode(JSON.stringify(o)),c=`${s}.${a}`,d=hf.sign("sha256",Buffer.from(c),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),f=this.base64UrlEncode(d);return`${c}.${f}`}async requestAsync(e,t=!1){if(this.caCertPath&&!e.agent){let n=(e.url||"").toString();if(!n.includes("googleapis.com")&&!n.includes("google.com"))e.agent=await this.getCaAgent()}return super.requestAsync(e,t)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),t=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!t)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let n=this.caCertPath;return this.caAgentPromise=(async()=>{try{let o=await mf.promises.readFile(n);return new gf.Agent({ca:o})}catch(o){if(this.cachedCaCertPath===n)this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;if(o instanceof Error)o.message=`Error reading certificate file from CA cert path, value '${n}': ${o.message}`;throw o}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e==="string"?Buffer.from(e):e).toString("base64url")}}yf.GdchClient=ps});var kf=r(function(Nf){Object.defineProperty(Nf,"__esModule",{value:!0});Nf.GoogleAuth=Nf.GoogleAuthExceptionMessages=void 0;var vf=p("child_process"),It=p("fs"),Tf=qe(),wt=rr(),Af=p("os"),rn=p("path"),Cf=ir(),Sf=Ao(),If=Co(),wf=So(),ct=Oo(),Si=Fo(),dt=Ho(),Rf=us(),Rt=Wt(),qn=Ze(),Ii=ds(),On=hs(),wi=mt();Nf.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.
|
|
22
|
+
${g}`,E=`${c}/${e.region}/${i}/${nT}`,y=`${Rd}
|
|
23
|
+
${s}
|
|
24
|
+
${E}
|
|
25
|
+
`+await e.crypto.sha256DigestHex(_),v=await rT(e.crypto,e.securityCredentials.secretAccessKey,c,e.region,i),C=await dr(e.crypto,v,y),T=`${Rd} Credential=${e.securityCredentials.accessKeyId}/${E}, SignedHeaders=${m}, Signature=${mi.fromArrayBufferToHex(C)}`;return{amzDate:t.has("date")?void 0:s,authorizationHeader:T,canonicalQuerystring:e.canonicalQuerystring}}});var Ud=r(function(Dd){Object.defineProperty(Dd,"__esModule",{value:!0});Dd.DefaultAwsSecurityCredentialsSupplier=void 0;var nn=Ze();class kd{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.#r)return this.#r;let t=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));if(!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:t};nn.AuthClient.setMethodName(n,"getAwsRegion");let i=await e.transporter.request(n);return i.data.substr(0,i.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let t=new Headers;if(this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(t,e.transporter),i=await this.#n(n,t,e.transporter);return{accessKeyId:i.AccessKeyId,secretAccessKey:i.SecretAccessKey,token:i.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return nn.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return nn.AuthClient.setMethodName(n,"#getAwsRoleName"),(await t.request(n)).data}async#n(e,t,n){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t,responseType:"json"};return nn.AuthClient.setMethodName(i,"#retrieveAwsSecurityCredentials"),(await n.request(i)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)return{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN};return null}}Dd.DefaultAwsSecurityCredentialsSupplier=kd});var Wo=r(function(Od){Object.defineProperty(Od,"__esModule",{value:!0});Od.AwsClient=void 0;var Gd=Yo(),bd=Wt(),Ld=Ud(),gi=mt(),qd=Oe();class _i extends bd.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 t=gi.originalOrCamelOptions(e),n=t.get("credential_source"),i=t.get("aws_security_credentials_supplier");if(!n&&!i)throw Error("A credential source or AWS security credentials supplier must be specified.");if(n&&i)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=_i.#e,this.credentialSourceType="programmatic";else{let o=gi.originalOrCamelOptions(n);this.environmentId=o.get("environment_id");let s=o.get("region_url"),c=o.get("url"),d=o.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Ld.DefaultAwsSecurityCredentialsSupplier({regionUrl:s,securityCredentialsUrl:c,imdsV2SessionTokenUrl:d}),this.regionalCredVerificationUrl=o.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 Error('No valid AWS "credential_source" provided');else if(parseInt(e[2],10)!==1)throw Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){if(!this.awsRequestSigner)this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Gd.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region);let e=await this.awsRequestSigner.getRequestOptions({..._i.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return qd.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,o)=>t.push({key:o,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}}Od.AwsClient=_i});var rs=r(function(Bd){Object.defineProperty(Bd,"__esModule",{value:!0});Bd.InvalidSubjectTokenError=Bd.InvalidMessageFieldError=Bd.InvalidCodeFieldError=Bd.InvalidTokenTypeFieldError=Bd.InvalidExpirationTimeFieldError=Bd.InvalidSuccessFieldError=Bd.InvalidVersionFieldError=Bd.ExecutableResponseError=Bd.ExecutableResponse=void 0;var yi="urn:ietf:params:oauth:token-type:saml2",zo="urn:ietf:params:oauth:token-type:id_token",Qo="urn:ietf:params:oauth:token-type:jwt";class Hd{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Zo("Executable response must contain a 'version' field.");if(e.success===void 0)throw new jo("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!==yi&&this.tokenType!==zo&&this.tokenType!==Qo)throw new es(`Executable response must contain a 'token_type' field when successful and it must be one of ${zo}, ${Qo}, or ${yi}.`);if(this.tokenType===yi){if(!e.saml_response)throw new Ei(`Executable response must contain a 'saml_response' field when token_type=${yi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ei(`Executable response must contain a 'id_token' field when token_type=${zo} or ${Qo}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ts("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ns("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()/1000)}}Bd.ExecutableResponse=Hd;class bt extends Error{constructor(e){super(e);Object.setPrototypeOf(this,new.target.prototype)}}Bd.ExecutableResponseError=bt;class Zo extends bt{}Bd.InvalidVersionFieldError=Zo;class jo extends bt{}Bd.InvalidSuccessFieldError=jo;class Vd extends bt{}Bd.InvalidExpirationTimeFieldError=Vd;class es extends bt{}Bd.InvalidTokenTypeFieldError=es;class ts extends bt{}Bd.InvalidCodeFieldError=ts;class ns extends bt{}Bd.InvalidMessageFieldError=ns;class Ei extends bt{}Bd.InvalidSubjectTokenError=Ei});var ss=r(function(Xd){Object.defineProperty(Xd,"__esModule",{value:!0});Xd.PluggableAuthHandler=Xd.ExecutableError=void 0;var Ye=rs(),Jd=p("child_process"),bn=p("fs");class is extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`);this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}Xd.ExecutableError=is;class os{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw Error("No command provided.");if(this.commandComponents=os.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,n)=>{let i=Jd.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),o="";i.stdout.on("data",(c)=>{o+=c}),i.stderr.on("data",(c)=>{o+=c});let s=setTimeout(()=>(i.removeAllListeners(),i.kill(),n(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",(c)=>{if(clearTimeout(s),c===0)try{let d=JSON.parse(o),f=new Ye.ExecutableResponse(d);return t(f)}catch(d){if(d instanceof Ye.ExecutableResponseError)return n(d);return n(new Ye.ExecutableResponseError(`The executable returned an invalid response: ${o}`))}else return n(new is(o,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await bn.promises.realpath(this.outputFile)}catch{return}if(!(await bn.promises.lstat(e)).isFile())return;let t=await bn.promises.readFile(e,{encoding:"utf8"});if(t==="")return;try{let n=JSON.parse(t);if(new Ye.ExecutableResponse(n).isValid())return new Ye.ExecutableResponse(n);return}catch(n){if(n instanceof Ye.ExecutableResponseError)throw n;throw new Ye.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<t.length;n++)if(t[n][0]==='"'&&t[n].slice(-1)==='"')t[n]=t[n].slice(1,-1);return t}}Xd.PluggableAuthHandler=os});var ls=r(function(as){Object.defineProperty(as,"__esModule",{value:!0});as.PluggableAuthClient=as.ExecutableError=void 0;var Qd=Wt(),Zd=rs(),vi=ss(),hT=ss();Object.defineProperty(as,"ExecutableError",{enumerable:!0,get:function(){return hT.ExecutableError}});var mT=30000,Yd=5000,Wd=120000,gT="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",zd=1;class jd extends Qd.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){super(e);if(!e.credential_source.executable)throw Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=mT;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Yd||this.timeoutMillis>Wd)throw Error(`Timeout must be between ${Yd} and ${Wd} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new vi.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[gT]!=="1")throw 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=void 0;if(this.outputFile)e=await this.handler.retrieveCachedResponse();if(!e){let t=new Map;if(t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile)t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();if(n)t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n);e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>zd)throw Error(`Version of executable is not currently supported, maximum supported version is ${zd}.`);if(!e.success)throw new vi.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile){if(!e.expirationTime)throw new Zd.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 Error("Executable response is expired.");return e.subjectToken}}as.PluggableAuthClient=jd});var us=r(function(af){Object.defineProperty(af,"__esModule",{value:!0});af.ExternalAccountClient=void 0;var tf=Wt(),nf=Ko(),rf=Wo(),of=ls();class sf{constructor(){throw 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){if(e&&e.type===tf.EXTERNAL_ACCOUNT_TYPE)if(e.credential_source?.environment_id)return new rf.AwsClient(e);else if(e.credential_source?.executable)return new of.PluggableAuthClient(e);else return new nf.IdentityPoolClient(e);else return null}}af.ExternalAccountClient=sf});var ds=r(function(ff){Object.defineProperty(ff,"__esModule",{value:!0});ff.ExternalAccountAuthorizedUserClient=ff.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Ai=Ze(),Ti=Vo(),Ci=Oe(),uf=p("stream"),cf=Wt();ff.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var _T="https://sts.{universeDomain}/v1/oauthtoken";class cs extends Ti.OAuthClientAuthHandler{#e;constructor(e){super(e);this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let n={...cs.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};Ai.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let i=await this.transporter.request(n),o=i.data;return o.res=i,o}catch(i){if(i instanceof Ci.GaxiosError&&i.response)throw Ti.getErrorFromOAuthErrorResponse(i.response.data,i);throw i}}}class df extends Ai.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e);if(e.universe_domain)this.universeDomain=e.universe_domain;this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};if(this.externalAccountAuthorizedUserHandler=new cs({tokenRefreshEndpoint:e.token_url??_T.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!=="number")this.eagerRefreshThresholdMillis=cf.EXPIRATION_TIME_OFFSET;else this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let i=await this.getRequestHeaders();e.headers=Ci.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),n=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let s=o.status,c=o.config.data instanceof uf.Readable;if(!t&&(s===401||s===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);if(this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1000,res:e.res},e.refresh_token!==void 0)this.refreshToken=e.refresh_token;return this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}ff.ExternalAccountAuthorizedUserClient=df});var hs=r(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.GdchClient=yf.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var hf=p("crypto"),mf=p("fs"),gf=p("https"),_f=Vt(),ET=3600;yf.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";class ps extends _f.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300000;constructor(e={}){super(e);this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||ET,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw Error("Audience cannot be null or empty for GDCH service account credentials.");return new ps({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==yf.GDCH_SERVICE_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${yf.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw Error("Only format version 1 is supported.");if(!e.project)throw Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),t={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},n={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:t,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath)n.agent=await this.getCaAgent();try{let i=await this.transporter.request(n),o=i.data;if(!o.access_token)throw Error("Token response did not contain an access_token.");if(!o.expires_in)throw Error("Token response did not contain an expires_in field.");let s={access_token:o.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+o.expires_in*1000};return this.emit("tokens",s),{res:i,tokens:s}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data==="string"){let o=JSON.parse(i.config.data);if(o.subject_token)o.subject_token="***REDACTED***",i.config.data=JSON.stringify(o)}else if(typeof i.config.data==="object"&&i.config.data.subject_token)i.config.data.subject_token="***REDACTED***"}catch{}if(i instanceof Error)i.message=`Error getting access token for GDCH service account: ${i.message}, iss: ${this.serviceIdentityName}`;throw i}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},t=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,n=Math.floor(Date.now()/1000),i={iss:t,sub:t,iat:n,exp:n+this.lifetime,aud:this.tokenServerUri},o=this.base64UrlEncode(JSON.stringify(e)),s=this.base64UrlEncode(JSON.stringify(i)),c=`${o}.${s}`,d=hf.sign("sha256",Buffer.from(c),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),f=this.base64UrlEncode(d);return`${c}.${f}`}async requestAsync(e,t=!1){if(this.caCertPath&&!e.agent){let n=(e.url||"").toString();if(!n.includes("googleapis.com")&&!n.includes("google.com"))e.agent=await this.getCaAgent()}return super.requestAsync(e,t)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),t=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!t)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let n=this.caCertPath;return this.caAgentPromise=(async()=>{try{let i=await mf.promises.readFile(n);return new gf.Agent({ca:i})}catch(i){if(this.cachedCaCertPath===n)this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;if(i instanceof Error)i.message=`Error reading certificate file from CA cert path, value '${n}': ${i.message}`;throw i}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e==="string"?Buffer.from(e):e).toString("base64url")}}yf.GdchClient=ps});var kf=r(function(Nf){Object.defineProperty(Nf,"__esModule",{value:!0});Nf.GoogleAuth=Nf.GoogleAuthExceptionMessages=void 0;var vf=p("child_process"),wt=p("fs"),Tf=Oe(),Rt=rr(),Af=p("os"),rn=p("path"),Cf=ir(),Sf=Ao(),If=Co(),wf=So(),ct=Oo(),Si=Fo(),dt=Ho(),Rf=us(),Pt=Wt(),qn=Ze(),Ii=ds(),On=hs(),wi=mt();Nf.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
26
26
|
To learn more about authentication and Google APIs, visit:
|
|
27
27
|
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
28
28
|
To learn more about authentication and Google APIs, visit:
|
|
29
29
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
30
30
|
To learn more about Universe Domain retrieval, visit:
|
|
31
|
-
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class Pf{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 RangeError(Nf.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);if(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((t)=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Nf.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;else 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;else throw Error(Nf.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){if(this._cachedProjectId)return this._cachedProjectId;if(!this._findProjectIdPromise)this._findProjectIdPromise=this.findAndCacheProjectId();return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let e;try{e=await wt.universe("universe-domain"),e||=qn.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=qn.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=wi.originalOrCamelOptions(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=qn.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e==="function")t=e;else n=e;if(t)this.getApplicationDefaultAsync(n).then((o)=>t(null,o.credential,o.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t){if(t instanceof ct.JWT)t.scopes=this.scopes;else if(t instanceof Rt.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t){if(t instanceof ct.JWT)t.scopes=this.scopes;else if(t instanceof Rt.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new Sf.Compute(e));throw Error(Nf.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();if(t)e.quotaProjectId=t;return this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){if(this.checkIsGCE===void 0)this.checkIsGCE=wt.getGCPResidency()||await wt.isAvailable();return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(t,e)}catch(n){if(n instanceof Error)n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`;throw n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=process.env.CLOUDSDK_CONFIG;if(!t)if(this._isWindows()){if(process.env.APPDATA)t=rn.join(process.env.APPDATA,"gcloud")}else{let s=process.env.HOME;if(s)t=rn.join(s,".config","gcloud")}if(!t)return null;let n=rn.join(t,"application_default_credentials.json");if(!It.existsSync(n))return null;return await this._getApplicationCredentialsFromFilePath(n,e)}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw Error("The file path is invalid.");try{if(e=It.realpathSync(e),!It.lstatSync(e).isFile())throw Error()}catch(o){if(o instanceof Error)o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`;throw o}let n=It.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==dt.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${dt.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new dt.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,t={}){let n,o=wi.originalOrCamelOptions(t).get("universe_domain");if(e.type===Si.USER_REFRESH_ACCOUNT_TYPE)n=new Si.UserRefreshClient(t),n.fromJSON(e);else if(e.type===dt.IMPERSONATED_ACCOUNT_TYPE)n=this.fromImpersonatedJSON(e);else if(e.type===Rt.EXTERNAL_ACCOUNT_TYPE)n=Rf.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes();else if(e.type===Ii.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE)n=new Ii.ExternalAccountAuthorizedUserClient({...e,...t});else if(e.type===On.GDCH_SERVICE_ACCOUNT_TYPE)n=new On.GdchClient(t),n.fromJSON(e);else t.scopes=this.scopes,n=new ct.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e);if(o)n.universeDomain=o;return n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let o={};if(typeof t==="function")n=t;else o=t;if(n)this.fromStreamAsync(e,o).then((s)=>n(null,s),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,t){return new Promise((n,o)=>{if(!e)throw Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",(a)=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),c=this._cacheClientFromJSON(a,t);return n(c)}catch(a){if(!this.keyFilename)throw a;let c=new ct.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(a){return o(a)}})})}fromAPIKey(e,t={}){return new ct.JWT({...t,apiKey:e})}_isWindows(){let e=Af.platform();if(e&&e.length>=3){if(e.substring(0,3).toLowerCase()==="win")return!0}return!1}async getDefaultServiceProjectId(){return new Promise((e)=>{vf.exec("gcloud config config-helper --format json",(t,n)=>{if(!t&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch(o){}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 t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(e)return e.projectId;else return null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==Rt.EXTERNAL_ACCOUNT_TYPE)return null;return await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await wt.project("project-id")}catch(e){return null}}getCredentials(e){if(e)this.getCredentialsAsync().then((t)=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof dt.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Rt.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,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[t,n]=await Promise.all([wt.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:n}}throw Error(Nf.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof On.GdchClient&&!e.apiAudience){let t=this.clientOptions,n=t.apiEndpoint||t.servicePath;if(n){let s=`${n.startsWith("http")?"":"https://"}${n}`.replace(/\/+$/,""),a=e.createWithGdchAudience(s);return this.cachedCredential=a,a}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);else if(this.keyFilename){let e=rn.resolve(this.keyFilename),t=It.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw 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 If.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,o=await(await this.getClient()).getRequestHeaders(t);return e.headers=Tf.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 wf.getEnv()}async sign(e,t){let n=await this.getClient(),o=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof dt.Impersonated)return(await n.sign(e)).signedBlob;let s=Cf.createCrypto();if(n instanceof ct.JWT&&n.key)return await s.sign(n.key,e);let a=await this.getCredentials();if(!a.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,t)}async signBlob(e,t,n,o){let s=new URL(o+`${t}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}Nf.GoogleAuth=Pf});var Gf=r(function(Mf){Object.defineProperty(Mf,"__esModule",{value:!0});Mf.IAMAuth=void 0;class Df{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}Mf.IAMAuth=Df});var Vf=r(function(Ff){Object.defineProperty(Ff,"__esModule",{value:!0});Ff.DownscopedClient=Ff.EXPIRATION_TIME_OFFSET=Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var bf=qe(),Lf=p("stream"),Fn=Ze(),qf=ui(),vT="urn:ietf:params:oauth:grant-type:token-exchange",TT="urn:ietf:params:oauth:token-type:access_token",AT="urn:ietf:params:oauth:token-type:access_token";Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Ff.EXPIRATION_TIME_OFFSET=300000;class Of extends Fn.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){super(e instanceof Fn.AuthClient?{}:e);if(e instanceof Fn.AuthClient)this.authClient=e,this.credentialAccessBoundary=t;else this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary;if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error("At least one access boundary rule needs to be defined.");else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new qf.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=bf.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof Lf.Readable;if(!t&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:vT,requestedTokenType:TT,subjectToken:e,subjectTokenType:AT},n=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=n.expires_in?new Date().getTime()+n.expires_in*1000:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:s,res:n.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 t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}Ff.DownscopedClient=Of});var Kf=r(function(Jf){Object.defineProperty(Jf,"__esModule",{value:!0});Jf.PassThroughClient=void 0;var Bf=Ze();class $f extends Bf.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}Jf.PassThroughClient=$f});var Zf=r(function(Q){var ST=Q&&Q.__createBinding||(Object.create?function(e,t,n,o){if(o===void 0)o=n;var s=Object.getOwnPropertyDescriptor(t,n);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,o,s)}:function(e,t,n,o){if(o===void 0)o=n;e[o]=t[n]}),IT=Q&&Q.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))ST(t,e,n)};Object.defineProperty(Q,"__esModule",{value:!0});Q.GoogleAuth=Q.auth=Q.GDCH_SERVICE_ACCOUNT_TYPE=Q.GdchClient=Q.PassThroughClient=Q.ExternalAccountAuthorizedUserClient=Q.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Q.ExecutableError=Q.PluggableAuthClient=Q.DownscopedClient=Q.BaseExternalAccountClient=Q.ExternalAccountClient=Q.IdentityPoolClient=Q.AwsRequestSigner=Q.AwsClient=Q.UserRefreshClient=Q.LoginTicket=Q.ClientAuthentication=Q.OAuth2Client=Q.CodeChallengeMethod=Q.Impersonated=Q.JWT=Q.JWTAccess=Q.IdTokenClient=Q.IAMAuth=Q.GCPEnv=Q.Compute=Q.DEFAULT_UNIVERSE=Q.AuthClient=Q.gaxios=Q.gcpMetadata=void 0;var Ri=kf();Object.defineProperty(Q,"GoogleAuth",{enumerable:!0,get:function(){return Ri.GoogleAuth}});Q.gcpMetadata=rr();Q.gaxios=qe();var Yf=Ze();Object.defineProperty(Q,"AuthClient",{enumerable:!0,get:function(){return Yf.AuthClient}});Object.defineProperty(Q,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Yf.DEFAULT_UNIVERSE}});var wT=Ao();Object.defineProperty(Q,"Compute",{enumerable:!0,get:function(){return wT.Compute}});var RT=So();Object.defineProperty(Q,"GCPEnv",{enumerable:!0,get:function(){return RT.GCPEnv}});var PT=Gf();Object.defineProperty(Q,"IAMAuth",{enumerable:!0,get:function(){return PT.IAMAuth}});var NT=Co();Object.defineProperty(Q,"IdTokenClient",{enumerable:!0,get:function(){return NT.IdTokenClient}});var xT=Lo();Object.defineProperty(Q,"JWTAccess",{enumerable:!0,get:function(){return xT.JWTAccess}});var kT=Oo();Object.defineProperty(Q,"JWT",{enumerable:!0,get:function(){return kT.JWT}});var DT=Ho();Object.defineProperty(Q,"Impersonated",{enumerable:!0,get:function(){return DT.Impersonated}});var gs=Bt();Object.defineProperty(Q,"CodeChallengeMethod",{enumerable:!0,get:function(){return gs.CodeChallengeMethod}});Object.defineProperty(Q,"OAuth2Client",{enumerable:!0,get:function(){return gs.OAuth2Client}});Object.defineProperty(Q,"ClientAuthentication",{enumerable:!0,get:function(){return gs.ClientAuthentication}});var MT=To();Object.defineProperty(Q,"LoginTicket",{enumerable:!0,get:function(){return MT.LoginTicket}});var UT=Fo();Object.defineProperty(Q,"UserRefreshClient",{enumerable:!0,get:function(){return UT.UserRefreshClient}});var GT=Wo();Object.defineProperty(Q,"AwsClient",{enumerable:!0,get:function(){return GT.AwsClient}});var bT=Yo();Object.defineProperty(Q,"AwsRequestSigner",{enumerable:!0,get:function(){return bT.AwsRequestSigner}});var LT=Ko();Object.defineProperty(Q,"IdentityPoolClient",{enumerable:!0,get:function(){return LT.IdentityPoolClient}});var qT=us();Object.defineProperty(Q,"ExternalAccountClient",{enumerable:!0,get:function(){return qT.ExternalAccountClient}});var OT=Wt();Object.defineProperty(Q,"BaseExternalAccountClient",{enumerable:!0,get:function(){return OT.BaseExternalAccountClient}});var FT=Vf();Object.defineProperty(Q,"DownscopedClient",{enumerable:!0,get:function(){return FT.DownscopedClient}});var Wf=ls();Object.defineProperty(Q,"PluggableAuthClient",{enumerable:!0,get:function(){return Wf.PluggableAuthClient}});Object.defineProperty(Q,"ExecutableError",{enumerable:!0,get:function(){return Wf.ExecutableError}});var zf=ds();Object.defineProperty(Q,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return zf.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Q,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return zf.ExternalAccountAuthorizedUserClient}});var HT=Kf();Object.defineProperty(Q,"PassThroughClient",{enumerable:!0,get:function(){return HT.PassThroughClient}});var Qf=hs();Object.defineProperty(Q,"GdchClient",{enumerable:!0,get:function(){return Qf.GdchClient}});Object.defineProperty(Q,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return Qf.GDCH_SERVICE_ACCOUNT_TYPE}});IT(Go(),Q);var VT=new Ri.GoogleAuth;Q.auth=VT});var Kh=i(ca(),1),Yh=i(Zf(),1);import{createWriteStream as BT}from"fs";import*as Fi from"fs/promises";import{writeFile as $T}from"fs/promises";import{Readable as JT}from"stream";import{finished as XT}from"stream/promises";import*as Wh from"ws";import*as zh from"path";var KT=void 0,YT=void 0;function WT(){return{geminiUrl:KT,vertexUrl:YT}}function zT(e,t,n,o){var s,a;if(!(e===null||e===void 0?void 0:e.baseUrl)){let c=WT();if(t)return(s=c.vertexUrl)!==null&&s!==void 0?s:n;else return(a=c.geminiUrl)!==null&&a!==void 0?a:o}return e.baseUrl}class xt{}function z(e,t){let n=/\{([^}]+)\}/g;return e.replace(n,(o,s)=>{if(Object.prototype.hasOwnProperty.call(t,s)){let a=t[s];return a!==void 0&&a!==null?String(a):""}else throw Error(`Key '${s}' not found in valueMap.`)})}function u(e,t,n){for(let a=0;a<t.length-1;a++){let c=t[a];if(c.endsWith("[]")){let d=c.slice(0,-2);if(!(d in e))if(Array.isArray(n))e[d]=Array.from({length:n.length},()=>({}));else throw Error(`Value must be a list given an array path ${c}`);if(Array.isArray(e[d])){let f=e[d];if(Array.isArray(n))for(let h=0;h<f.length;h++){let m=f[h];u(m,t.slice(a+1),n[h])}else for(let h of f)u(h,t.slice(a+1),n)}return}else if(c.endsWith("[0]")){let d=c.slice(0,-3);if(!(d in e))e[d]=[{}];let f=e[d];u(f[0],t.slice(a+1),n);return}if(!e[c]||typeof e[c]!=="object")e[c]={};e=e[c]}let o=t[t.length-1],s=e[o];if(s!==void 0){if(!n||typeof n==="object"&&Object.keys(n).length===0)return;if(n===s)return;if(typeof s==="object"&&typeof n==="object"&&s!==null&&n!==null)Object.assign(s,n);else throw Error(`Cannot set value for an existing key. Key: ${o}`)}else if(o==="_self"&&typeof n==="object"&&n!==null&&!Array.isArray(n))Object.assign(e,n);else e[o]=n}function l(e,t,n=void 0){try{if(t.length===1&&t[0]==="_self")return e;for(let o=0;o<t.length;o++){if(typeof e!=="object"||e===null)return n;let s=t[o];if(s.endsWith("[]")){let a=s.slice(0,-2);if(a in e){let c=e[a];if(!Array.isArray(c))return n;return c.map((d)=>l(d,t.slice(o+1),n))}else return n}else e=e[s]}return e}catch(o){if(o instanceof TypeError)return n;throw o}}function QT(e,t){for(let[n,o]of Object.entries(t)){let s=n.split("."),a=o.split("."),c=new Set,d=-1;for(let f=0;f<s.length;f++)if(s[f]==="*"){d=f;break}if(d!==-1&&a.length>d)for(let f=d;f<a.length;f++){let h=a[f];if(h!=="*"&&!h.endsWith("[]")&&!h.endsWith("[0]"))c.add(h)}vs(e,s,a,0,c)}}function vs(e,t,n,o,s){if(o>=t.length)return;if(typeof e!=="object"||e===null)return;let a=t[o];if(a.endsWith("[]")){let c=a.slice(0,-2),d=e;if(c in d&&Array.isArray(d[c]))for(let f of d[c])vs(f,t,n,o+1,s)}else if(a==="*"){if(typeof e==="object"&&e!==null&&!Array.isArray(e)){let c=e,d=Object.keys(c).filter((h)=>!h.startsWith("_")&&!s.has(h)),f={};for(let h of d)f[h]=c[h];for(let[h,m]of Object.entries(f)){let g=[];for(let _ of n.slice(o))if(_==="*")g.push(h);else g.push(_);u(c,g,m)}for(let h of d)delete c[h]}}else{let c=e;if(a in c)vs(c[a],t,n,o+1,s)}}function Fs(e){if(typeof e!=="string")throw Error("fromImageBytes must be a string");return e}function ZT(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["operationName"],n);let o=l(e,["resourceName"]);if(o!=null)u(t,["_url","resourceName"],o);return t}function jT(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["response","generateVideoResponse"]);if(c!=null)u(t,["response"],tA(c));return t}function eA(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["response"]);if(c!=null)u(t,["response"],nA(c));return t}function tA(e){let t={},n=l(e,["generatedSamples"]);if(n!=null){let a=n;if(Array.isArray(a))a=a.map((c)=>rA(c));u(t,["generatedVideos"],a)}let o=l(e,["raiMediaFilteredCount"]);if(o!=null)u(t,["raiMediaFilteredCount"],o);let s=l(e,["raiMediaFilteredReasons"]);if(s!=null)u(t,["raiMediaFilteredReasons"],s);return t}function nA(e){let t={},n=l(e,["videos"]);if(n!=null){let a=n;if(Array.isArray(a))a=a.map((c)=>iA(c));u(t,["generatedVideos"],a)}let o=l(e,["raiMediaFilteredCount"]);if(o!=null)u(t,["raiMediaFilteredCount"],o);let s=l(e,["raiMediaFilteredReasons"]);if(s!=null)u(t,["raiMediaFilteredReasons"],s);return t}function rA(e){let t={},n=l(e,["video"]);if(n!=null)u(t,["video"],cA(n));return t}function iA(e){let t={},n=l(e,["_self"]);if(n!=null)u(t,["video"],dA(n));return t}function oA(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["_url","operationName"],n);return t}function sA(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["_url","operationName"],n);return t}function aA(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["response"]);if(c!=null)u(t,["response"],lA(c));return t}function lA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["parent"]);if(o!=null)u(t,["parent"],o);let s=l(e,["documentName"]);if(s!=null)u(t,["documentName"],s);return t}function Hs(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["response"]);if(c!=null)u(t,["response"],uA(c));return t}function uA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["parent"]);if(o!=null)u(t,["parent"],o);let s=l(e,["documentName"]);if(s!=null)u(t,["documentName"],s);return t}function cA(e){let t={},n=l(e,["uri"]);if(n!=null)u(t,["uri"],n);let o=l(e,["encodedVideo"]);if(o!=null)u(t,["videoBytes"],Fs(o));let s=l(e,["encoding"]);if(s!=null)u(t,["mimeType"],s);return t}function dA(e){let t={},n=l(e,["gcsUri"]);if(n!=null)u(t,["uri"],n);let o=l(e,["bytesBase64Encoded"]);if(o!=null)u(t,["videoBytes"],Fs(o));let s=l(e,["mimeType"]);if(s!=null)u(t,["mimeType"],s);return t}var jf;(function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(jf||(jf={}));var ep;(function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"})(ep||(ep={}));var tp;(function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"})(tp||(tp={}));var on;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"})(on||(on={}));var np;(function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"})(np||(np={}));var rp;(function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(rp||(rp={}));var ip;(function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ip||(ip={}));var op;(function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(op||(op={}));var sp;(function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(sp||(sp={}));var ap;(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(ap||(ap={}));var lp;(function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"})(lp||(lp={}));var up;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(up||(up={}));var ln;(function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(ln||(ln={}));var cp;(function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"})(cp||(cp={}));var dp;(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(dp||(dp={}));var fp;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(fp||(fp={}));var pp;(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"})(pp||(pp={}));var hp;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"})(hp||(hp={}));var un;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"})(un||(un={}));var Me;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER"})(Me||(Me={}));var mp;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(mp||(mp={}));var gp;(function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(gp||(gp={}));var _p;(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(_p||(_p={}));var yp;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"})(yp||(yp={}));var Ep;(function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Ep||(Ep={}));var vp;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"})(vp||(vp={}));var Tp;(function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"})(Tp||(Tp={}));var Ap;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Ap||(Ap={}));var Ui;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"})(Ui||(Ui={}));var Cp;(function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"})(Cp||(Cp={}));var Sp;(function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(Sp||(Sp={}));var Ip;(function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(Ip||(Ip={}));var wp;(function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(wp||(wp={}));var Rp;(function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Rp||(Rp={}));var Pp;(function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"})(Pp||(Pp={}));var Np;(function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"})(Np||(Np={}));var xp;(function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.HIGH="HIGH"})(xp||(xp={}));var Ts;(function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(Ts||(Ts={}));var kp;(function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(kp||(kp={}));var Dp;(function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"})(Dp||(Dp={}));var Mp;(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"})(Mp||(Mp={}));var Up;(function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"})(Up||(Up={}));var Gp;(function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"})(Gp||(Gp={}));var bp;(function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"})(bp||(bp={}));var Lp;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"})(Lp||(Lp={}));var qp;(function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"})(qp||(qp={}));var Op;(function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"})(Op||(Op={}));var Fp;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Fp||(Fp={}));var Hp;(function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"})(Hp||(Hp={}));var fr;(function(e){e.COLLECTION="COLLECTION"})(fr||(fr={}));var Vp;(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"})(Vp||(Vp={}));var Gi;(function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT"})(Gi||(Gi={}));var Bp;(function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})(Bp||(Bp={}));var $p;(function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"})($p||($p={}));var Jp;(function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Jp||(Jp={}));var Xp;(function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Xp||(Xp={}));var Kp;(function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Kp||(Kp={}));var Yp;(function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Yp||(Yp={}));var Wp;(function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"})(Wp||(Wp={}));var zp;(function(e){e.ASSET="ASSET",e.STYLE="STYLE"})(zp||(zp={}));var Qp;(function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"})(Qp||(Qp={}));var Zp;(function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"})(Zp||(Zp={}));var jp;(function(e){e.CROP="CROP",e.PAD="PAD"})(jp||(jp={}));var eh;(function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(eh||(eh={}));var th;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"})(th||(th={}));var nh;(function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"})(nh||(nh={}));var rh;(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(rh||(rh={}));var ih;(function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"})(ih||(ih={}));var oh;(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(oh||(oh={}));var sh;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"})(sh||(sh={}));var ah;(function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(ah||(ah={}));var lh;(function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(lh||(lh={}));var uh;(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"})(uh||(uh={}));var ch;(function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(ch||(ch={}));var dh;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"})(dh||(dh={}));var fh;(function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(fh||(fh={}));var ph;(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"})(ph||(ph={}));var Bn;(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"})(Bn||(Bn={}));class yn{constructor(e){let t={};for(let n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class Hn{get text(){var e,t,n,o,s,a,c,d;if(((o=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||o===void 0?void 0:o.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning text from the first one.");let f="",h=!1,m=[];for(let g of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[_,v]of Object.entries(g))if(_!=="text"&&_!=="thought"&&_!=="thoughtSignature"&&(v!==null||v!==void 0))m.push(_);if(typeof g.text==="string"){if(typeof g.thought==="boolean"&&g.thought)continue;h=!0,f+=g.text}}if(m.length>0)console.warn(`there are non-text parts ${m} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);return h?f:void 0}get data(){var e,t,n,o,s,a,c,d;if(((o=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||o===void 0?void 0:o.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning data from the first one.");let f="",h=[];for(let m of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[g,_]of Object.entries(m))if(g!=="inlineData"&&(_!==null||_!==void 0))h.push(g);if(m.inlineData&&typeof m.inlineData.data==="string")f+=atob(m.inlineData.data)}if(h.length>0)console.warn(`there are non-data parts ${h} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);return f.length>0?btoa(f):void 0}get functionCalls(){var e,t,n,o,s,a,c,d;if(((o=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||o===void 0?void 0:o.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning function calls from the first one.");let f=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((h)=>h.functionCall).map((h)=>h.functionCall).filter((h)=>h!==void 0);if((f===null||f===void 0?void 0:f.length)===0)return;return f}get executableCode(){var e,t,n,o,s,a,c,d,f;if(((o=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||o===void 0?void 0:o.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning executable code from the first one.");let h=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((m)=>m.executableCode).map((m)=>m.executableCode).filter((m)=>m!==void 0);if((h===null||h===void 0?void 0:h.length)===0)return;return(f=h===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.code}get codeExecutionResult(){var e,t,n,o,s,a,c,d,f;if(((o=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||o===void 0?void 0:o.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let h=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((m)=>m.codeExecutionResult).map((m)=>m.codeExecutionResult).filter((m)=>m!==void 0);if((h===null||h===void 0?void 0:h.length)===0)return;return(f=h===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.output}}class As{}class Qh{}class Zh{}class jh{}class em{}class tm{}class Cs{}class Ss{}class Is{}class nm{}class bi{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new bi,o,s=e;if(t)o=eA(s);else o=jT(s);return Object.assign(n,o),n}}class rm{}class ws{}class im{}class Rs{}class Ps{}class om{}class sm{}class am{}class Vs{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new Vs,s=aA(e);return Object.assign(n,s),n}}class lm{}class um{}class cm{}class dm{}class Ns{}class fm{get text(){var e,t,n;let o="",s=!1,a=[];for(let c of(n=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&n!==void 0?n:[]){for(let[d,f]of Object.entries(c))if(d!=="text"&&d!=="thought"&&f!==null)a.push(d);if(typeof c.text==="string"){if(typeof c.thought==="boolean"&&c.thought)continue;s=!0,o+=c.text}}if(a.length>0)console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);return s?o:void 0}get data(){var e,t,n;let o="",s=[];for(let a of(n=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&n!==void 0?n:[]){for(let[c,d]of Object.entries(a))if(c!=="inlineData"&&d!==null)s.push(c);if(a.inlineData&&typeof a.inlineData.data==="string")o+=atob(a.inlineData.data)}if(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.`);return o.length>0?btoa(o):void 0}}class pm{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0];return}}class Hi{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new Hi,s=Hs(e);return Object.assign(n,s),n}}function pe(e,t){if(!t||typeof t!=="string")throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else if(t.indexOf("/")>=0){let n=t.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${t}`;else if(t.startsWith("models/")||t.startsWith("tunedModels/"))return t;else return`models/${t}`}function hm(e,t){let n=pe(e,t);if(!n)return"";if(n.startsWith("publishers/")&&e.isVertexAI())return`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`;else if(n.startsWith("models/")&&e.isVertexAI())return`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`;else return n}function mm(e){if(Array.isArray(e))return e.map((t)=>Li(t));else return[Li(e)]}function Li(e){if(typeof e==="object"&&e!==null)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function gm(e){let t=Li(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function _m(e){let t=Li(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function hh(e){if(e===null||e===void 0)throw Error("PartUnion is required");if(typeof e==="object")return e;if(typeof e==="string")return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function ym(e){if(e===null||e===void 0||Array.isArray(e)&&e.length===0)throw Error("PartListUnion is required");if(Array.isArray(e))return e.map((t)=>hh(t));return[hh(e)]}function xs(e){return e!==null&&e!==void 0&&typeof e==="object"&&"parts"in e&&Array.isArray(e.parts)}function mh(e){return e!==null&&e!==void 0&&typeof e==="object"&&"functionCall"in e}function gh(e){return e!==null&&e!==void 0&&typeof e==="object"&&"functionResponse"in e}function Le(e){if(e===null||e===void 0)throw Error("ContentUnion is required");if(xs(e))return e;return{role:"user",parts:ym(e)}}function Bs(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap((n)=>{let o=Le(n);if(o.parts&&o.parts.length>0&&o.parts[0].text!==void 0)return[o.parts[0].text];return[]});else if(e.isVertexAI()){let n=Le(t);if(n.parts&&n.parts.length>0&&n.parts[0].text!==void 0)return[n.parts[0].text];return[]}if(Array.isArray(t))return t.map((n)=>Le(n));return[Le(t)]}function We(e){if(e===null||e===void 0||Array.isArray(e)&&e.length===0)throw Error("contents are required");if(!Array.isArray(e)){if(mh(e)||gh(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Le(e)]}let t=[],n=[],o=xs(e[0]);for(let s of e){let a=xs(s);if(a!=o)throw 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(a)t.push(s);else if(mh(s)||gh(s))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else n.push(s)}if(!o)t.push({role:"user",parts:ym(n)});return t}function fA(e,t){if(e.includes("null"))t.nullable=!0;let n=e.filter((o)=>o!=="null");if(n.length===1)t.type=Object.values(on).includes(n[0].toUpperCase())?n[0].toUpperCase():on.TYPE_UNSPECIFIED;else{t.anyOf=[];for(let o of n)t.anyOf.push({type:Object.values(on).includes(o.toUpperCase())?o.toUpperCase():on.TYPE_UNSPECIFIED})}}function Jn(e){let t={},n=["items"],o=["anyOf"],s=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let a=e.anyOf;if(a!=null&&a.length==2){if(a[0].type==="null")t.nullable=!0,e=a[1];else if(a[1].type==="null")t.nullable=!0,e=a[0]}if(e.type instanceof Array)fA(e.type,t);for(let[c,d]of Object.entries(e)){if(d==null)continue;if(c=="type"){if(d==="null")throw Error("type: null can not be the only possible type for the field.");if(d instanceof Array)continue;t.type=Object.values(on).includes(d.toUpperCase())?d.toUpperCase():on.TYPE_UNSPECIFIED}else if(n.includes(c))t[c]=Jn(d);else if(o.includes(c)){let f=[];for(let h of d){if(h.type=="null"){t.nullable=!0;continue}f.push(Jn(h))}t[c]=f}else if(s.includes(c)){let f={};for(let[h,m]of Object.entries(d))f[h]=Jn(m);t[c]=f}else{if(c==="additionalProperties")continue;t[c]=d}}return t}function $s(e){return Jn(e)}function Yn(e){return e}function Js(e){if(typeof e==="object")return e;else if(typeof e==="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};else throw Error(`Unsupported speechConfig type: ${typeof e}`)}function Xs(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Wn(e){if(e.functionDeclarations)for(let t of e.functionDeclarations){if(t.parameters){if(!Object.keys(t.parameters).includes("$schema"))t.parameters=Jn(t.parameters);else if(!t.parametersJsonSchema)t.parametersJsonSchema=t.parameters,delete t.parameters}if(t.response){if(!Object.keys(t.response).includes("$schema"))t.response=Jn(t.response);else if(!t.responseJsonSchema)t.responseJsonSchema=t.response,delete t.response}}return e}function zn(e){if(e===void 0||e===null)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let n of e)t.push(n);return t}function pA(e,t,n,o=1){let s=!t.startsWith(`${n}/`)&&t.split("/").length===o;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${n}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(s)return`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`;else return t;if(s)return`${n}/${t}`;return t}function Ot(e,t){if(typeof t!=="string")throw Error("name must be a string");return pA(e,t,"cachedContents")}function Em(e){switch(e){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 e}}function En(e){return Fs(e)}function hA(e){return e!==null&&e!==void 0&&typeof e==="object"&&"name"in e}function vm(e){return e!==null&&e!==void 0&&typeof e==="object"&&"video"in e}function Tm(e){return e!==null&&e!==void 0&&typeof e==="object"&&"uri"in e}function Ks(e){var t;let n;if(hA(e))n=e.name;if(Tm(e)){if(n=e.uri,n===void 0)return}if(vm(e)){if(n=(t=e.video)===null||t===void 0?void 0:t.uri,n===void 0)return}if(typeof e==="string")n=e;if(n===void 0)throw Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){let s=n.split("files/")[1].match(/[a-z0-9]+/);if(s===null)throw Error(`Could not extract file name from URI ${n}`);n=s[0]}else if(n.startsWith("files/"))n=n.split("files/")[1];return n}function Am(e,t){let n;if(e.isVertexAI())n=t?"publishers/google/models":"models";else n=t?"models":"tunedModels";return n}function Cm(e){for(let t of["models","tunedModels","publisherModels"])if(mA(e,t))return e[t];return[]}function mA(e,t){return e!==null&&typeof e==="object"&&t in e}function gA(e,t={}){let n=e,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};if(n.outputSchema)o.responseJsonSchema=n.outputSchema;if(t.behavior)o.behavior=t.behavior;return{functionDeclarations:[o]}}function _A(e,t={}){let n=[],o=new Set;for(let s of e){let a=s.name;if(o.has(a))throw Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);o.add(a);let c=gA(s,t);if(c.functionDeclarations)n.push(...c.functionDeclarations)}return{functionDeclarations:n}}function Sm(e,t){let n;if(typeof t==="string")if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))n={format:"vertex-dataset",vertexDatasetName:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))n={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;let o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,s=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(s>0||o!==1)throw Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||s!==1)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function yA(e){if(typeof e!=="string")return e;let t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};else if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};else throw Error(`Unsupported destination: ${t}`)}function Im(e){if(typeof e!=="object"||e===null)return{};let t=e,n=t.inlinedResponses;if(typeof n!=="object"||n===null)return e;let s=n.inlinedResponses;if(!Array.isArray(s)||s.length===0)return e;let a=!1;for(let c of s){if(typeof c!=="object"||c===null)continue;let f=c.response;if(typeof f!=="object"||f===null)continue;if(f.embedding!==void 0){a=!0;break}}if(a)t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses;return e}function Qn(e,t){let n=t;if(!e.isVertexAI())if(/batches\/[^/]+$/.test(n))return n.split("/").pop();else throw Error(`Invalid batch job name: ${n}.`);if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();else if(/^\d+$/.test(n))return n;else throw Error(`Invalid batch job name: ${n}.`)}function wm(e){let t=e;if(t==="BATCH_STATE_UNSPECIFIED")return"JOB_STATE_UNSPECIFIED";else if(t==="BATCH_STATE_PENDING")return"JOB_STATE_PENDING";else if(t==="BATCH_STATE_RUNNING")return"JOB_STATE_RUNNING";else if(t==="BATCH_STATE_SUCCEEDED")return"JOB_STATE_SUCCEEDED";else if(t==="BATCH_STATE_FAILED")return"JOB_STATE_FAILED";else if(t==="BATCH_STATE_CANCELLED")return"JOB_STATE_CANCELLED";else if(t==="BATCH_STATE_EXPIRED")return"JOB_STATE_EXPIRED";else return t}function EA(e){return e.includes("gemini")&&e!=="gemini-embedding-001"||e.includes("maas")}function vA(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function TA(e){let t={},n=l(e,["responsesFile"]);if(n!=null)u(t,["fileName"],n);let o=l(e,["inlinedResponses","inlinedResponses"]);if(o!=null){let a=o;if(Array.isArray(a))a=a.map((c)=>tC(c));u(t,["inlinedResponses"],a)}let s=l(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["inlinedEmbedContentResponses"],a)}return t}function AA(e){let t={},n=l(e,["predictionsFormat"]);if(n!=null)u(t,["format"],n);let o=l(e,["gcsDestination","outputUriPrefix"]);if(o!=null)u(t,["gcsUri"],o);let s=l(e,["bigqueryDestination","outputUri"]);if(s!=null)u(t,["bigqueryUri"],s);let a=l(e,["vertexMultimodalDatasetDestination"]);if(a!=null)u(t,["vertexDataset"],fC(a));return t}function CA(e){let t={},n=l(e,["format"]);if(n!=null)u(t,["predictionsFormat"],n);let o=l(e,["gcsUri"]);if(o!=null)u(t,["gcsDestination","outputUriPrefix"],o);let s=l(e,["bigqueryUri"]);if(s!=null)u(t,["bigqueryDestination","outputUri"],s);let a=l(e,["vertexDataset"]);if(a!=null)u(t,["vertexMultimodalDatasetDestination"],pC(a));if(l(e,["fileName"])!==void 0)throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedResponses"])!==void 0)throw Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedEmbedContentResponses"])!==void 0)throw Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Di(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata","displayName"]);if(o!=null)u(t,["displayName"],o);let s=l(e,["metadata","state"]);if(s!=null)u(t,["state"],wm(s));let a=l(e,["metadata","createTime"]);if(a!=null)u(t,["createTime"],a);let c=l(e,["metadata","endTime"]);if(c!=null)u(t,["endTime"],c);let d=l(e,["metadata","updateTime"]);if(d!=null)u(t,["updateTime"],d);let f=l(e,["metadata","model"]);if(f!=null)u(t,["model"],f);let h=l(e,["metadata","output"]);if(h!=null)u(t,["dest"],TA(Im(h)));return t}function ks(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["displayName"]);if(o!=null)u(t,["displayName"],o);let s=l(e,["state"]);if(s!=null)u(t,["state"],wm(s));let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["createTime"]);if(c!=null)u(t,["createTime"],c);let d=l(e,["startTime"]);if(d!=null)u(t,["startTime"],d);let f=l(e,["endTime"]);if(f!=null)u(t,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(t,["updateTime"],h);let m=l(e,["model"]);if(m!=null)u(t,["model"],m);let g=l(e,["inputConfig"]);if(g!=null)u(t,["src"],SA(g));let _=l(e,["outputConfig"]);if(_!=null)u(t,["dest"],AA(Im(_)));let v=l(e,["outputInfo"]);if(v!=null)u(t,["outputInfo"],v);let E=l(e,["completionStats"]);if(E!=null)u(t,["completionStats"],E);return t}function SA(e){let t={},n=l(e,["instancesFormat"]);if(n!=null)u(t,["format"],n);let o=l(e,["gcsSource","uris"]);if(o!=null)u(t,["gcsUri"],o);let s=l(e,["bigquerySource","inputUri"]);if(s!=null)u(t,["bigqueryUri"],s);let a=l(e,["vertexMultimodalDatasetSource","datasetName"]);if(a!=null)u(t,["vertexDatasetName"],a);return t}function IA(e,t){let n={};if(l(t,["format"])!==void 0)throw Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["bigqueryUri"])!==void 0)throw Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["vertexDatasetName"])!==void 0)throw Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(t,["fileName"]);if(o!=null)u(n,["fileName"],o);let s=l(t,["inlinedRequests"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>eC(e,c));u(n,["requests","requests"],a)}return n}function wA(e){let t={},n=l(e,["format"]);if(n!=null)u(t,["instancesFormat"],n);let o=l(e,["gcsUri"]);if(o!=null)u(t,["gcsSource","uris"],o);let s=l(e,["bigqueryUri"]);if(s!=null)u(t,["bigquerySource","inputUri"],s);let a=l(e,["vertexDatasetName"]);if(a!=null)u(t,["vertexMultimodalDatasetSource","datasetName"],a);if(l(e,["fileName"])!==void 0)throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedRequests"])!==void 0)throw Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function RA(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function PA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function NA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function xA(e){let t={},n=l(e,["content"]);if(n!=null)u(t,["content"],n);let o=l(e,["citationMetadata"]);if(o!=null)u(t,["citationMetadata"],kA(o));let s=l(e,["tokenCount"]);if(s!=null)u(t,["tokenCount"],s);let a=l(e,["finishReason"]);if(a!=null)u(t,["finishReason"],a);let c=l(e,["groundingMetadata"]);if(c!=null)u(t,["groundingMetadata"],c);let d=l(e,["avgLogprobs"]);if(d!=null)u(t,["avgLogprobs"],d);let f=l(e,["index"]);if(f!=null)u(t,["index"],f);let h=l(e,["logprobsResult"]);if(h!=null)u(t,["logprobsResult"],h);let m=l(e,["safetyRatings"]);if(m!=null){let _=m;if(Array.isArray(_))_=_.map((v)=>v);u(t,["safetyRatings"],_)}let g=l(e,["urlContextMetadata"]);if(g!=null)u(t,["urlContextMetadata"],g);return t}function kA(e){let t={},n=l(e,["citationSources"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>s);u(t,["citations"],o)}return t}function Rm(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>lC(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function DA(e,t){let n={},o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["batch","displayName"],o);if(l(e,["dest"])!==void 0)throw Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["webhookConfig"]);if(t!==void 0&&s!=null)u(t,["batch","webhookConfig"],s);return n}function MA(e,t){let n={},o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["displayName"],o);let s=l(e,["dest"]);if(t!==void 0&&s!=null)u(t,["outputConfig"],CA(yA(s)));if(l(e,["webhookConfig"])!==void 0)throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function _h(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["_url","model"],pe(e,o));let s=l(t,["src"]);if(s!=null)u(n,["batch","inputConfig"],IA(e,Sm(e,s)));let a=l(t,["config"]);if(a!=null)DA(a,n);return n}function UA(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["model"],pe(e,o));let s=l(t,["src"]);if(s!=null)u(n,["inputConfig"],wA(Sm(e,s)));let a=l(t,["config"]);if(a!=null)MA(a,n);return n}function GA(e,t){let n={},o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["batch","displayName"],o);return n}function bA(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["_url","model"],pe(e,o));let s=l(t,["src"]);if(s!=null)u(n,["batch","inputConfig"],BA(e,s));let a=l(t,["config"]);if(a!=null)GA(a,n);return n}function LA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function qA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function OA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);return t}function FA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);return t}function HA(e,t){let n={},o=l(t,["contents"]);if(o!=null){let a=Bs(e,o);if(Array.isArray(a))a=a.map((c)=>c);u(n,["requests[]","request","content"],a)}let s=l(t,["config"]);if(s!=null)u(n,["_self"],VA(s,n)),QT(n,{"requests[].*":"requests[].request.*"});return n}function VA(e,t){let n={},o=l(e,["taskType"]);if(t!==void 0&&o!=null)u(t,["requests[]","taskType"],o);let s=l(e,["title"]);if(t!==void 0&&s!=null)u(t,["requests[]","title"],s);let a=l(e,["outputDimensionality"]);if(t!==void 0&&a!=null)u(t,["requests[]","outputDimensionality"],a);if(l(e,["mimeType"])!==void 0)throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["autoTruncate"])!==void 0)throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["documentOcr"])!==void 0)throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["audioTrackExtraction"])!==void 0)throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function BA(e,t){let n={},o=l(t,["fileName"]);if(o!=null)u(n,["file_name"],o);let s=l(t,["inlinedRequests"]);if(s!=null)u(n,["requests"],HA(e,s));return n}function $A(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function JA(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let o=l(e,["id"]);if(o!=null)u(t,["id"],o);let s=l(e,["name"]);if(s!=null)u(t,["name"],s);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function XA(e){let t={},n=l(e,["allowedFunctionNames"]);if(n!=null)u(t,["allowedFunctionNames"],n);let o=l(e,["mode"]);if(o!=null)u(t,["mode"],o);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function KA(e,t,n){let o={},s=l(t,["serviceTier"]);if(n!==void 0&&s!=null)u(n,["serviceTier"],s);let a=l(t,["systemInstruction"]);if(n!==void 0&&a!=null)u(n,["systemInstruction"],Rm(Le(a)));let c=l(t,["temperature"]);if(c!=null)u(o,["temperature"],c);let d=l(t,["topP"]);if(d!=null)u(o,["topP"],d);let f=l(t,["topK"]);if(f!=null)u(o,["topK"],f);let h=l(t,["candidateCount"]);if(h!=null)u(o,["candidateCount"],h);let m=l(t,["maxOutputTokens"]);if(m!=null)u(o,["maxOutputTokens"],m);let g=l(t,["stopSequences"]);if(g!=null)u(o,["stopSequences"],g);let _=l(t,["responseLogprobs"]);if(_!=null)u(o,["responseLogprobs"],_);let v=l(t,["logprobs"]);if(v!=null)u(o,["logprobs"],v);let E=l(t,["presencePenalty"]);if(E!=null)u(o,["presencePenalty"],E);let T=l(t,["frequencyPenalty"]);if(T!=null)u(o,["frequencyPenalty"],T);let S=l(t,["seed"]);if(S!=null)u(o,["seed"],S);let A=l(t,["responseMimeType"]);if(A!=null)u(o,["responseMimeType"],A);let w=l(t,["responseSchema"]);if(w!=null)u(o,["responseSchema"],$s(w));let P=l(t,["responseJsonSchema"]);if(P!=null)u(o,["responseJsonSchema"],Yn(P));if(l(t,["routingConfig"])!==void 0)throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["modelSelectionConfig"])!==void 0)throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let N=l(t,["safetySettings"]);if(n!==void 0&&N!=null){let oe=N;if(Array.isArray(oe))oe=oe.map((se)=>uC(se));u(n,["safetySettings"],oe)}let D=l(t,["tools"]);if(n!==void 0&&D!=null){let oe=zn(D);if(Array.isArray(oe))oe=oe.map((se)=>dC(Wn(se)));u(n,["tools"],oe)}let O=l(t,["toolConfig"]);if(n!==void 0&&O!=null)u(n,["toolConfig"],cC(O));if(l(t,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let B=l(t,["cachedContent"]);if(n!==void 0&&B!=null)u(n,["cachedContent"],Ot(e,B));let X=l(t,["responseModalities"]);if(X!=null)u(o,["responseModalities"],X);let q=l(t,["mediaResolution"]);if(q!=null)u(o,["mediaResolution"],q);let Y=l(t,["speechConfig"]);if(Y!=null)u(o,["speechConfig"],Js(Y));if(l(t,["audioTimestamp"])!==void 0)throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Z=l(t,["thinkingConfig"]);if(Z!=null)u(o,["thinkingConfig"],Z);let ne=l(t,["audioTranscriptionConfig"]);if(ne!=null)u(o,["audioTranscriptionConfig"],ne);let W=l(t,["imageConfig"]);if(W!=null)u(o,["imageConfig"],jA(W));let V=l(t,["enableEnhancedCivicAnswers"]);if(V!=null)u(o,["enableEnhancedCivicAnswers"],V);if(l(t,["modelArmorConfig"])!==void 0)throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function YA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["candidates"]);if(o!=null){let h=o;if(Array.isArray(h))h=h.map((m)=>xA(m));u(t,["candidates"],h)}let s=l(e,["modelVersion"]);if(s!=null)u(t,["modelVersion"],s);let a=l(e,["promptFeedback"]);if(a!=null)u(t,["promptFeedback"],a);let c=l(e,["responseId"]);if(c!=null)u(t,["responseId"],c);let d=l(e,["usageMetadata"]);if(d!=null)u(t,["usageMetadata"],d);let f=l(e,["modelStatus"]);if(f!=null)u(t,["modelStatus"],f);return t}function WA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function zA(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Qn(e,o));return n}function QA(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],vA(n));let o=l(e,["enableWidget"]);if(o!=null)u(t,["enableWidget"],o);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function ZA(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let o=l(e,["timeRangeFilter"]);if(o!=null)u(t,["timeRangeFilter"],o);return t}function jA(e){let t={},n=l(e,["aspectRatio"]);if(n!=null)u(t,["aspectRatio"],n);let o=l(e,["imageSize"]);if(o!=null)u(t,["imageSize"],o);if(l(e,["personGeneration"])!==void 0)throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputMimeType"])!==void 0)throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputCompressionQuality"])!==void 0)throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["imageOutputOptions"])!==void 0)throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["prominentPeople"])!==void 0)throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function eC(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["request","model"],pe(e,o));let s=l(t,["contents"]);if(s!=null){let d=We(s);if(Array.isArray(d))d=d.map((f)=>Rm(f));u(n,["request","contents"],d)}let a=l(t,["metadata"]);if(a!=null)u(n,["metadata"],a);let c=l(t,["config"]);if(c!=null)u(n,["request","generationConfig"],KA(e,c,l(n,["request"],{})));return n}function tC(e){let t={},n=l(e,["response"]);if(n!=null)u(t,["response"],YA(n));let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);return t}function nC(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);if(l(e,["filter"])!==void 0)throw Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function rC(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);let a=l(e,["filter"]);if(t!==void 0&&a!=null)u(t,["_query","filter"],a);return n}function iC(e){let t={},n=l(e,["config"]);if(n!=null)nC(n,t);return t}function oC(e){let t={},n=l(e,["config"]);if(n!=null)rC(n,t);return t}function sC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["operations"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>Di(c));u(t,["batchJobs"],a)}return t}function aC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["batchPredictionJobs"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>ks(c));u(t,["batchJobs"],a)}return t}function lC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let o=l(e,["toolCall"]);if(o!=null)u(t,["toolCall"],o);let s=l(e,["toolResponse"]);if(s!=null)u(t,["toolResponse"],s);let a=l(e,["audioTranscription"]);if(a!=null)u(t,["audioTranscription"],a);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],$A(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],JA(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],RA(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let v=l(e,["thought"]);if(v!=null)u(t,["thought"],v);let E=l(e,["thoughtSignature"]);if(E!=null)u(t,["thoughtSignature"],E);let T=l(e,["videoMetadata"]);if(T!=null)u(t,["videoMetadata"],T);let S=l(e,["partMetadata"]);if(S!=null)u(t,["partMetadata"],S);let A=l(e,["mediaProcessing"]);if(A!=null)u(t,["mediaProcessing"],A);return t}function uC(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["threshold"]);if(o!=null)u(t,["threshold"],o);return t}function cC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],XA(n));let o=l(e,["retrievalConfig"]);if(o!=null)u(t,["retrievalConfig"],o);let s=l(e,["includeServerSideToolInvocations"]);if(s!=null)u(t,["includeServerSideToolInvocations"],s);return t}function dC(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],QA(n));let o=l(e,["mcpServers"]);if(o!=null){let g=o;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let a=l(e,["computerUse"]);if(a!=null)u(t,["computerUse"],a);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],ZA(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function fC(e){let t={},n=l(e,["bigqueryDestination","outputUri"]);if(n!=null)u(t,["bigqueryDestination"],n);let o=l(e,["displayName"]);if(o!=null)u(t,["displayName"],o);return t}function pC(e){let t={},n=l(e,["bigqueryDestination"]);if(n!=null)u(t,["bigqueryDestination","outputUri"],n);let o=l(e,["displayName"]);if(o!=null)u(t,["displayName"],o);return t}var qt;(function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"})(qt||(qt={}));class pn{constructor(e,t,n,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,o)}init(e,t,n){var o,s;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t===null||t===void 0?void 0:t.sdkHttpResponse,this.idxInternal=0;let a={config:{}};if(!n||Object.keys(n).length===0)a={config:{}};else if(typeof n==="object")a=Object.assign({},n);else a=n;if(a.config)a.config.pageToken=t.nextPageToken;this.paramsInternal=a,this.pageInternalSize=(s=(o=a.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 Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;if(((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0)return!0;return!1}}class Pm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_BATCH_JOBS,(n)=>this.listInternal(n),await this.listInternal(t),t),this.create=async(t)=>{if(this.apiClient.isVertexAI())t.config=this.formatDestination(t.src,t.config);return this.createInternal(t)},this.createEmbeddings=async(t)=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){let t=_h(this.apiClient,e),n=t._url,o=z("{model}:batchGenerateContent",n),c=t.batch.inputConfig.requests,d=c.requests,f=[];for(let h of d){let m=Object.assign({},h);if(m.systemInstruction){let g=m.systemInstruction;delete m.systemInstruction;let _=m.request;_.systemInstruction=g,m.request=_}f.push(m)}return c.requests=f,delete t.config,delete t._url,delete t._query,{path:o,body:t}}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];return}getBigqueryUri(e){if(typeof e==="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri;return}formatDestination(e,t){let n=t?Object.assign({},t):{},o=Date.now().toString();if(!n.displayName)n.displayName=`genaiBatchJob_${o}`;if(n.dest===void 0){let s=this.getGcsUri(e),a=this.getBigqueryUri(e);if(s)if(s.endsWith(".jsonl"))n.dest=`${s.slice(0,-6)}/dest`;else n.dest=`${s}_dest_${o}`;else if(a)n.dest=`${a}_dest_${o}`;else throw Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return n}async createInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=UA(this.apiClient,e);return c=z("batchPredictionJobs",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>ks(h))}else{let f=_h(this.apiClient,e);return c=z("{model}:batchGenerateContent",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>Di(h))}}async createEmbeddingsInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=bA(this.apiClient,e);return s=z("{model}:asyncBatchEmbedContent",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>Di(d))}}async get(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=zA(this.apiClient,e);return c=z("batchPredictionJobs/{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>ks(h))}else{let f=WA(this.apiClient,e);return c=z("batches/{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>Di(h))}}async cancel(e){var t,n,o,s;let a="",c={};if(this.apiClient.isVertexAI()){let d=NA(this.apiClient,e);a=z("batchPredictionJobs/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}else{let d=PA(this.apiClient,e);a=z("batches/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:a,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})}}async listInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=oC(e);return c=z("batchPredictionJobs",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=aC(h),g=new Ns;return Object.assign(g,m),g})}else{let f=iC(e);return c=z("batches",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=sC(h),g=new Ns;return Object.assign(g,m),g})}}async delete(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=qA(this.apiClient,e);return c=z("batchPredictionJobs/{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>FA(h))}else{let f=LA(this.apiClient,e);return c=z("batches/{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>OA(h))}}}function hC(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function mC(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function gC(e){let t={},n=l(e,["enablePromptInjectionDetection"]);if(n!=null)u(t,["enablePromptInjectionDetection"],n);let o=l(e,["environment"]);if(o!=null)u(t,["environment"],o);let s=l(e,["excludedPredefinedFunctions"]);if(s!=null)u(t,["excludedPredefinedFunctions"],s);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function yh(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>OC(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function Eh(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>FC(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function _C(e,t){let n={},o=l(e,["ttl"]);if(t!==void 0&&o!=null)u(t,["ttl"],o);let s=l(e,["expireTime"]);if(t!==void 0&&s!=null)u(t,["expireTime"],s);let a=l(e,["displayName"]);if(t!==void 0&&a!=null)u(t,["displayName"],a);let c=l(e,["contents"]);if(t!==void 0&&c!=null){let m=We(c);if(Array.isArray(m))m=m.map((g)=>yh(g));u(t,["contents"],m)}let d=l(e,["systemInstruction"]);if(t!==void 0&&d!=null)u(t,["systemInstruction"],yh(Le(d)));let f=l(e,["tools"]);if(t!==void 0&&f!=null){let m=f;if(Array.isArray(m))m=m.map((g)=>BC(g));u(t,["tools"],m)}let h=l(e,["toolConfig"]);if(t!==void 0&&h!=null)u(t,["toolConfig"],HC(h));if(l(e,["kmsKeyName"])!==void 0)throw Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function yC(e,t){let n={},o=l(e,["ttl"]);if(t!==void 0&&o!=null)u(t,["ttl"],o);let s=l(e,["expireTime"]);if(t!==void 0&&s!=null)u(t,["expireTime"],s);let a=l(e,["displayName"]);if(t!==void 0&&a!=null)u(t,["displayName"],a);let c=l(e,["contents"]);if(t!==void 0&&c!=null){let g=We(c);if(Array.isArray(g))g=g.map((_)=>Eh(_));u(t,["contents"],g)}let d=l(e,["systemInstruction"]);if(t!==void 0&&d!=null)u(t,["systemInstruction"],Eh(Le(d)));let f=l(e,["tools"]);if(t!==void 0&&f!=null){let g=f;if(Array.isArray(g))g=g.map((_)=>$C(_));u(t,["tools"],g)}let h=l(e,["toolConfig"]);if(t!==void 0&&h!=null)u(t,["toolConfig"],VC(h));let m=l(e,["kmsKeyName"]);if(t!==void 0&&m!=null)u(t,["encryption_spec","kmsKeyName"],m);return n}function EC(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["model"],hm(e,o));let s=l(t,["config"]);if(s!=null)_C(s,n);return n}function vC(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["model"],hm(e,o));let s=l(t,["config"]);if(s!=null)yC(s,n);return n}function TC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));return n}function AC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));return n}function CC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function SC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function IC(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function wC(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let o=l(e,["id"]);if(o!=null)u(t,["id"],o);let s=l(e,["name"]);if(s!=null)u(t,["name"],s);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function RC(e){let t={},n=l(e,["allowedFunctionNames"]);if(n!=null)u(t,["allowedFunctionNames"],n);let o=l(e,["mode"]);if(o!=null)u(t,["mode"],o);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function PC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));return n}function NC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));return n}function xC(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],hC(n));let o=l(e,["enableWidget"]);if(o!=null)u(t,["enableWidget"],o);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function kC(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let o=l(e,["timeRangeFilter"]);if(o!=null)u(t,["timeRangeFilter"],o);return t}function DC(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);return n}function MC(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);return n}function UC(e){let t={},n=l(e,["config"]);if(n!=null)DC(n,t);return t}function GC(e){let t={},n=l(e,["config"]);if(n!=null)MC(n,t);return t}function bC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["cachedContents"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["cachedContents"],a)}return t}function LC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["cachedContents"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["cachedContents"],a)}return t}function qC(e){let t={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function OC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let o=l(e,["toolCall"]);if(o!=null)u(t,["toolCall"],o);let s=l(e,["toolResponse"]);if(s!=null)u(t,["toolResponse"],s);let a=l(e,["audioTranscription"]);if(a!=null)u(t,["audioTranscription"],a);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],IC(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],wC(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],mC(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let v=l(e,["thought"]);if(v!=null)u(t,["thought"],v);let E=l(e,["thoughtSignature"]);if(E!=null)u(t,["thoughtSignature"],E);let T=l(e,["videoMetadata"]);if(T!=null)u(t,["videoMetadata"],T);let S=l(e,["partMetadata"]);if(S!=null)u(t,["partMetadata"],S);let A=l(e,["mediaProcessing"]);if(A!=null)u(t,["mediaProcessing"],A);return t}function FC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=l(e,["audioTranscription"]);if(o!=null)u(t,["audioTranscription"],o);let s=l(e,["codeExecutionResult"]);if(s!=null)u(t,["codeExecutionResult"],s);let a=l(e,["executableCode"]);if(a!=null)u(t,["executableCode"],a);let c=l(e,["fileData"]);if(c!=null)u(t,["fileData"],c);let d=l(e,["functionCall"]);if(d!=null)u(t,["functionCall"],d);let f=l(e,["functionResponse"]);if(f!=null)u(t,["functionResponse"],f);let h=l(e,["inlineData"]);if(h!=null)u(t,["inlineData"],h);let m=l(e,["text"]);if(m!=null)u(t,["text"],m);let g=l(e,["thought"]);if(g!=null)u(t,["thought"],g);let _=l(e,["thoughtSignature"]);if(_!=null)u(t,["thoughtSignature"],_);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let E=l(e,["mediaProcessing"]);if(E!=null)u(t,["mediaProcessing"],E);return t}function HC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],RC(n));let o=l(e,["retrievalConfig"]);if(o!=null)u(t,["retrievalConfig"],o);let s=l(e,["includeServerSideToolInvocations"]);if(s!=null)u(t,["includeServerSideToolInvocations"],s);return t}function VC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],n);let o=l(e,["retrievalConfig"]);if(o!=null)u(t,["retrievalConfig"],o);if(l(e,["includeServerSideToolInvocations"])!==void 0)throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function BC(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],xC(n));let o=l(e,["mcpServers"]);if(o!=null){let g=o;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let a=l(e,["computerUse"]);if(a!=null)u(t,["computerUse"],a);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],kC(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function $C(e){let t={},n=l(e,["retrieval"]);if(n!=null)u(t,["retrieval"],n);let o=l(e,["googleMaps"]);if(o!=null)u(t,["googleMaps"],o);let s=l(e,["mcpServers"]);if(s!=null){let E=s;if(Array.isArray(E))E=E.map((T)=>qC(T));u(t,["mcpServers"],E)}let a=l(e,["codeExecution"]);if(a!=null)u(t,["codeExecution"],a);let c=l(e,["computerUse"]);if(c!=null)u(t,["computerUse"],gC(c));let d=l(e,["enterpriseWebSearch"]);if(d!=null)u(t,["enterpriseWebSearch"],d);let f=l(e,["exaAiSearch"]);if(f!=null)u(t,["exaAiSearch"],f);let h=l(e,["functionDeclarations"]);if(h!=null){let E=h;if(Array.isArray(E))E=E.map((T)=>T);u(t,["functionDeclarations"],E)}let m=l(e,["googleSearch"]);if(m!=null)u(t,["googleSearch"],m);let g=l(e,["googleSearchRetrieval"]);if(g!=null)u(t,["googleSearchRetrieval"],g);let _=l(e,["parallelAiSearch"]);if(_!=null)u(t,["parallelAiSearch"],_);let v=l(e,["urlContext"]);if(v!=null)u(t,["urlContext"],v);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function JC(e,t){let n={},o=l(e,["ttl"]);if(t!==void 0&&o!=null)u(t,["ttl"],o);let s=l(e,["expireTime"]);if(t!==void 0&&s!=null)u(t,["expireTime"],s);return n}function XC(e,t){let n={},o=l(e,["ttl"]);if(t!==void 0&&o!=null)u(t,["ttl"],o);let s=l(e,["expireTime"]);if(t!==void 0&&s!=null)u(t,["expireTime"],s);return n}function KC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));let s=l(t,["config"]);if(s!=null)JC(s,n);return n}function YC(e,t){let n={},o=l(t,["name"]);if(o!=null)u(n,["_url","name"],Ot(e,o));let s=l(t,["config"]);if(s!=null)XC(s,n);return n}class Nm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_CACHED_CONTENTS,(n)=>this.listInternal(n),await this.listInternal(t),t)}async create(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=vC(this.apiClient,e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>h)}else{let f=EC(this.apiClient,e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>h)}}async get(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=NC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>h)}else{let f=PC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>h)}}async delete(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=AC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=SC(h),g=new Rs;return Object.assign(g,m),g})}else{let f=TC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=CC(h),g=new Rs;return Object.assign(g,m),g})}}async update(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=YC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>h)}else{let f=KC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>h)}}async listInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=GC(e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=LC(h),g=new Ps;return Object.assign(g,m),g})}else{let f=UC(e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=bC(h),g=new Ps;return Object.assign(g,m),g})}}}function Ve(e,t){var n={};for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0)n[o]=e[o];if(e!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var s=0,o=Object.getOwnPropertySymbols(e);s<o.length;s++)if(t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s]))n[o[s]]=e[o[s]]}return n}function vh(e){var t=typeof Symbol==="function"&&Symbol.iterator,n=t&&e[t],o=0;if(n)return n.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&o>=e.length)e=void 0;return{value:e&&e[o++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ne(e){return this instanceof Ne?(this.v=e,this):new Ne(e)}function Xn(e,t,n){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(e,t||[]),s,a=[];return s=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),d("next"),d("throw"),d("return",c),s[Symbol.asyncIterator]=function(){return this},s;function c(v){return function(E){return Promise.resolve(E).then(v,g)}}function d(v,E){if(o[v]){if(s[v]=function(T){return new Promise(function(S,A){a.push([v,T,S,A])>1||f(v,T)})},E)s[v]=E(s[v])}}function f(v,E){try{h(o[v](E))}catch(T){_(a[0][3],T)}}function h(v){v.value instanceof Ne?Promise.resolve(v.value.v).then(m,g):_(a[0][2],v)}function m(v){f("next",v)}function g(v){f("throw",v)}function _(v,E){if(v(E),a.shift(),a.length)f(a[0][0],a[0][1])}}function Er(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof vh==="function"?vh(e):e[Symbol.iterator](),n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n);function o(a){n[a]=e[a]&&function(c){return new Promise(function(d,f){c=e[a](c),s(d,f,c.done,c.value)})}}function s(a,c,d,f){Promise.resolve(f).then(function(h){a({value:h,done:d})},c)}}function WC(e){var t;if(e.candidates==null||e.candidates.length===0)return!1;let n=(t=e.candidates[0])===null||t===void 0?void 0:t.content;if(n===void 0)return!1;return xm(n)}function xm(e){if(e.parts===void 0||e.parts.length===0)return!1;for(let t of e.parts)if(t===void 0||Object.keys(t).length===0)return!1;return!0}function zC(e){if(e.length===0)return;for(let t of e)if(t.role!=="user"&&t.role!=="model")throw Error(`Role must be user or model, but got ${t.role}.`)}function Th(e){if(e===void 0||e.length===0)return[];let t=[],n=e.length,o=0;while(o<n)if(e[o].role==="user")t.push(e[o]),o++;else{let s=[],a=!0;while(o<n&&e[o].role==="model"){if(s.push(e[o]),a&&!xm(e[o]))a=!1;o++}if(a)t.push(...s);else t.pop()}return t}class km{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new Dm(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class Dm{constructor(e,t,n,o={},s=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=o,this.history=s,this.sendPromise=Promise.resolve(),zC(s)}async sendMessage(e){var t;await this.sendPromise;let n=Le(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(n),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var s,a,c;let d=await o,f=(a=(s=d.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content,h=d.automaticFunctionCallingHistory,m=this.getHistory(!0).length,g=[];if(h!=null)g=(c=h.slice(m))!==null&&c!==void 0?c:[];let _=f?[f]:[];this.recordHistory(n,_,g);return})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;let n=Le(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(n),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=o.then(()=>{return}).catch(()=>{return});let s=await o;return this.processStreamResponse(s,n)}getHistory(e=!1){let t=e?Th(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return Xn(this,arguments,function*(){var o,s,a,c,d,f;let h=[];try{for(var m=!0,g=Er(e),_;_=yield Ne(g.next()),o=_.done,!o;m=!0){c=_.value,m=!1;let v=c;if(WC(v)){let E=(f=(d=v.candidates)===null||d===void 0?void 0:d[0])===null||f===void 0?void 0:f.content;if(E!==void 0)h.push(E)}yield yield Ne(v)}}catch(v){s={error:v}}finally{try{if(!m&&!o&&(a=g.return))yield Ne(a.call(g))}finally{if(s)throw s.error}}this.recordHistory(t,h)})}recordHistory(e,t,n){let o=[];if(t.length>0&&t.every((s)=>s.role!==void 0))o=t;else o.push({role:"model",parts:[]});if(n&&n.length>0)this.history.push(...Th(n));else this.history.push(e);this.history.push(...o)}}class Vi extends Error{constructor(e){super(e.message);this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,Vi.prototype)}}function QC(e){let t={},n=l(e,["file"]);if(n!=null)u(t,["file"],n);return t}function ZC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function jC(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","file"],Ks(n));return t}function e0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function t0(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","file"],Ks(n));return t}function n0(e){let t={},n=l(e,["uris"]);if(n!=null)u(t,["uris"],n);return t}function r0(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);return n}function i0(e){let t={},n=l(e,["config"]);if(n!=null)r0(n,t);return t}function o0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["files"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["files"],a)}return t}function s0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["files"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>a);u(t,["files"],s)}return t}var a0=class extends xt{constructor(t){super();this.apiClient=t,this.list=async(n={})=>new pn(qt.PAGED_ITEM_FILES,(o)=>this.listInternal(o),await this.listInternal(n),n)}async upload(t){if(this.apiClient.isVertexAI())throw 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(t.file,t.config).then((n)=>n)}async download(t){await this.apiClient.downloadFile(t)}async registerFiles(t){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(t){return this.registerFilesInternal(t)}async listInternal(t){var n,o;let s,a="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=i0(t);return a=z("files",d._url),c=d._query,delete d._url,delete d._query,s=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then((f)=>f.json().then((h)=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),s.then((f)=>{let h=o0(f),m=new lm;return Object.assign(m,h),m})}}async createInternal(t){var n,o;let s,a="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=QC(t);return a=z("upload/v1beta/files",d._url),c=d._query,delete d._url,delete d._query,s=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then((f)=>f.json()),s.then((f)=>{let h=ZC(f),m=new um;return Object.assign(m,h),m})}}async get(t){var n,o;let s,a="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=t0(t);return a=z("files/{file}",d._url),c=d._query,delete d._url,delete d._query,s=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then((f)=>f.json()),s.then((f)=>f)}}async delete(t){var n,o;let s,a="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=jC(t);return a=z("files/{file}",d._url),c=d._query,delete d._url,delete d._query,s=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then((f)=>f.json().then((h)=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),s.then((f)=>{let h=e0(f),m=new cm;return Object.assign(m,h),m})}}async registerFilesInternal(t){var n,o;let s,a="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=n0(t);return a=z("files:register",d._url),c=d._query,delete d._url,delete d._query,s=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then((f)=>f.json()),s.then((f)=>{let h=s0(f),m=new dm;return Object.assign(m,h),m})}}};function l0(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Mi(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function u0(e){let t={},n=l(e,["enablePromptInjectionDetection"]);if(n!=null)u(t,["enablePromptInjectionDetection"],n);let o=l(e,["environment"]);if(o!=null)u(t,["environment"],o);let s=l(e,["excludedPredefinedFunctions"]);if(s!=null)u(t,["excludedPredefinedFunctions"],s);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function c0(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>P0(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function d0(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>N0(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function f0(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function p0(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let o=l(e,["id"]);if(o!=null)u(t,["id"],o);let s=l(e,["name"]);if(s!=null)u(t,["name"],s);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function h0(e){let t={},n=l(e,["modelSelectionConfig"]);if(n!=null)u(t,["modelConfig"],n);let o=l(e,["responseJsonSchema"]);if(o!=null)u(t,["responseJsonSchema"],Yn(o));let s=l(e,["audioTranscriptionConfig"]);if(s!=null)u(t,["audioTranscriptionConfig"],s);let a=l(e,["audioTimestamp"]);if(a!=null)u(t,["audioTimestamp"],a);let c=l(e,["candidateCount"]);if(c!=null)u(t,["candidateCount"],c);let d=l(e,["enableAffectiveDialog"]);if(d!=null)u(t,["enableAffectiveDialog"],d);let f=l(e,["frequencyPenalty"]);if(f!=null)u(t,["frequencyPenalty"],f);let h=l(e,["logprobs"]);if(h!=null)u(t,["logprobs"],h);let m=l(e,["maxOutputTokens"]);if(m!=null)u(t,["maxOutputTokens"],m);let g=l(e,["mediaResolution"]);if(g!=null)u(t,["mediaResolution"],g);let _=l(e,["presencePenalty"]);if(_!=null)u(t,["presencePenalty"],_);let v=l(e,["responseFormat"]);if(v!=null){let Y=v;if(Array.isArray(Y))Y=Y.map((Z)=>Z);u(t,["responseFormat"],Y)}let E=l(e,["responseLogprobs"]);if(E!=null)u(t,["responseLogprobs"],E);let T=l(e,["responseMimeType"]);if(T!=null)u(t,["responseMimeType"],T);let S=l(e,["responseModalities"]);if(S!=null)u(t,["responseModalities"],S);let A=l(e,["responseSchema"]);if(A!=null)u(t,["responseSchema"],A);let w=l(e,["routingConfig"]);if(w!=null)u(t,["routingConfig"],w);let P=l(e,["seed"]);if(P!=null)u(t,["seed"],P);let N=l(e,["speechConfig"]);if(N!=null)u(t,["speechConfig"],Mm(N));let D=l(e,["stopSequences"]);if(D!=null)u(t,["stopSequences"],D);let O=l(e,["temperature"]);if(O!=null)u(t,["temperature"],O);let B=l(e,["thinkingConfig"]);if(B!=null)u(t,["thinkingConfig"],B);let X=l(e,["topK"]);if(X!=null)u(t,["topK"],X);let q=l(e,["topP"]);if(q!=null)u(t,["topP"],q);if(l(e,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["translationConfig"])!==void 0)throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function m0(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],l0(n));let o=l(e,["enableWidget"]);if(o!=null)u(t,["enableWidget"],o);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function g0(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let o=l(e,["timeRangeFilter"]);if(o!=null)u(t,["timeRangeFilter"],o);return t}function _0(e,t){let n={},o=l(e,["generationConfig"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig"],o);let s=l(e,["responseModalities"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","responseModalities"],s);let a=l(e,["temperature"]);if(t!==void 0&&a!=null)u(t,["setup","generationConfig","temperature"],a);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Xs(g));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let v=l(e,["enableAffectiveDialog"]);if(t!==void 0&&v!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],v);let E=l(e,["systemInstruction"]);if(t!==void 0&&E!=null)u(t,["setup","systemInstruction"],c0(Le(E)));let T=l(e,["tools"]);if(t!==void 0&&T!=null){let q=zn(T);if(Array.isArray(q))q=q.map((Y)=>U0(Wn(Y)));u(t,["setup","tools"],q)}let S=l(e,["sessionResumption"]);if(t!==void 0&&S!=null)u(t,["setup","sessionResumption"],D0(S));let A=l(e,["inputAudioTranscription"]);if(t!==void 0&&A!=null)u(t,["setup","inputAudioTranscription"],A);let w=l(e,["outputAudioTranscription"]);if(t!==void 0&&w!=null)u(t,["setup","outputAudioTranscription"],w);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);if(l(e,["explicitVadSignal"])!==void 0)throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let O=l(e,["avatarConfig"]);if(t!==void 0&&O!=null)u(t,["setup","avatarConfig"],O);let B=l(e,["safetySettings"]);if(t!==void 0&&B!=null){let q=B;if(Array.isArray(q))q=q.map((Y)=>k0(Y));u(t,["setup","safetySettings"],q)}let X=l(e,["translationConfig"]);if(t!==void 0&&X!=null)u(t,["setup","generationConfig","translationConfig"],X);return n}function y0(e,t){let n={},o=l(e,["generationConfig"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig"],h0(o));let s=l(e,["responseModalities"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","responseModalities"],s);let a=l(e,["temperature"]);if(t!==void 0&&a!=null)u(t,["setup","generationConfig","temperature"],a);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Mm(Xs(g)));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let v=l(e,["enableAffectiveDialog"]);if(t!==void 0&&v!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],v);let E=l(e,["systemInstruction"]);if(t!==void 0&&E!=null)u(t,["setup","systemInstruction"],d0(Le(E)));let T=l(e,["tools"]);if(t!==void 0&&T!=null){let Y=zn(T);if(Array.isArray(Y))Y=Y.map((Z)=>G0(Wn(Z)));u(t,["setup","tools"],Y)}let S=l(e,["sessionResumption"]);if(t!==void 0&&S!=null)u(t,["setup","sessionResumption"],S);let A=l(e,["inputAudioTranscription"]);if(t!==void 0&&A!=null)u(t,["setup","inputAudioTranscription"],A);let w=l(e,["outputAudioTranscription"]);if(t!==void 0&&w!=null)u(t,["setup","outputAudioTranscription"],w);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);let O=l(e,["explicitVadSignal"]);if(t!==void 0&&O!=null)u(t,["setup","explicitVadSignal"],O);let B=l(e,["avatarConfig"]);if(t!==void 0&&B!=null)u(t,["setup","avatarConfig"],B);let X=l(e,["safetySettings"]);if(t!==void 0&&X!=null){let Y=X;if(Array.isArray(Y))Y=Y.map((Z)=>Z);u(t,["setup","safetySettings"],Y)}let q=l(e,["translationConfig"]);if(t!==void 0&&q!=null)u(t,["setup","generationConfig","translationConfig"],q);return n}function E0(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["setup","model"],pe(e,o));let s=l(t,["config"]);if(s!=null)u(n,["config"],_0(s,n));return n}function v0(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["setup","model"],pe(e,o));let s=l(t,["config"]);if(s!=null)u(n,["config"],y0(s,n));return n}function T0(e){let t={},n=l(e,["musicGenerationConfig"]);if(n!=null)u(t,["musicGenerationConfig"],n);return t}function A0(e){let t={},n=l(e,["weightedPrompts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>s);u(t,["weightedPrompts"],o)}return t}function C0(e){let t={},n=l(e,["media"]);if(n!=null){let h=mm(n);if(Array.isArray(h))h=h.map((m)=>Mi(m));u(t,["mediaChunks"],h)}let o=l(e,["audio"]);if(o!=null)u(t,["audio"],Mi(_m(o)));let s=l(e,["audioStreamEnd"]);if(s!=null)u(t,["audioStreamEnd"],s);let a=l(e,["video"]);if(a!=null)u(t,["video"],Mi(gm(a)));let c=l(e,["text"]);if(c!=null)u(t,["text"],c);let d=l(e,["activityStart"]);if(d!=null)u(t,["activityStart"],d);let f=l(e,["activityEnd"]);if(f!=null)u(t,["activityEnd"],f);return t}function S0(e){let t={},n=l(e,["media"]);if(n!=null){let h=mm(n);if(Array.isArray(h))h=h.map((m)=>m);u(t,["mediaChunks"],h)}let o=l(e,["audio"]);if(o!=null)u(t,["audio"],_m(o));let s=l(e,["audioStreamEnd"]);if(s!=null)u(t,["audioStreamEnd"],s);let a=l(e,["video"]);if(a!=null)u(t,["video"],gm(a));let c=l(e,["text"]);if(c!=null)u(t,["text"],c);let d=l(e,["activityStart"]);if(d!=null)u(t,["activityStart"],d);let f=l(e,["activityEnd"]);if(f!=null)u(t,["activityEnd"],f);return t}function I0(e){let t={},n=l(e,["setupComplete"]);if(n!=null)u(t,["setupComplete"],n);let o=l(e,["serverContent"]);if(o!=null)u(t,["serverContent"],o);let s=l(e,["toolCall"]);if(s!=null)u(t,["toolCall"],s);let a=l(e,["toolCallCancellation"]);if(a!=null)u(t,["toolCallCancellation"],a);let c=l(e,["usageMetadata"]);if(c!=null)u(t,["usageMetadata"],b0(c));let d=l(e,["goAway"]);if(d!=null)u(t,["goAway"],d);let f=l(e,["sessionResumptionUpdate"]);if(f!=null)u(t,["sessionResumptionUpdate"],f);let h=l(e,["voiceActivityDetectionSignal"]);if(h!=null)u(t,["voiceActivityDetectionSignal"],h);let m=l(e,["voiceActivity"]);if(m!=null)u(t,["voiceActivity"],L0(m));return t}function w0(e){let t={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function R0(e){let t={},n=l(e,["speakerVoiceConfigs"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>M0(s));u(t,["speakerVoiceConfigs"],o)}return t}function P0(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let o=l(e,["toolCall"]);if(o!=null)u(t,["toolCall"],o);let s=l(e,["toolResponse"]);if(s!=null)u(t,["toolResponse"],s);let a=l(e,["audioTranscription"]);if(a!=null)u(t,["audioTranscription"],a);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],f0(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],p0(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],Mi(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let v=l(e,["thought"]);if(v!=null)u(t,["thought"],v);let E=l(e,["thoughtSignature"]);if(E!=null)u(t,["thoughtSignature"],E);let T=l(e,["videoMetadata"]);if(T!=null)u(t,["videoMetadata"],T);let S=l(e,["partMetadata"]);if(S!=null)u(t,["partMetadata"],S);let A=l(e,["mediaProcessing"]);if(A!=null)u(t,["mediaProcessing"],A);return t}function N0(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=l(e,["audioTranscription"]);if(o!=null)u(t,["audioTranscription"],o);let s=l(e,["codeExecutionResult"]);if(s!=null)u(t,["codeExecutionResult"],s);let a=l(e,["executableCode"]);if(a!=null)u(t,["executableCode"],a);let c=l(e,["fileData"]);if(c!=null)u(t,["fileData"],c);let d=l(e,["functionCall"]);if(d!=null)u(t,["functionCall"],d);let f=l(e,["functionResponse"]);if(f!=null)u(t,["functionResponse"],f);let h=l(e,["inlineData"]);if(h!=null)u(t,["inlineData"],h);let m=l(e,["text"]);if(m!=null)u(t,["text"],m);let g=l(e,["thought"]);if(g!=null)u(t,["thought"],g);let _=l(e,["thoughtSignature"]);if(_!=null)u(t,["thoughtSignature"],_);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let E=l(e,["mediaProcessing"]);if(E!=null)u(t,["mediaProcessing"],E);return t}function x0(e){let t={},n=l(e,["mimeType"]);if(n!=null)u(t,["mimeType"],n);let o=l(e,["voiceSampleAudio"]);if(o!=null)u(t,["voiceSampleAudio"],o);if(l(e,["consentAudio"])!==void 0)throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["voiceConsentSignature"])!==void 0)throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function k0(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["threshold"]);if(o!=null)u(t,["threshold"],o);return t}function D0(e){let t={},n=l(e,["handle"]);if(n!=null)u(t,["handle"],n);if(l(e,["transparent"])!==void 0)throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function M0(e){let t={},n=l(e,["speaker"]);if(n!=null)u(t,["speaker"],n);let o=l(e,["voiceConfig"]);if(o!=null)u(t,["voiceConfig"],Um(o));return t}function Mm(e){let t={},n=l(e,["voiceConfig"]);if(n!=null)u(t,["voiceConfig"],Um(n));let o=l(e,["languageCode"]);if(o!=null)u(t,["languageCode"],o);let s=l(e,["multiSpeakerVoiceConfig"]);if(s!=null)u(t,["multiSpeakerVoiceConfig"],R0(s));return t}function U0(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],m0(n));let o=l(e,["mcpServers"]);if(o!=null){let g=o;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let a=l(e,["computerUse"]);if(a!=null)u(t,["computerUse"],a);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],g0(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function G0(e){let t={},n=l(e,["retrieval"]);if(n!=null)u(t,["retrieval"],n);let o=l(e,["googleMaps"]);if(o!=null)u(t,["googleMaps"],o);let s=l(e,["mcpServers"]);if(s!=null){let E=s;if(Array.isArray(E))E=E.map((T)=>w0(T));u(t,["mcpServers"],E)}let a=l(e,["codeExecution"]);if(a!=null)u(t,["codeExecution"],a);let c=l(e,["computerUse"]);if(c!=null)u(t,["computerUse"],u0(c));let d=l(e,["enterpriseWebSearch"]);if(d!=null)u(t,["enterpriseWebSearch"],d);let f=l(e,["exaAiSearch"]);if(f!=null)u(t,["exaAiSearch"],f);let h=l(e,["functionDeclarations"]);if(h!=null){let E=h;if(Array.isArray(E))E=E.map((T)=>T);u(t,["functionDeclarations"],E)}let m=l(e,["googleSearch"]);if(m!=null)u(t,["googleSearch"],m);let g=l(e,["googleSearchRetrieval"]);if(g!=null)u(t,["googleSearchRetrieval"],g);let _=l(e,["parallelAiSearch"]);if(_!=null)u(t,["parallelAiSearch"],_);let v=l(e,["urlContext"]);if(v!=null)u(t,["urlContext"],v);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function b0(e){let t={},n=l(e,["candidatesTokenCount"]);if(n!=null)u(t,["responseTokenCount"],n);let o=l(e,["candidatesTokensDetails"]);if(o!=null){let v=o;if(Array.isArray(v))v=v.map((E)=>E);u(t,["responseTokensDetails"],v)}let s=l(e,["cacheTokensDetails"]);if(s!=null){let v=s;if(Array.isArray(v))v=v.map((E)=>E);u(t,["cacheTokensDetails"],v)}let a=l(e,["cachedContentTokenCount"]);if(a!=null)u(t,["cachedContentTokenCount"],a);let c=l(e,["promptTokenCount"]);if(c!=null)u(t,["promptTokenCount"],c);let d=l(e,["promptTokensDetails"]);if(d!=null){let v=d;if(Array.isArray(v))v=v.map((E)=>E);u(t,["promptTokensDetails"],v)}let f=l(e,["thoughtsTokenCount"]);if(f!=null)u(t,["thoughtsTokenCount"],f);let h=l(e,["toolUsePromptTokenCount"]);if(h!=null)u(t,["toolUsePromptTokenCount"],h);let m=l(e,["toolUsePromptTokensDetails"]);if(m!=null){let v=m;if(Array.isArray(v))v=v.map((E)=>E);u(t,["toolUsePromptTokensDetails"],v)}let g=l(e,["totalTokenCount"]);if(g!=null)u(t,["totalTokenCount"],g);let _=l(e,["trafficType"]);if(_!=null)u(t,["trafficType"],_);return t}function L0(e){let t={},n=l(e,["type"]);if(n!=null)u(t,["voiceActivityType"],n);let o=l(e,["audioOffset"]);if(o!=null)u(t,["audioOffset"],o);return t}function Um(e){let t={},n=l(e,["replicatedVoiceConfig"]);if(n!=null)u(t,["replicatedVoiceConfig"],x0(n));let o=l(e,["prebuiltVoiceConfig"]);if(o!=null)u(t,["prebuiltVoiceConfig"],o);return t}function q0(e,t){let n={},o=l(e,["apiKey"]);if(o!=null)u(n,["apiKey"],o);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function O0(e,t){let n={},o=l(e,["data"]);if(o!=null)u(n,["data"],o);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function F0(e,t){let n={},o=l(e,["content"]);if(o!=null)u(n,["content"],o);let s=l(e,["citationMetadata"]);if(s!=null)u(n,["citationMetadata"],H0(s));let a=l(e,["tokenCount"]);if(a!=null)u(n,["tokenCount"],a);let c=l(e,["finishReason"]);if(c!=null)u(n,["finishReason"],c);let d=l(e,["groundingMetadata"]);if(d!=null)u(n,["groundingMetadata"],d);let f=l(e,["avgLogprobs"]);if(f!=null)u(n,["avgLogprobs"],f);let h=l(e,["index"]);if(h!=null)u(n,["index"],h);let m=l(e,["logprobsResult"]);if(m!=null)u(n,["logprobsResult"],m);let g=l(e,["safetyRatings"]);if(g!=null){let v=g;if(Array.isArray(v))v=v.map((E)=>E);u(n,["safetyRatings"],v)}let _=l(e,["urlContextMetadata"]);if(_!=null)u(n,["urlContextMetadata"],_);return n}function H0(e,t){let n={},o=l(e,["citationSources"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>a);u(n,["citations"],s)}return n}function V0(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let c=We(a);if(Array.isArray(c))c=c.map((d)=>Zn(d));u(o,["contents"],c)}return o}function B0(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["tokensInfo"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(n,["tokensInfo"],a)}return n}function $0(e,t){let n={},o=l(e,["enablePromptInjectionDetection"]);if(o!=null)u(n,["enablePromptInjectionDetection"],o);let s=l(e,["environment"]);if(s!=null)u(n,["environment"],s);let a=l(e,["excludedPredefinedFunctions"]);if(a!=null)u(n,["excludedPredefinedFunctions"],a);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function J0(e,t){let n={},o=l(e,["values"]);if(o!=null)u(n,["values"],o);let s=l(e,["statistics"]);if(s!=null)u(n,["statistics"],X0(s));return n}function X0(e,t){let n={},o=l(e,["truncated"]);if(o!=null)u(n,["truncated"],o);let s=l(e,["token_count"]);if(s!=null)u(n,["tokenCount"],s);let a=l(e,["tokensDetails"]);if(a!=null){let c=a;if(Array.isArray(c))c=c.map((d)=>d);u(n,["tokensDetails"],c)}return n}function Cr(e,t){let n={},o=l(e,["parts"]);if(o!=null){let a=o;if(Array.isArray(a))a=a.map((c)=>QS(c));u(n,["parts"],a)}let s=l(e,["role"]);if(s!=null)u(n,["role"],s);return n}function Zn(e,t){let n={},o=l(e,["parts"]);if(o!=null){let a=o;if(Array.isArray(a))a=a.map((c)=>ZS(c));u(n,["parts"],a)}let s=l(e,["role"]);if(s!=null)u(n,["role"],s);return n}function K0(e,t){let n={},o=l(e,["controlType"]);if(o!=null)u(n,["controlType"],o);let s=l(e,["enableControlImageComputation"]);if(s!=null)u(n,["computeControl"],s);return n}function Y0(e,t){let n={};if(l(e,["systemInstruction"])!==void 0)throw Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tools"])!==void 0)throw Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["generationConfig"])!==void 0)throw Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function W0(e,t,n){let o={},s=l(e,["systemInstruction"]);if(t!==void 0&&s!=null)u(t,["systemInstruction"],Zn(Le(s)));let a=l(e,["tools"]);if(t!==void 0&&a!=null){let d=a;if(Array.isArray(d))d=d.map((f)=>qm(f));u(t,["tools"],d)}let c=l(e,["generationConfig"]);if(t!==void 0&&c!=null)u(t,["generationConfig"],GS(c));return o}function z0(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let d=We(a);if(Array.isArray(d))d=d.map((f)=>Cr(f));u(o,["contents"],d)}let c=l(t,["config"]);if(c!=null)Y0(c);return o}function Q0(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let d=We(a);if(Array.isArray(d))d=d.map((f)=>Zn(f));u(o,["contents"],d)}let c=l(t,["config"]);if(c!=null)W0(c,o);return o}function Z0(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["totalTokens"]);if(s!=null)u(n,["totalTokens"],s);let a=l(e,["cachedContentTokenCount"]);if(a!=null)u(n,["cachedContentTokenCount"],a);return n}function j0(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["totalTokens"]);if(s!=null)u(n,["totalTokens"],s);return n}function eS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","name"],pe(e,s));return o}function tS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","name"],pe(e,s));return o}function nS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);return n}function rS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);return n}function iS(e,t,n){let o={},s=l(e,["outputGcsUri"]);if(t!==void 0&&s!=null)u(t,["parameters","storageUri"],s);let a=l(e,["negativePrompt"]);if(t!==void 0&&a!=null)u(t,["parameters","negativePrompt"],a);let c=l(e,["numberOfImages"]);if(t!==void 0&&c!=null)u(t,["parameters","sampleCount"],c);let d=l(e,["aspectRatio"]);if(t!==void 0&&d!=null)u(t,["parameters","aspectRatio"],d);let f=l(e,["guidanceScale"]);if(t!==void 0&&f!=null)u(t,["parameters","guidanceScale"],f);let h=l(e,["seed"]);if(t!==void 0&&h!=null)u(t,["parameters","seed"],h);let m=l(e,["safetyFilterLevel"]);if(t!==void 0&&m!=null)u(t,["parameters","safetySetting"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["includeSafetyAttributes"]);if(t!==void 0&&_!=null)u(t,["parameters","includeSafetyAttributes"],_);let v=l(e,["includeRaiReason"]);if(t!==void 0&&v!=null)u(t,["parameters","includeRaiReason"],v);let E=l(e,["language"]);if(t!==void 0&&E!=null)u(t,["parameters","language"],E);let T=l(e,["outputMimeType"]);if(t!==void 0&&T!=null)u(t,["parameters","outputOptions","mimeType"],T);let S=l(e,["outputCompressionQuality"]);if(t!==void 0&&S!=null)u(t,["parameters","outputOptions","compressionQuality"],S);let A=l(e,["addWatermark"]);if(t!==void 0&&A!=null)u(t,["parameters","addWatermark"],A);let w=l(e,["labels"]);if(t!==void 0&&w!=null)u(t,["labels"],w);let P=l(e,["editMode"]);if(t!==void 0&&P!=null)u(t,["parameters","editMode"],P);let N=l(e,["baseSteps"]);if(t!==void 0&&N!=null)u(t,["parameters","editConfig","baseSteps"],N);return o}function oS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["prompt"]);if(a!=null)u(o,["instances[0]","prompt"],a);let c=l(t,["referenceImages"]);if(c!=null){let f=c;if(Array.isArray(f))f=f.map((h)=>iI(h));u(o,["instances[0]","referenceImages"],f)}let d=l(t,["config"]);if(d!=null)iS(d,o);return o}function sS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["predictions"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>Bi(c));u(n,["generatedImages"],a)}return n}function aS(e,t,n){let o={},s=l(e,["taskType"]);if(t!==void 0&&s!=null)u(t,["requests[]","taskType"],s);let a=l(e,["title"]);if(t!==void 0&&a!=null)u(t,["requests[]","title"],a);let c=l(e,["outputDimensionality"]);if(t!==void 0&&c!=null)u(t,["requests[]","outputDimensionality"],c);if(l(e,["mimeType"])!==void 0)throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["autoTruncate"])!==void 0)throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["documentOcr"])!==void 0)throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["audioTrackExtraction"])!==void 0)throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function lS(e,t,n){let o={},s=l(n,["embeddingApiType"]);if(s===void 0)s="PREDICT";if(s==="PREDICT"){let g=l(e,["taskType"]);if(t!==void 0&&g!=null)u(t,["instances[]","task_type"],g)}else if(s==="EMBED_CONTENT"){let g=l(e,["taskType"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","taskType"],g)}let a=l(n,["embeddingApiType"]);if(a===void 0)a="PREDICT";if(a==="PREDICT"){let g=l(e,["title"]);if(t!==void 0&&g!=null)u(t,["instances[]","title"],g)}else if(a==="EMBED_CONTENT"){let g=l(e,["title"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","title"],g)}let c=l(n,["embeddingApiType"]);if(c===void 0)c="PREDICT";if(c==="PREDICT"){let g=l(e,["outputDimensionality"]);if(t!==void 0&&g!=null)u(t,["parameters","outputDimensionality"],g)}else if(c==="EMBED_CONTENT"){let g=l(e,["outputDimensionality"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","outputDimensionality"],g)}let d=l(n,["embeddingApiType"]);if(d===void 0)d="PREDICT";if(d==="PREDICT"){let g=l(e,["mimeType"]);if(t!==void 0&&g!=null)u(t,["instances[]","mimeType"],g)}let f=l(n,["embeddingApiType"]);if(f===void 0)f="PREDICT";if(f==="PREDICT"){let g=l(e,["autoTruncate"]);if(t!==void 0&&g!=null)u(t,["parameters","autoTruncate"],g)}else if(f==="EMBED_CONTENT"){let g=l(e,["autoTruncate"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","autoTruncate"],g)}let h=l(n,["embeddingApiType"]);if(h===void 0)h="PREDICT";if(h==="EMBED_CONTENT"){let g=l(e,["documentOcr"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","documentOcr"],g)}let m=l(n,["embeddingApiType"]);if(m===void 0)m="PREDICT";if(m==="EMBED_CONTENT"){let g=l(e,["audioTrackExtraction"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","audioTrackExtraction"],g)}return o}function uS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let h=Bs(e,a);if(Array.isArray(h))h=h.map((m)=>m);u(o,["requests[]","content"],h)}let c=l(t,["content"]);if(c!=null)Cr(Le(c));let d=l(t,["config"]);if(d!=null)aS(d,o);let f=l(t,["model"]);if(f!==void 0)u(o,["requests[]","model"],pe(e,f));return o}function cS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(n,["embeddingApiType"]);if(a===void 0)a="PREDICT";if(a==="PREDICT"){let f=l(t,["contents"]);if(f!=null){let h=Bs(e,f);if(Array.isArray(h))h=h.map((m)=>m);u(o,["instances[]","content"],h)}}let c=l(n,["embeddingApiType"]);if(c===void 0)c="PREDICT";if(c==="EMBED_CONTENT"){let f=l(t,["content"]);if(f!=null)u(o,["content"],Zn(Le(f)))}let d=l(t,["config"]);if(d!=null)lS(d,o,n);return o}function dS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["embeddings"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>d);u(n,["embeddings"],c)}let a=l(e,["metadata"]);if(a!=null)u(n,["metadata"],a);return n}function fS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["predictions[]","embeddings"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>J0(d));u(n,["embeddings"],c)}let a=l(e,["metadata"]);if(a!=null)u(n,["metadata"],a);if(t&&l(t,["embeddingApiType"])==="EMBED_CONTENT"){let c=l(e,["embedding"]),d=l(e,["usageMetadata"]),f=l(e,["truncated"]);if(c){let h={};if(d&&d.promptTokenCount)h.tokenCount=d.promptTokenCount;if(d&&d.promptTokensDetails)h.tokensDetails=d.promptTokensDetails;if(f)h.truncated=f;c.statistics=h,u(n,["embeddings"],[c])}}return n}function pS(e,t){let n={},o=l(e,["endpoint"]);if(o!=null)u(n,["name"],o);let s=l(e,["deployedModelId"]);if(s!=null)u(n,["deployedModelId"],s);return n}function hS(e,t){let n={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["fileUri"]);if(o!=null)u(n,["fileUri"],o);let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function mS(e,t){let n={},o=l(e,["args"]);if(o!=null)u(n,["args"],o);let s=l(e,["id"]);if(s!=null)u(n,["id"],s);let a=l(e,["name"]);if(a!=null)u(n,["name"],a);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function gS(e,t){let n={},o=l(e,["allowedFunctionNames"]);if(o!=null)u(n,["allowedFunctionNames"],o);let s=l(e,["mode"]);if(s!=null)u(n,["mode"],s);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function _S(e,t,n,o){let s={},a=l(t,["serviceTier"]);if(n!==void 0&&a!=null)u(n,["serviceTier"],a);let c=l(t,["systemInstruction"]);if(n!==void 0&&c!=null)u(n,["systemInstruction"],Cr(Le(c)));let d=l(t,["temperature"]);if(d!=null)u(s,["temperature"],d);let f=l(t,["topP"]);if(f!=null)u(s,["topP"],f);let h=l(t,["topK"]);if(h!=null)u(s,["topK"],h);let m=l(t,["candidateCount"]);if(m!=null)u(s,["candidateCount"],m);let g=l(t,["maxOutputTokens"]);if(g!=null)u(s,["maxOutputTokens"],g);let _=l(t,["stopSequences"]);if(_!=null)u(s,["stopSequences"],_);let v=l(t,["responseLogprobs"]);if(v!=null)u(s,["responseLogprobs"],v);let E=l(t,["logprobs"]);if(E!=null)u(s,["logprobs"],E);let T=l(t,["presencePenalty"]);if(T!=null)u(s,["presencePenalty"],T);let S=l(t,["frequencyPenalty"]);if(S!=null)u(s,["frequencyPenalty"],S);let A=l(t,["seed"]);if(A!=null)u(s,["seed"],A);let w=l(t,["responseMimeType"]);if(w!=null)u(s,["responseMimeType"],w);let P=l(t,["responseSchema"]);if(P!=null)u(s,["responseSchema"],$s(P));let N=l(t,["responseJsonSchema"]);if(N!=null)u(s,["responseJsonSchema"],Yn(N));if(l(t,["routingConfig"])!==void 0)throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["modelSelectionConfig"])!==void 0)throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let D=l(t,["safetySettings"]);if(n!==void 0&&D!=null){let se=D;if(Array.isArray(se))se=se.map((xe)=>sI(xe));u(n,["safetySettings"],se)}let O=l(t,["tools"]);if(n!==void 0&&O!=null){let se=zn(O);if(Array.isArray(se))se=se.map((xe)=>mI(Wn(xe)));u(n,["tools"],se)}let B=l(t,["toolConfig"]);if(n!==void 0&&B!=null)u(n,["toolConfig"],pI(B));if(l(t,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let X=l(t,["cachedContent"]);if(n!==void 0&&X!=null)u(n,["cachedContent"],Ot(e,X));let q=l(t,["responseModalities"]);if(q!=null)u(s,["responseModalities"],q);let Y=l(t,["mediaResolution"]);if(Y!=null)u(s,["mediaResolution"],Y);let Z=l(t,["speechConfig"]);if(Z!=null)u(s,["speechConfig"],Js(Z));if(l(t,["audioTimestamp"])!==void 0)throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ne=l(t,["thinkingConfig"]);if(ne!=null)u(s,["thinkingConfig"],ne);let W=l(t,["audioTranscriptionConfig"]);if(W!=null)u(s,["audioTranscriptionConfig"],W);let V=l(t,["imageConfig"]);if(V!=null)u(s,["imageConfig"],FS(V));let oe=l(t,["enableEnhancedCivicAnswers"]);if(oe!=null)u(s,["enableEnhancedCivicAnswers"],oe);if(l(t,["modelArmorConfig"])!==void 0)throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return s}function yS(e,t,n,o){let s={},a=l(t,["serviceTier"]);if(n!==void 0&&a!=null)u(n,["serviceTier"],a);let c=l(t,["systemInstruction"]);if(n!==void 0&&c!=null)u(n,["systemInstruction"],Zn(Le(c)));let d=l(t,["temperature"]);if(d!=null)u(s,["temperature"],d);let f=l(t,["topP"]);if(f!=null)u(s,["topP"],f);let h=l(t,["topK"]);if(h!=null)u(s,["topK"],h);let m=l(t,["candidateCount"]);if(m!=null)u(s,["candidateCount"],m);let g=l(t,["maxOutputTokens"]);if(g!=null)u(s,["maxOutputTokens"],g);let _=l(t,["stopSequences"]);if(_!=null)u(s,["stopSequences"],_);let v=l(t,["responseLogprobs"]);if(v!=null)u(s,["responseLogprobs"],v);let E=l(t,["logprobs"]);if(E!=null)u(s,["logprobs"],E);let T=l(t,["presencePenalty"]);if(T!=null)u(s,["presencePenalty"],T);let S=l(t,["frequencyPenalty"]);if(S!=null)u(s,["frequencyPenalty"],S);let A=l(t,["seed"]);if(A!=null)u(s,["seed"],A);let w=l(t,["responseMimeType"]);if(w!=null)u(s,["responseMimeType"],w);let P=l(t,["responseSchema"]);if(P!=null)u(s,["responseSchema"],$s(P));let N=l(t,["responseJsonSchema"]);if(N!=null)u(s,["responseJsonSchema"],Yn(N));let D=l(t,["routingConfig"]);if(D!=null)u(s,["routingConfig"],D);let O=l(t,["modelSelectionConfig"]);if(O!=null)u(s,["modelConfig"],O);let B=l(t,["safetySettings"]);if(n!==void 0&&B!=null){let be=B;if(Array.isArray(be))be=be.map((ze)=>ze);u(n,["safetySettings"],be)}let X=l(t,["tools"]);if(n!==void 0&&X!=null){let be=zn(X);if(Array.isArray(be))be=be.map((ze)=>qm(Wn(ze)));u(n,["tools"],be)}let q=l(t,["toolConfig"]);if(n!==void 0&&q!=null)u(n,["toolConfig"],hI(q));let Y=l(t,["labels"]);if(n!==void 0&&Y!=null)u(n,["labels"],Y);let Z=l(t,["cachedContent"]);if(n!==void 0&&Z!=null)u(n,["cachedContent"],Ot(e,Z));let ne=l(t,["responseModalities"]);if(ne!=null)u(s,["responseModalities"],ne);let W=l(t,["mediaResolution"]);if(W!=null)u(s,["mediaResolution"],W);let V=l(t,["speechConfig"]);if(V!=null)u(s,["speechConfig"],Lm(Js(V)));let oe=l(t,["audioTimestamp"]);if(oe!=null)u(s,["audioTimestamp"],oe);let se=l(t,["thinkingConfig"]);if(se!=null)u(s,["thinkingConfig"],se);let xe=l(t,["audioTranscriptionConfig"]);if(xe!=null)u(s,["audioTranscriptionConfig"],xe);let Ue=l(t,["imageConfig"]);if(Ue!=null)u(s,["imageConfig"],HS(Ue));if(l(t,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let Xe=l(t,["modelArmorConfig"]);if(n!==void 0&&Xe!=null)u(n,["modelArmorConfig"],Xe);return s}function Ah(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let d=We(a);if(Array.isArray(d))d=d.map((f)=>Cr(f));u(o,["contents"],d)}let c=l(t,["config"]);if(c!=null)u(o,["generationConfig"],_S(e,c,o));return o}function Ch(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["contents"]);if(a!=null){let d=We(a);if(Array.isArray(d))d=d.map((f)=>Zn(f));u(o,["contents"],d)}let c=l(t,["config"]);if(c!=null)u(o,["generationConfig"],yS(e,c,o));return o}function Sh(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["candidates"]);if(s!=null){let m=s;if(Array.isArray(m))m=m.map((g)=>F0(g));u(n,["candidates"],m)}let a=l(e,["modelVersion"]);if(a!=null)u(n,["modelVersion"],a);let c=l(e,["promptFeedback"]);if(c!=null)u(n,["promptFeedback"],c);let d=l(e,["responseId"]);if(d!=null)u(n,["responseId"],d);let f=l(e,["usageMetadata"]);if(f!=null)u(n,["usageMetadata"],f);let h=l(e,["modelStatus"]);if(h!=null)u(n,["modelStatus"],h);return n}function Ih(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["candidates"]);if(s!=null){let m=s;if(Array.isArray(m))m=m.map((g)=>g);u(n,["candidates"],m)}let a=l(e,["createTime"]);if(a!=null)u(n,["createTime"],a);let c=l(e,["modelVersion"]);if(c!=null)u(n,["modelVersion"],c);let d=l(e,["promptFeedback"]);if(d!=null)u(n,["promptFeedback"],d);let f=l(e,["responseId"]);if(f!=null)u(n,["responseId"],f);let h=l(e,["usageMetadata"]);if(h!=null)u(n,["usageMetadata"],h);return n}function ES(e,t,n){let o={},s=l(e,["outputGcsUri"]);if(t!==void 0&&s!=null)u(t,["parameters","storageUri"],s);let a=l(e,["negativePrompt"]);if(t!==void 0&&a!=null)u(t,["parameters","negativePrompt"],a);let c=l(e,["numberOfImages"]);if(t!==void 0&&c!=null)u(t,["parameters","sampleCount"],c);let d=l(e,["aspectRatio"]);if(t!==void 0&&d!=null)u(t,["parameters","aspectRatio"],d);let f=l(e,["guidanceScale"]);if(t!==void 0&&f!=null)u(t,["parameters","guidanceScale"],f);let h=l(e,["seed"]);if(t!==void 0&&h!=null)u(t,["parameters","seed"],h);let m=l(e,["safetyFilterLevel"]);if(t!==void 0&&m!=null)u(t,["parameters","safetySetting"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["includeSafetyAttributes"]);if(t!==void 0&&_!=null)u(t,["parameters","includeSafetyAttributes"],_);let v=l(e,["includeRaiReason"]);if(t!==void 0&&v!=null)u(t,["parameters","includeRaiReason"],v);let E=l(e,["language"]);if(t!==void 0&&E!=null)u(t,["parameters","language"],E);let T=l(e,["outputMimeType"]);if(t!==void 0&&T!=null)u(t,["parameters","outputOptions","mimeType"],T);let S=l(e,["outputCompressionQuality"]);if(t!==void 0&&S!=null)u(t,["parameters","outputOptions","compressionQuality"],S);let A=l(e,["addWatermark"]);if(t!==void 0&&A!=null)u(t,["parameters","addWatermark"],A);let w=l(e,["labels"]);if(t!==void 0&&w!=null)u(t,["labels"],w);let P=l(e,["imageSize"]);if(t!==void 0&&P!=null)u(t,["parameters","sampleImageSize"],P);let N=l(e,["enhancePrompt"]);if(t!==void 0&&N!=null)u(t,["parameters","enhancePrompt"],N);return o}function vS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["prompt"]);if(a!=null)u(o,["instances[0]","prompt"],a);let c=l(t,["config"]);if(c!=null)ES(c,o);return o}function TS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["predictions"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>Bi(d));u(n,["generatedImages"],c)}let a=l(e,["positivePromptSafetyAttributes"]);if(a!=null)u(n,["positivePromptSafetyAttributes"],bm(a));return n}function AS(e,t,n){let o={},s=l(e,["numberOfVideos"]);if(t!==void 0&&s!=null)u(t,["parameters","sampleCount"],s);if(l(e,["outputGcsUri"])!==void 0)throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["fps"])!==void 0)throw Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=l(e,["durationSeconds"]);if(t!==void 0&&a!=null)u(t,["parameters","durationSeconds"],a);if(l(e,["seed"])!==void 0)throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["aspectRatio"]);if(t!==void 0&&c!=null)u(t,["parameters","aspectRatio"],c);let d=l(e,["resolution"]);if(t!==void 0&&d!=null)u(t,["parameters","resolution"],d);let f=l(e,["personGeneration"]);if(t!==void 0&&f!=null)u(t,["parameters","personGeneration"],f);if(l(e,["pubsubTopic"])!==void 0)throw Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["negativePrompt"]);if(t!==void 0&&h!=null)u(t,["parameters","negativePrompt"],h);let m=l(e,["enhancePrompt"]);if(t!==void 0&&m!=null)u(t,["parameters","enhancePrompt"],m);if(l(e,["generateAudio"])!==void 0)throw Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=l(e,["lastFrame"]);if(t!==void 0&&g!=null)u(t,["instances[0]","lastFrame"],$i(g));let _=l(e,["referenceImages"]);if(t!==void 0&&_!=null){let E=_;if(Array.isArray(E))E=E.map((T)=>PI(T));u(t,["instances[0]","referenceImages"],E)}if(l(e,["mask"])!==void 0)throw Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["compressionQuality"])!==void 0)throw Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let v=l(e,["webhookConfig"]);if(t!==void 0&&v!=null)u(t,["webhookConfig"],v);if(l(e,["resizeMode"])!==void 0)throw Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function CS(e,t,n){let o={},s=l(e,["numberOfVideos"]);if(t!==void 0&&s!=null)u(t,["parameters","sampleCount"],s);let a=l(e,["outputGcsUri"]);if(t!==void 0&&a!=null)u(t,["parameters","storageUri"],a);let c=l(e,["fps"]);if(t!==void 0&&c!=null)u(t,["parameters","fps"],c);let d=l(e,["durationSeconds"]);if(t!==void 0&&d!=null)u(t,["parameters","durationSeconds"],d);let f=l(e,["seed"]);if(t!==void 0&&f!=null)u(t,["parameters","seed"],f);let h=l(e,["aspectRatio"]);if(t!==void 0&&h!=null)u(t,["parameters","aspectRatio"],h);let m=l(e,["resolution"]);if(t!==void 0&&m!=null)u(t,["parameters","resolution"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["pubsubTopic"]);if(t!==void 0&&_!=null)u(t,["parameters","pubsubTopic"],_);let v=l(e,["negativePrompt"]);if(t!==void 0&&v!=null)u(t,["parameters","negativePrompt"],v);let E=l(e,["enhancePrompt"]);if(t!==void 0&&E!=null)u(t,["parameters","enhancePrompt"],E);let T=l(e,["generateAudio"]);if(t!==void 0&&T!=null)u(t,["parameters","generateAudio"],T);let S=l(e,["lastFrame"]);if(t!==void 0&&S!=null)u(t,["instances[0]","lastFrame"],Et(S));let A=l(e,["referenceImages"]);if(t!==void 0&&A!=null){let O=A;if(Array.isArray(O))O=O.map((B)=>NI(B));u(t,["instances[0]","referenceImages"],O)}let w=l(e,["mask"]);if(t!==void 0&&w!=null)u(t,["instances[0]","mask"],RI(w));let P=l(e,["compressionQuality"]);if(t!==void 0&&P!=null)u(t,["parameters","compressionQuality"],P);let N=l(e,["labels"]);if(t!==void 0&&N!=null)u(t,["labels"],N);if(l(e,["webhookConfig"])!==void 0)throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let D=l(e,["resizeMode"]);if(t!==void 0&&D!=null)u(t,["parameters","resizeMode"],D);return o}function SS(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["metadata"]);if(s!=null)u(n,["metadata"],s);let a=l(e,["done"]);if(a!=null)u(n,["done"],a);let c=l(e,["error"]);if(c!=null)u(n,["error"],c);let d=l(e,["response","generateVideoResponse"]);if(d!=null)u(n,["response"],PS(d));return n}function IS(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["metadata"]);if(s!=null)u(n,["metadata"],s);let a=l(e,["done"]);if(a!=null)u(n,["done"],a);let c=l(e,["error"]);if(c!=null)u(n,["error"],c);let d=l(e,["response"]);if(d!=null)u(n,["response"],NS(d));return n}function wS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["prompt"]);if(a!=null)u(o,["instances[0]","prompt"],a);let c=l(t,["image"]);if(c!=null)u(o,["instances[0]","image"],$i(c));let d=l(t,["video"]);if(d!=null)u(o,["instances[0]","video"],Om(d));let f=l(t,["source"]);if(f!=null)xS(f,o);let h=l(t,["config"]);if(h!=null)AS(h,o);return o}function RS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["prompt"]);if(a!=null)u(o,["instances[0]","prompt"],a);let c=l(t,["image"]);if(c!=null)u(o,["instances[0]","image"],Et(c));let d=l(t,["video"]);if(d!=null)u(o,["instances[0]","video"],Fm(d));let f=l(t,["source"]);if(f!=null)kS(f,o);let h=l(t,["config"]);if(h!=null)CS(h,o);return o}function PS(e,t){let n={},o=l(e,["generatedSamples"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>MS(d));u(n,["generatedVideos"],c)}let s=l(e,["raiMediaFilteredCount"]);if(s!=null)u(n,["raiMediaFilteredCount"],s);let a=l(e,["raiMediaFilteredReasons"]);if(a!=null)u(n,["raiMediaFilteredReasons"],a);return n}function NS(e,t){let n={},o=l(e,["videos"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>US(d));u(n,["generatedVideos"],c)}let s=l(e,["raiMediaFilteredCount"]);if(s!=null)u(n,["raiMediaFilteredCount"],s);let a=l(e,["raiMediaFilteredReasons"]);if(a!=null)u(n,["raiMediaFilteredReasons"],a);return n}function xS(e,t,n){let o={},s=l(e,["prompt"]);if(t!==void 0&&s!=null)u(t,["instances[0]","prompt"],s);let a=l(e,["image"]);if(t!==void 0&&a!=null)u(t,["instances[0]","image"],$i(a));let c=l(e,["video"]);if(t!==void 0&&c!=null)u(t,["instances[0]","video"],Om(c));return o}function kS(e,t,n){let o={},s=l(e,["prompt"]);if(t!==void 0&&s!=null)u(t,["instances[0]","prompt"],s);let a=l(e,["image"]);if(t!==void 0&&a!=null)u(t,["instances[0]","image"],Et(a));let c=l(e,["video"]);if(t!==void 0&&c!=null)u(t,["instances[0]","video"],Fm(c));return o}function Bi(e,t){let n={},o=l(e,["_self"]);if(o!=null)u(n,["image"],Gm(o));let s=l(e,["raiFilteredReason"]);if(s!=null)u(n,["raiFilteredReason"],s);let a=l(e,["_self"]);if(a!=null)u(n,["safetyAttributes"],bm(a));let c=l(e,["prompt"]);if(c!=null)u(n,["enhancedPrompt"],c);return n}function DS(e,t){let n={},o=l(e,["_self"]);if(o!=null)u(n,["mask"],Gm(o));let s=l(e,["labels"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(n,["labels"],a)}return n}function MS(e,t){let n={},o=l(e,["video"]);if(o!=null)u(n,["video"],II(o));return n}function US(e,t){let n={},o=l(e,["_self"]);if(o!=null)u(n,["video"],wI(o));return n}function GS(e,t){let n={},o=l(e,["modelSelectionConfig"]);if(o!=null)u(n,["modelConfig"],o);let s=l(e,["responseJsonSchema"]);if(s!=null)u(n,["responseJsonSchema"],Yn(s));let a=l(e,["audioTranscriptionConfig"]);if(a!=null)u(n,["audioTranscriptionConfig"],a);let c=l(e,["audioTimestamp"]);if(c!=null)u(n,["audioTimestamp"],c);let d=l(e,["candidateCount"]);if(d!=null)u(n,["candidateCount"],d);let f=l(e,["enableAffectiveDialog"]);if(f!=null)u(n,["enableAffectiveDialog"],f);let h=l(e,["frequencyPenalty"]);if(h!=null)u(n,["frequencyPenalty"],h);let m=l(e,["logprobs"]);if(m!=null)u(n,["logprobs"],m);let g=l(e,["maxOutputTokens"]);if(g!=null)u(n,["maxOutputTokens"],g);let _=l(e,["mediaResolution"]);if(_!=null)u(n,["mediaResolution"],_);let v=l(e,["presencePenalty"]);if(v!=null)u(n,["presencePenalty"],v);let E=l(e,["responseFormat"]);if(E!=null){let Z=E;if(Array.isArray(Z))Z=Z.map((ne)=>ne);u(n,["responseFormat"],Z)}let T=l(e,["responseLogprobs"]);if(T!=null)u(n,["responseLogprobs"],T);let S=l(e,["responseMimeType"]);if(S!=null)u(n,["responseMimeType"],S);let A=l(e,["responseModalities"]);if(A!=null)u(n,["responseModalities"],A);let w=l(e,["responseSchema"]);if(w!=null)u(n,["responseSchema"],w);let P=l(e,["routingConfig"]);if(P!=null)u(n,["routingConfig"],P);let N=l(e,["seed"]);if(N!=null)u(n,["seed"],N);let D=l(e,["speechConfig"]);if(D!=null)u(n,["speechConfig"],Lm(D));let O=l(e,["stopSequences"]);if(O!=null)u(n,["stopSequences"],O);let B=l(e,["temperature"]);if(B!=null)u(n,["temperature"],B);let X=l(e,["thinkingConfig"]);if(X!=null)u(n,["thinkingConfig"],X);let q=l(e,["topK"]);if(q!=null)u(n,["topK"],q);let Y=l(e,["topP"]);if(Y!=null)u(n,["topP"],Y);if(l(e,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["translationConfig"])!==void 0)throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","name"],pe(e,s));return o}function LS(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","name"],pe(e,s));return o}function qS(e,t){let n={},o=l(e,["authConfig"]);if(o!=null)u(n,["authConfig"],q0(o));let s=l(e,["enableWidget"]);if(s!=null)u(n,["enableWidget"],s);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function OS(e,t){let n={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["searchTypes"]);if(o!=null)u(n,["searchTypes"],o);let s=l(e,["timeRangeFilter"]);if(s!=null)u(n,["timeRangeFilter"],s);return n}function FS(e,t){let n={},o=l(e,["aspectRatio"]);if(o!=null)u(n,["aspectRatio"],o);let s=l(e,["imageSize"]);if(s!=null)u(n,["imageSize"],s);if(l(e,["personGeneration"])!==void 0)throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputMimeType"])!==void 0)throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputCompressionQuality"])!==void 0)throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["imageOutputOptions"])!==void 0)throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["prominentPeople"])!==void 0)throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function HS(e,t){let n={},o=l(e,["aspectRatio"]);if(o!=null)u(n,["aspectRatio"],o);let s=l(e,["imageSize"]);if(s!=null)u(n,["imageSize"],s);let a=l(e,["personGeneration"]);if(a!=null)u(n,["personGeneration"],a);let c=l(e,["outputMimeType"]);if(c!=null)u(n,["imageOutputOptions","mimeType"],c);let d=l(e,["outputCompressionQuality"]);if(d!=null)u(n,["imageOutputOptions","compressionQuality"],d);let f=l(e,["imageOutputOptions"]);if(f!=null)u(n,["imageOutputOptions"],f);let h=l(e,["prominentPeople"]);if(h!=null)u(n,["prominentPeople"],h);return n}function Gm(e,t){let n={},o=l(e,["gcsUri"]);if(o!=null)u(n,["gcsUri"],o);let s=l(e,["bytesBase64Encoded"]);if(s!=null)u(n,["imageBytes"],En(s));let a=l(e,["mimeType"]);if(a!=null)u(n,["mimeType"],a);return n}function $i(e,t){let n={};if(l(e,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["imageBytes"]);if(o!=null)u(n,["bytesBase64Encoded"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function Et(e,t){let n={},o=l(e,["gcsUri"]);if(o!=null)u(n,["gcsUri"],o);let s=l(e,["imageBytes"]);if(s!=null)u(n,["bytesBase64Encoded"],En(s));let a=l(e,["mimeType"]);if(a!=null)u(n,["mimeType"],a);return n}function VS(e,t,n,o){let s={},a=l(t,["pageSize"]);if(n!==void 0&&a!=null)u(n,["_query","pageSize"],a);let c=l(t,["pageToken"]);if(n!==void 0&&c!=null)u(n,["_query","pageToken"],c);let d=l(t,["filter"]);if(n!==void 0&&d!=null)u(n,["_query","filter"],d);let f=l(t,["queryBase"]);if(n!==void 0&&f!=null)u(n,["_url","models_url"],Am(e,f));return s}function BS(e,t,n,o){let s={},a=l(t,["pageSize"]);if(n!==void 0&&a!=null)u(n,["_query","pageSize"],a);let c=l(t,["pageToken"]);if(n!==void 0&&c!=null)u(n,["_query","pageToken"],c);let d=l(t,["filter"]);if(n!==void 0&&d!=null)u(n,["_query","filter"],d);let f=l(t,["queryBase"]);if(n!==void 0&&f!=null)u(n,["_url","models_url"],Am(e,f));return s}function $S(e,t,n){let o={},s=l(t,["config"]);if(s!=null)VS(e,s,o);return o}function JS(e,t,n){let o={},s=l(t,["config"]);if(s!=null)BS(e,s,o);return o}function XS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["nextPageToken"]);if(s!=null)u(n,["nextPageToken"],s);let a=l(e,["_self"]);if(a!=null){let c=Cm(a);if(Array.isArray(c))c=c.map((d)=>Ds(d));u(n,["models"],c)}return n}function KS(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["nextPageToken"]);if(s!=null)u(n,["nextPageToken"],s);let a=l(e,["_self"]);if(a!=null){let c=Cm(a);if(Array.isArray(c))c=c.map((d)=>Ms(d));u(n,["models"],c)}return n}function YS(e,t){let n={},o=l(e,["maskMode"]);if(o!=null)u(n,["maskMode"],o);let s=l(e,["segmentationClasses"]);if(s!=null)u(n,["maskClasses"],s);let a=l(e,["maskDilation"]);if(a!=null)u(n,["dilation"],a);return n}function WS(e,t){let n={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Ds(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["displayName"]);if(s!=null)u(n,["displayName"],s);let a=l(e,["description"]);if(a!=null)u(n,["description"],a);let c=l(e,["version"]);if(c!=null)u(n,["version"],c);let d=l(e,["_self"]);if(d!=null)u(n,["tunedModelInfo"],gI(d));let f=l(e,["inputTokenLimit"]);if(f!=null)u(n,["inputTokenLimit"],f);let h=l(e,["outputTokenLimit"]);if(h!=null)u(n,["outputTokenLimit"],h);let m=l(e,["supportedGenerationMethods"]);if(m!=null)u(n,["supportedActions"],m);let g=l(e,["temperature"]);if(g!=null)u(n,["temperature"],g);let _=l(e,["maxTemperature"]);if(_!=null)u(n,["maxTemperature"],_);let v=l(e,["topP"]);if(v!=null)u(n,["topP"],v);let E=l(e,["topK"]);if(E!=null)u(n,["topK"],E);let T=l(e,["thinking"]);if(T!=null)u(n,["thinking"],T);return n}function Ms(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["displayName"]);if(s!=null)u(n,["displayName"],s);let a=l(e,["description"]);if(a!=null)u(n,["description"],a);let c=l(e,["versionId"]);if(c!=null)u(n,["version"],c);let d=l(e,["deployedModels"]);if(d!=null){let _=d;if(Array.isArray(_))_=_.map((v)=>pS(v));u(n,["endpoints"],_)}let f=l(e,["labels"]);if(f!=null)u(n,["labels"],f);let h=l(e,["_self"]);if(h!=null)u(n,["tunedModelInfo"],_I(h));let m=l(e,["defaultCheckpointId"]);if(m!=null)u(n,["defaultCheckpointId"],m);let g=l(e,["checkpoints"]);if(g!=null){let _=g;if(Array.isArray(_))_=_.map((v)=>v);u(n,["checkpoints"],_)}return n}function zS(e,t){let n={},o=l(e,["speakerVoiceConfigs"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>fI(a));u(n,["speakerVoiceConfigs"],s)}return n}function QS(e,t){let n={},o=l(e,["mediaResolution"]);if(o!=null)u(n,["mediaResolution"],o);let s=l(e,["toolCall"]);if(s!=null)u(n,["toolCall"],s);let a=l(e,["toolResponse"]);if(a!=null)u(n,["toolResponse"],a);let c=l(e,["audioTranscription"]);if(c!=null)u(n,["audioTranscription"],c);let d=l(e,["codeExecutionResult"]);if(d!=null)u(n,["codeExecutionResult"],d);let f=l(e,["executableCode"]);if(f!=null)u(n,["executableCode"],f);let h=l(e,["fileData"]);if(h!=null)u(n,["fileData"],hS(h));let m=l(e,["functionCall"]);if(m!=null)u(n,["functionCall"],mS(m));let g=l(e,["functionResponse"]);if(g!=null)u(n,["functionResponse"],g);let _=l(e,["inlineData"]);if(_!=null)u(n,["inlineData"],O0(_));let v=l(e,["text"]);if(v!=null)u(n,["text"],v);let E=l(e,["thought"]);if(E!=null)u(n,["thought"],E);let T=l(e,["thoughtSignature"]);if(T!=null)u(n,["thoughtSignature"],T);let S=l(e,["videoMetadata"]);if(S!=null)u(n,["videoMetadata"],S);let A=l(e,["partMetadata"]);if(A!=null)u(n,["partMetadata"],A);let w=l(e,["mediaProcessing"]);if(w!=null)u(n,["mediaProcessing"],w);return n}function ZS(e,t){let n={},o=l(e,["mediaResolution"]);if(o!=null)u(n,["mediaResolution"],o);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let s=l(e,["audioTranscription"]);if(s!=null)u(n,["audioTranscription"],s);let a=l(e,["codeExecutionResult"]);if(a!=null)u(n,["codeExecutionResult"],a);let c=l(e,["executableCode"]);if(c!=null)u(n,["executableCode"],c);let d=l(e,["fileData"]);if(d!=null)u(n,["fileData"],d);let f=l(e,["functionCall"]);if(f!=null)u(n,["functionCall"],f);let h=l(e,["functionResponse"]);if(h!=null)u(n,["functionResponse"],h);let m=l(e,["inlineData"]);if(m!=null)u(n,["inlineData"],m);let g=l(e,["text"]);if(g!=null)u(n,["text"],g);let _=l(e,["thought"]);if(_!=null)u(n,["thought"],_);let v=l(e,["thoughtSignature"]);if(v!=null)u(n,["thoughtSignature"],v);let E=l(e,["videoMetadata"]);if(E!=null)u(n,["videoMetadata"],E);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let T=l(e,["mediaProcessing"]);if(T!=null)u(n,["mediaProcessing"],T);return n}function jS(e,t){let n={},o=l(e,["productImage"]);if(o!=null)u(n,["image"],Et(o));return n}function eI(e,t,n){let o={},s=l(e,["numberOfImages"]);if(t!==void 0&&s!=null)u(t,["parameters","sampleCount"],s);let a=l(e,["baseSteps"]);if(t!==void 0&&a!=null)u(t,["parameters","baseSteps"],a);let c=l(e,["outputGcsUri"]);if(t!==void 0&&c!=null)u(t,["parameters","storageUri"],c);let d=l(e,["seed"]);if(t!==void 0&&d!=null)u(t,["parameters","seed"],d);let f=l(e,["safetyFilterLevel"]);if(t!==void 0&&f!=null)u(t,["parameters","safetySetting"],f);let h=l(e,["personGeneration"]);if(t!==void 0&&h!=null)u(t,["parameters","personGeneration"],h);let m=l(e,["addWatermark"]);if(t!==void 0&&m!=null)u(t,["parameters","addWatermark"],m);let g=l(e,["outputMimeType"]);if(t!==void 0&&g!=null)u(t,["parameters","outputOptions","mimeType"],g);let _=l(e,["outputCompressionQuality"]);if(t!==void 0&&_!=null)u(t,["parameters","outputOptions","compressionQuality"],_);let v=l(e,["enhancePrompt"]);if(t!==void 0&&v!=null)u(t,["parameters","enhancePrompt"],v);let E=l(e,["labels"]);if(t!==void 0&&E!=null)u(t,["labels"],E);return o}function tI(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["source"]);if(a!=null)rI(a,o);let c=l(t,["config"]);if(c!=null)eI(c,o);return o}function nI(e,t){let n={},o=l(e,["predictions"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>Bi(a));u(n,["generatedImages"],s)}return n}function rI(e,t,n){let o={},s=l(e,["prompt"]);if(t!==void 0&&s!=null)u(t,["instances[0]","prompt"],s);let a=l(e,["personImage"]);if(t!==void 0&&a!=null)u(t,["instances[0]","personImage","image"],Et(a));let c=l(e,["productImages"]);if(t!==void 0&&c!=null){let d=c;if(Array.isArray(d))d=d.map((f)=>jS(f));u(t,["instances[0]","productImages"],d)}return o}function iI(e,t){let n={},o=l(e,["referenceImage"]);if(o!=null)u(n,["referenceImage"],Et(o));let s=l(e,["referenceId"]);if(s!=null)u(n,["referenceId"],s);let a=l(e,["referenceType"]);if(a!=null)u(n,["referenceType"],a);let c=l(e,["maskImageConfig"]);if(c!=null)u(n,["maskImageConfig"],YS(c));let d=l(e,["controlImageConfig"]);if(d!=null)u(n,["controlImageConfig"],K0(d));let f=l(e,["styleImageConfig"]);if(f!=null)u(n,["styleImageConfig"],f);let h=l(e,["subjectImageConfig"]);if(h!=null)u(n,["subjectImageConfig"],h);return n}function oI(e,t){let n={},o=l(e,["mimeType"]);if(o!=null)u(n,["mimeType"],o);let s=l(e,["voiceSampleAudio"]);if(s!=null)u(n,["voiceSampleAudio"],s);if(l(e,["consentAudio"])!==void 0)throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["voiceConsentSignature"])!==void 0)throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bm(e,t){let n={},o=l(e,["safetyAttributes","categories"]);if(o!=null)u(n,["categories"],o);let s=l(e,["safetyAttributes","scores"]);if(s!=null)u(n,["scores"],s);let a=l(e,["contentType"]);if(a!=null)u(n,["contentType"],a);return n}function sI(e,t){let n={},o=l(e,["category"]);if(o!=null)u(n,["category"],o);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["threshold"]);if(s!=null)u(n,["threshold"],s);return n}function aI(e,t){let n={},o=l(e,["image"]);if(o!=null)u(n,["image"],Et(o));return n}function lI(e,t,n){let o={},s=l(e,["mode"]);if(t!==void 0&&s!=null)u(t,["parameters","mode"],s);let a=l(e,["maxPredictions"]);if(t!==void 0&&a!=null)u(t,["parameters","maxPredictions"],a);let c=l(e,["confidenceThreshold"]);if(t!==void 0&&c!=null)u(t,["parameters","confidenceThreshold"],c);let d=l(e,["maskDilation"]);if(t!==void 0&&d!=null)u(t,["parameters","maskDilation"],d);let f=l(e,["binaryColorThreshold"]);if(t!==void 0&&f!=null)u(t,["parameters","binaryColorThreshold"],f);let h=l(e,["labels"]);if(t!==void 0&&h!=null)u(t,["labels"],h);return o}function uI(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["source"]);if(a!=null)dI(a,o);let c=l(t,["config"]);if(c!=null)lI(c,o);return o}function cI(e,t){let n={},o=l(e,["predictions"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>DS(a));u(n,["generatedMasks"],s)}return n}function dI(e,t,n){let o={},s=l(e,["prompt"]);if(t!==void 0&&s!=null)u(t,["instances[0]","prompt"],s);let a=l(e,["image"]);if(t!==void 0&&a!=null)u(t,["instances[0]","image"],Et(a));let c=l(e,["scribbleImage"]);if(t!==void 0&&c!=null)u(t,["instances[0]","scribble"],aI(c));return o}function fI(e,t){let n={},o=l(e,["speaker"]);if(o!=null)u(n,["speaker"],o);let s=l(e,["voiceConfig"]);if(s!=null)u(n,["voiceConfig"],Hm(s));return n}function Lm(e,t){let n={},o=l(e,["voiceConfig"]);if(o!=null)u(n,["voiceConfig"],Hm(o));let s=l(e,["languageCode"]);if(s!=null)u(n,["languageCode"],s);let a=l(e,["multiSpeakerVoiceConfig"]);if(a!=null)u(n,["multiSpeakerVoiceConfig"],zS(a));return n}function pI(e,t){let n={},o=l(e,["functionCallingConfig"]);if(o!=null)u(n,["functionCallingConfig"],gS(o));let s=l(e,["retrievalConfig"]);if(s!=null)u(n,["retrievalConfig"],s);let a=l(e,["includeServerSideToolInvocations"]);if(a!=null)u(n,["includeServerSideToolInvocations"],a);return n}function hI(e,t){let n={},o=l(e,["functionCallingConfig"]);if(o!=null)u(n,["functionCallingConfig"],o);let s=l(e,["retrievalConfig"]);if(s!=null)u(n,["retrievalConfig"],s);if(l(e,["includeServerSideToolInvocations"])!==void 0)throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function mI(e,t){let n={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["googleMaps"]);if(o!=null)u(n,["googleMaps"],qS(o));let s=l(e,["mcpServers"]);if(s!=null){let _=s;if(Array.isArray(_))_=_.map((v)=>v);u(n,["mcpServers"],_)}let a=l(e,["codeExecution"]);if(a!=null)u(n,["codeExecution"],a);let c=l(e,["computerUse"]);if(c!=null)u(n,["computerUse"],c);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=l(e,["functionDeclarations"]);if(d!=null){let _=d;if(Array.isArray(_))_=_.map((v)=>v);u(n,["functionDeclarations"],_)}let f=l(e,["googleSearch"]);if(f!=null)u(n,["googleSearch"],OS(f));let h=l(e,["googleSearchRetrieval"]);if(h!=null)u(n,["googleSearchRetrieval"],h);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=l(e,["urlContext"]);if(m!=null)u(n,["urlContext"],m);let g=l(e,["fileSearch"]);if(g!=null)u(n,["fileSearch"],g);return n}function qm(e,t){let n={},o=l(e,["retrieval"]);if(o!=null)u(n,["retrieval"],o);let s=l(e,["googleMaps"]);if(s!=null)u(n,["googleMaps"],s);let a=l(e,["mcpServers"]);if(a!=null){let T=a;if(Array.isArray(T))T=T.map((S)=>WS(S));u(n,["mcpServers"],T)}let c=l(e,["codeExecution"]);if(c!=null)u(n,["codeExecution"],c);let d=l(e,["computerUse"]);if(d!=null)u(n,["computerUse"],$0(d));let f=l(e,["enterpriseWebSearch"]);if(f!=null)u(n,["enterpriseWebSearch"],f);let h=l(e,["exaAiSearch"]);if(h!=null)u(n,["exaAiSearch"],h);let m=l(e,["functionDeclarations"]);if(m!=null){let T=m;if(Array.isArray(T))T=T.map((S)=>S);u(n,["functionDeclarations"],T)}let g=l(e,["googleSearch"]);if(g!=null)u(n,["googleSearch"],g);let _=l(e,["googleSearchRetrieval"]);if(_!=null)u(n,["googleSearchRetrieval"],_);let v=l(e,["parallelAiSearch"]);if(v!=null)u(n,["parallelAiSearch"],v);let E=l(e,["urlContext"]);if(E!=null)u(n,["urlContext"],E);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function gI(e,t){let n={},o=l(e,["baseModel"]);if(o!=null)u(n,["baseModel"],o);let s=l(e,["createTime"]);if(s!=null)u(n,["createTime"],s);let a=l(e,["updateTime"]);if(a!=null)u(n,["updateTime"],a);return n}function _I(e,t){let n={},o=l(e,["labels","google-vertex-llm-tuning-base-model-id"]);if(o!=null)u(n,["baseModel"],o);let s=l(e,["createTime"]);if(s!=null)u(n,["createTime"],s);let a=l(e,["updateTime"]);if(a!=null)u(n,["updateTime"],a);return n}function yI(e,t,n){let o={},s=l(e,["displayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);let a=l(e,["description"]);if(t!==void 0&&a!=null)u(t,["description"],a);let c=l(e,["defaultCheckpointId"]);if(t!==void 0&&c!=null)u(t,["defaultCheckpointId"],c);return o}function EI(e,t,n){let o={},s=l(e,["displayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);let a=l(e,["description"]);if(t!==void 0&&a!=null)u(t,["description"],a);let c=l(e,["defaultCheckpointId"]);if(t!==void 0&&c!=null)u(t,["defaultCheckpointId"],c);return o}function vI(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","name"],pe(e,s));let a=l(t,["config"]);if(a!=null)yI(a,o);return o}function TI(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["config"]);if(a!=null)EI(a,o);return o}function AI(e,t,n){let o={},s=l(e,["outputGcsUri"]);if(t!==void 0&&s!=null)u(t,["parameters","storageUri"],s);let a=l(e,["safetyFilterLevel"]);if(t!==void 0&&a!=null)u(t,["parameters","safetySetting"],a);let c=l(e,["personGeneration"]);if(t!==void 0&&c!=null)u(t,["parameters","personGeneration"],c);let d=l(e,["includeRaiReason"]);if(t!==void 0&&d!=null)u(t,["parameters","includeRaiReason"],d);let f=l(e,["outputMimeType"]);if(t!==void 0&&f!=null)u(t,["parameters","outputOptions","mimeType"],f);let h=l(e,["outputCompressionQuality"]);if(t!==void 0&&h!=null)u(t,["parameters","outputOptions","compressionQuality"],h);let m=l(e,["enhanceInputImage"]);if(t!==void 0&&m!=null)u(t,["parameters","upscaleConfig","enhanceInputImage"],m);let g=l(e,["imagePreservationFactor"]);if(t!==void 0&&g!=null)u(t,["parameters","upscaleConfig","imagePreservationFactor"],g);let _=l(e,["labels"]);if(t!==void 0&&_!=null)u(t,["labels"],_);let v=l(e,["numberOfImages"]);if(t!==void 0&&v!=null)u(t,["parameters","sampleCount"],v);let E=l(e,["mode"]);if(t!==void 0&&E!=null)u(t,["parameters","mode"],E);return o}function CI(e,t,n){let o={},s=l(t,["model"]);if(s!=null)u(o,["_url","model"],pe(e,s));let a=l(t,["image"]);if(a!=null)u(o,["instances[0]","image"],Et(a));let c=l(t,["upscaleFactor"]);if(c!=null)u(o,["parameters","upscaleConfig","upscaleFactor"],c);let d=l(t,["config"]);if(d!=null)AI(d,o);return o}function SI(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["predictions"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>Bi(c));u(n,["generatedImages"],a)}return n}function II(e,t){let n={},o=l(e,["uri"]);if(o!=null)u(n,["uri"],o);let s=l(e,["encodedVideo"]);if(s!=null)u(n,["videoBytes"],En(s));let a=l(e,["encoding"]);if(a!=null)u(n,["mimeType"],a);return n}function wI(e,t){let n={},o=l(e,["gcsUri"]);if(o!=null)u(n,["uri"],o);let s=l(e,["bytesBase64Encoded"]);if(s!=null)u(n,["videoBytes"],En(s));let a=l(e,["mimeType"]);if(a!=null)u(n,["mimeType"],a);return n}function RI(e,t){let n={},o=l(e,["image"]);if(o!=null)u(n,["_self"],Et(o));let s=l(e,["maskMode"]);if(s!=null)u(n,["maskMode"],s);return n}function PI(e,t){let n={},o=l(e,["image"]);if(o!=null)u(n,["image"],$i(o));let s=l(e,["referenceType"]);if(s!=null)u(n,["referenceType"],s);return n}function NI(e,t){let n={},o=l(e,["image"]);if(o!=null)u(n,["image"],Et(o));let s=l(e,["referenceType"]);if(s!=null)u(n,["referenceType"],s);return n}function Om(e,t){let n={},o=l(e,["uri"]);if(o!=null)u(n,["uri"],o);let s=l(e,["videoBytes"]);if(s!=null)u(n,["encodedVideo"],En(s));let a=l(e,["mimeType"]);if(a!=null)u(n,["encoding"],a);return n}function Fm(e,t){let n={},o=l(e,["uri"]);if(o!=null)u(n,["gcsUri"],o);let s=l(e,["videoBytes"]);if(s!=null)u(n,["bytesBase64Encoded"],En(s));let a=l(e,["mimeType"]);if(a!=null)u(n,["mimeType"],a);return n}function Hm(e,t){let n={},o=l(e,["replicatedVoiceConfig"]);if(o!=null)u(n,["replicatedVoiceConfig"],oI(o));let s=l(e,["prebuiltVoiceConfig"]);if(s!=null)u(n,["prebuiltVoiceConfig"],s);return n}function xI(e,t,n){let o={},s=l(t,["displayName"]);if(n!==void 0&&s!=null)u(n,["displayName"],s);let a=l(t,["embeddingModel"]);if(n!==void 0&&a!=null)u(n,["embeddingModel"],pe(e,a));return o}function kI(e,t){let n={},o=l(t,["config"]);if(o!=null)xI(e,o,n);return n}function DI(e,t){let n={},o=l(e,["force"]);if(t!==void 0&&o!=null)u(t,["_query","force"],o);return n}function MI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);let o=l(e,["config"]);if(o!=null)DI(o,t);return t}function UI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);return t}function GI(e,t){let n={},o=l(e,["customMetadata"]);if(t!==void 0&&o!=null){let a=o;if(Array.isArray(a))a=a.map((c)=>c);u(t,["customMetadata"],a)}let s=l(e,["chunkingConfig"]);if(t!==void 0&&s!=null)u(t,["chunkingConfig"],s);return n}function bI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let o=l(e,["metadata"]);if(o!=null)u(t,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(t,["done"],s);let a=l(e,["error"]);if(a!=null)u(t,["error"],a);let c=l(e,["response"]);if(c!=null)u(t,["response"],qI(c));return t}function LI(e){let t={},n=l(e,["fileSearchStoreName"]);if(n!=null)u(t,["_url","file_search_store_name"],n);let o=l(e,["fileName"]);if(o!=null)u(t,["fileName"],o);let s=l(e,["config"]);if(s!=null)GI(s,t);return t}function qI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["parent"]);if(o!=null)u(t,["parent"],o);let s=l(e,["documentName"]);if(s!=null)u(t,["documentName"],s);return t}function OI(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);return n}function FI(e){let t={},n=l(e,["config"]);if(n!=null)OI(n,t);return t}function HI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["fileSearchStores"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["fileSearchStores"],a)}return t}function Vm(e,t){let n={},o=l(e,["mimeType"]);if(t!==void 0&&o!=null)u(t,["mimeType"],o);let s=l(e,["displayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);let a=l(e,["customMetadata"]);if(t!==void 0&&a!=null){let d=a;if(Array.isArray(d))d=d.map((f)=>f);u(t,["customMetadata"],d)}let c=l(e,["chunkingConfig"]);if(t!==void 0&&c!=null)u(t,["chunkingConfig"],c);return n}function VI(e){let t={},n=l(e,["fileSearchStoreName"]);if(n!=null)u(t,["_url","file_search_store_name"],n);let o=l(e,["config"]);if(o!=null)Vm(o,t);return t}function BI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}var $I="Content-Type",JI="X-Server-Timeout",XI="User-Agent",Us="x-goog-api-client",KI="2.21.0",YI=`google-genai-sdk/${KI}`,WI="v1beta1",zI="v1beta",QI=new Set(["us","eu"]);function ZI(e){let n=globalThis[Symbol.for("undici.globalDispatcher.1")];if(!n)return;for(let o of Object.getOwnPropertySymbols(n)){let s=o.description;if((s===null||s===void 0?void 0:s.includes("headers timeout"))||(s===null||s===void 0?void 0:s.includes("body timeout"))){let a=n[o];if(typeof a==="number")n[o]=Math.max(a,e)}}}function jI(e,t){let n=()=>{};if(!(e&&e>0)&&!t)return{signal:void 0,dispose:n};let o=new AbortController,s;if(e&&e>0){if(s=setTimeout(()=>o.abort(),e),s&&typeof s.unref==="function")s.unref()}let a=()=>o.abort();if(t)if(t.aborted)o.abort();else t.addEventListener("abort",a);return{signal:o.signal,dispose:()=>{if(s!==void 0)clearTimeout(s);t===null||t===void 0||t.removeEventListener("abort",a)}}}var ew=5,tw=1,nw=60,rw=2,iw=1,ow=[408,429,500,502,503,504];class Bm{constructor(e){var t,n,o;this.clientOptions=Object.assign({},e),this.customBaseUrl=(t=e.httpOptions)===null||t===void 0?void 0:t.baseUrl;let s={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl)this.clientOptions.location="global";if(!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let c=e.project&&e.location||!!e.apiKey;if(this.customBaseUrl&&!c)s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0;else if(this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global")s.baseUrl="https://aiplatform.googleapis.com/";else if(this.clientOptions.project&&this.clientOptions.location&&QI.has(this.clientOptions.location))s.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`;else if(this.clientOptions.project&&this.clientOptions.location)s.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`;s.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:WI}else{if(!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:zI,s.baseUrl="https://generativelanguage.googleapis.com/"}if(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 Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw 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;else throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw Error("HTTP options are not correctly set.");let n=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];if(e.apiVersion&&e.apiVersion!=="")n.push(e.apiVersion);return n.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,n){let o=[this.getRequestUrlInternal(t)];if(n)o.push(this.getBaseResourcePath());if(e!=="")o.push(e);return new URL(`${o.join("/")}`)}shouldPrependVertexProjectPath(e,t){if(t.baseUrl&&t.baseUrlResourceScope===fr.COLLECTION)return!1;if(!this.clientOptions.vertexai)return!1;if(!this.clientOptions.project||!this.clientOptions.location)return!1;if(e.path.startsWith("projects/"))return!1;if(e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))return!1;return!0}async request(e){let t=this.clientOptions.httpOptions;if(e.httpOptions)t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions);let n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);if(e.queryParams)for(let[a,c]of Object.entries(e.queryParams))o.searchParams.append(a,String(c));let s={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw 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,t,o.toString()),this.unaryApiCall(o,s,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal)}patchHttpOptions(e,t){let n=JSON.parse(JSON.stringify(e));for(let[o,s]of Object.entries(t))if(typeof s==="object")n[o]=Object.assign(Object.assign({},n[o]),s);else if(s!==void 0)n[o]=s;return n}async requestStream(e){let t=this.clientOptions.httpOptions;if(e.httpOptions)t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions);let n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);if(!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,t,o.toString()),this.streamApiCall(o,s,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal)}async includeExtraHttpOptionsToRequestInit(e,t,n){if((t===null||t===void 0?void 0:t.timeout)&&t.timeout>0)ZI(t.timeout);if(t&&t.extraBody!==null)sw(e,t.extraBody);return e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n,o,s,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,s,a).then(async(c)=>(await _s(c),new yn(c))).catch((c)=>{if(c instanceof Error)throw c;else throw Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,t,n,o,s,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,s,a).then(async(c)=>(await _s(c),this.processStreamResponse(c))).catch((c)=>{if(c instanceof Error)throw c;else throw Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return Xn(this,arguments,function*(){var n;let o=(n=e===null||e===void 0?void 0:e.body)===null||n===void 0?void 0:n.getReader(),s=new TextDecoder("utf-8");if(!o)throw Error("Response body is empty");try{let a="",c="data:",d=[`
|
|
31
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class Pf{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 RangeError(Nf.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);if(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((t)=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Nf.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;else 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;else throw Error(Nf.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){if(this._cachedProjectId)return this._cachedProjectId;if(!this._findProjectIdPromise)this._findProjectIdPromise=this.findAndCacheProjectId();return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let e;try{e=await Rt.universe("universe-domain"),e||=qn.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=qn.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=wi.originalOrCamelOptions(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=qn.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e==="function")t=e;else n=e;if(t)this.getApplicationDefaultAsync(n).then((i)=>t(null,i.credential,i.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t){if(t instanceof ct.JWT)t.scopes=this.scopes;else if(t instanceof Pt.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t){if(t instanceof ct.JWT)t.scopes=this.scopes;else if(t instanceof Pt.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new Sf.Compute(e));throw Error(Nf.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();if(t)e.quotaProjectId=t;return this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){if(this.checkIsGCE===void 0)this.checkIsGCE=Rt.getGCPResidency()||await Rt.isAvailable();return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(t,e)}catch(n){if(n instanceof Error)n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`;throw n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=process.env.CLOUDSDK_CONFIG;if(!t)if(this._isWindows()){if(process.env.APPDATA)t=rn.join(process.env.APPDATA,"gcloud")}else{let o=process.env.HOME;if(o)t=rn.join(o,".config","gcloud")}if(!t)return null;let n=rn.join(t,"application_default_credentials.json");if(!wt.existsSync(n))return null;return await this._getApplicationCredentialsFromFilePath(n,e)}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw Error("The file path is invalid.");try{if(e=wt.realpathSync(e),!wt.lstatSync(e).isFile())throw Error()}catch(i){if(i instanceof Error)i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`;throw i}let n=wt.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==dt.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${dt.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let i=(this.scopes||e.scopes||this.defaultScopes)??[];return new dt.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,t={}){let n,i=wi.originalOrCamelOptions(t).get("universe_domain");if(e.type===Si.USER_REFRESH_ACCOUNT_TYPE)n=new Si.UserRefreshClient(t),n.fromJSON(e);else if(e.type===dt.IMPERSONATED_ACCOUNT_TYPE)n=this.fromImpersonatedJSON(e);else if(e.type===Pt.EXTERNAL_ACCOUNT_TYPE)n=Rf.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes();else if(e.type===Ii.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE)n=new Ii.ExternalAccountAuthorizedUserClient({...e,...t});else if(e.type===On.GDCH_SERVICE_ACCOUNT_TYPE)n=new On.GdchClient(t),n.fromJSON(e);else t.scopes=this.scopes,n=new ct.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e);if(i)n.universeDomain=i;return n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let i={};if(typeof t==="function")n=t;else i=t;if(n)this.fromStreamAsync(e,i).then((o)=>n(null,o),n);else return this.fromStreamAsync(e,i)}fromStreamAsync(e,t){return new Promise((n,i)=>{if(!e)throw Error("Must pass in a stream containing the Google auth settings.");let o=[];e.setEncoding("utf8").on("error",i).on("data",(s)=>o.push(s)).on("end",()=>{try{try{let s=JSON.parse(o.join("")),c=this._cacheClientFromJSON(s,t);return n(c)}catch(s){if(!this.keyFilename)throw s;let c=new ct.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(s){return i(s)}})})}fromAPIKey(e,t={}){return new ct.JWT({...t,apiKey:e})}_isWindows(){let e=Af.platform();if(e&&e.length>=3){if(e.substring(0,3).toLowerCase()==="win")return!0}return!1}async getDefaultServiceProjectId(){return new Promise((e)=>{vf.exec("gcloud config config-helper --format json",(t,n)=>{if(!t&&n)try{let i=JSON.parse(n).configuration.properties.core.project;e(i);return}catch(i){}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 t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(e)return e.projectId;else return null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==Pt.EXTERNAL_ACCOUNT_TYPE)return null;return await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Rt.project("project-id")}catch(e){return null}}getCredentials(e){if(e)this.getCredentialsAsync().then((t)=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof dt.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Pt.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,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[t,n]=await Promise.all([Rt.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:n}}throw Error(Nf.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof On.GdchClient&&!e.apiAudience){let t=this.clientOptions,n=t.apiEndpoint||t.servicePath;if(n){let o=`${n.startsWith("http")?"":"https://"}${n}`.replace(/\/+$/,""),s=e.createWithGdchAudience(o);return this.cachedCredential=s,s}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);else if(this.keyFilename){let e=rn.resolve(this.keyFilename),t=wt.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw 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 If.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,i=await(await this.getClient()).getRequestHeaders(t);return e.headers=Tf.Gaxios.mergeHeaders(e.headers,i),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return wf.getEnv()}async sign(e,t){let n=await this.getClient(),i=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${i}/v1/projects/-/serviceAccounts/`,n instanceof dt.Impersonated)return(await n.sign(e)).signedBlob;let o=Cf.createCrypto();if(n instanceof ct.JWT&&n.key)return await o.sign(n.key,e);let s=await this.getCredentials();if(!s.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(o,s.client_email,e,t)}async signBlob(e,t,n,i){let o=new URL(i+`${t}:signBlob`);return(await this.request({method:"POST",url:o.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}Nf.GoogleAuth=Pf});var Gf=r(function(Mf){Object.defineProperty(Mf,"__esModule",{value:!0});Mf.IAMAuth=void 0;class Df{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}Mf.IAMAuth=Df});var Vf=r(function(Ff){Object.defineProperty(Ff,"__esModule",{value:!0});Ff.DownscopedClient=Ff.EXPIRATION_TIME_OFFSET=Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var bf=Oe(),Lf=p("stream"),Fn=Ze(),qf=ui(),vT="urn:ietf:params:oauth:grant-type:token-exchange",TT="urn:ietf:params:oauth:token-type:access_token",AT="urn:ietf:params:oauth:token-type:access_token";Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Ff.EXPIRATION_TIME_OFFSET=300000;class Of extends Fn.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){super(e instanceof Fn.AuthClient?{}:e);if(e instanceof Fn.AuthClient)this.authClient=e,this.credentialAccessBoundary=t;else this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary;if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error("At least one access boundary rule needs to be defined.");else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${Ff.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new qf.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((n)=>t(null,n),(n)=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let i=await this.getRequestHeaders();e.headers=bf.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),n=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let s=o.status,c=o.config.data instanceof Lf.Readable;if(!t&&(s===401||s===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:vT,requestedTokenType:TT,subjectToken:e,subjectTokenType:AT},n=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,o=n.expires_in?new Date().getTime()+n.expires_in*1000:i;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:o,res:n.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 t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}Ff.DownscopedClient=Of});var Kf=r(function(Jf){Object.defineProperty(Jf,"__esModule",{value:!0});Jf.PassThroughClient=void 0;var Bf=Ze();class $f extends Bf.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}Jf.PassThroughClient=$f});var Zf=r(function(Q){var ST=Q&&Q.__createBinding||(Object.create?function(e,t,n,i){if(i===void 0)i=n;var o=Object.getOwnPropertyDescriptor(t,n);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[n]}};Object.defineProperty(e,i,o)}:function(e,t,n,i){if(i===void 0)i=n;e[i]=t[n]}),IT=Q&&Q.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))ST(t,e,n)};Object.defineProperty(Q,"__esModule",{value:!0});Q.GoogleAuth=Q.auth=Q.GDCH_SERVICE_ACCOUNT_TYPE=Q.GdchClient=Q.PassThroughClient=Q.ExternalAccountAuthorizedUserClient=Q.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Q.ExecutableError=Q.PluggableAuthClient=Q.DownscopedClient=Q.BaseExternalAccountClient=Q.ExternalAccountClient=Q.IdentityPoolClient=Q.AwsRequestSigner=Q.AwsClient=Q.UserRefreshClient=Q.LoginTicket=Q.ClientAuthentication=Q.OAuth2Client=Q.CodeChallengeMethod=Q.Impersonated=Q.JWT=Q.JWTAccess=Q.IdTokenClient=Q.IAMAuth=Q.GCPEnv=Q.Compute=Q.DEFAULT_UNIVERSE=Q.AuthClient=Q.gaxios=Q.gcpMetadata=void 0;var Ri=kf();Object.defineProperty(Q,"GoogleAuth",{enumerable:!0,get:function(){return Ri.GoogleAuth}});Q.gcpMetadata=rr();Q.gaxios=Oe();var Yf=Ze();Object.defineProperty(Q,"AuthClient",{enumerable:!0,get:function(){return Yf.AuthClient}});Object.defineProperty(Q,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Yf.DEFAULT_UNIVERSE}});var wT=Ao();Object.defineProperty(Q,"Compute",{enumerable:!0,get:function(){return wT.Compute}});var RT=So();Object.defineProperty(Q,"GCPEnv",{enumerable:!0,get:function(){return RT.GCPEnv}});var PT=Gf();Object.defineProperty(Q,"IAMAuth",{enumerable:!0,get:function(){return PT.IAMAuth}});var NT=Co();Object.defineProperty(Q,"IdTokenClient",{enumerable:!0,get:function(){return NT.IdTokenClient}});var xT=Lo();Object.defineProperty(Q,"JWTAccess",{enumerable:!0,get:function(){return xT.JWTAccess}});var kT=Oo();Object.defineProperty(Q,"JWT",{enumerable:!0,get:function(){return kT.JWT}});var DT=Ho();Object.defineProperty(Q,"Impersonated",{enumerable:!0,get:function(){return DT.Impersonated}});var gs=Vt();Object.defineProperty(Q,"CodeChallengeMethod",{enumerable:!0,get:function(){return gs.CodeChallengeMethod}});Object.defineProperty(Q,"OAuth2Client",{enumerable:!0,get:function(){return gs.OAuth2Client}});Object.defineProperty(Q,"ClientAuthentication",{enumerable:!0,get:function(){return gs.ClientAuthentication}});var MT=To();Object.defineProperty(Q,"LoginTicket",{enumerable:!0,get:function(){return MT.LoginTicket}});var UT=Fo();Object.defineProperty(Q,"UserRefreshClient",{enumerable:!0,get:function(){return UT.UserRefreshClient}});var GT=Wo();Object.defineProperty(Q,"AwsClient",{enumerable:!0,get:function(){return GT.AwsClient}});var bT=Yo();Object.defineProperty(Q,"AwsRequestSigner",{enumerable:!0,get:function(){return bT.AwsRequestSigner}});var LT=Ko();Object.defineProperty(Q,"IdentityPoolClient",{enumerable:!0,get:function(){return LT.IdentityPoolClient}});var qT=us();Object.defineProperty(Q,"ExternalAccountClient",{enumerable:!0,get:function(){return qT.ExternalAccountClient}});var OT=Wt();Object.defineProperty(Q,"BaseExternalAccountClient",{enumerable:!0,get:function(){return OT.BaseExternalAccountClient}});var FT=Vf();Object.defineProperty(Q,"DownscopedClient",{enumerable:!0,get:function(){return FT.DownscopedClient}});var Wf=ls();Object.defineProperty(Q,"PluggableAuthClient",{enumerable:!0,get:function(){return Wf.PluggableAuthClient}});Object.defineProperty(Q,"ExecutableError",{enumerable:!0,get:function(){return Wf.ExecutableError}});var zf=ds();Object.defineProperty(Q,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return zf.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Q,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return zf.ExternalAccountAuthorizedUserClient}});var HT=Kf();Object.defineProperty(Q,"PassThroughClient",{enumerable:!0,get:function(){return HT.PassThroughClient}});var Qf=hs();Object.defineProperty(Q,"GdchClient",{enumerable:!0,get:function(){return Qf.GdchClient}});Object.defineProperty(Q,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return Qf.GDCH_SERVICE_ACCOUNT_TYPE}});IT(Go(),Q);var VT=new Ri.GoogleAuth;Q.auth=VT});var Kh=a(ca(),1),Yh=a(Zf(),1);import{createWriteStream as BT}from"fs";import*as Fi from"fs/promises";import{writeFile as $T}from"fs/promises";import{Readable as JT}from"stream";import{finished as XT}from"stream/promises";import*as Wh from"ws";import*as zh from"path";var KT=void 0,YT=void 0;function WT(){return{geminiUrl:KT,vertexUrl:YT}}function zT(e,t,n,i){var o,s;if(!(e===null||e===void 0?void 0:e.baseUrl)){let c=WT();if(t)return(o=c.vertexUrl)!==null&&o!==void 0?o:n;else return(s=c.geminiUrl)!==null&&s!==void 0?s:i}return e.baseUrl}class xt{}function z(e,t){let n=/\{([^}]+)\}/g;return e.replace(n,(i,o)=>{if(Object.prototype.hasOwnProperty.call(t,o)){let s=t[o];return s!==void 0&&s!==null?String(s):""}else throw Error(`Key '${o}' not found in valueMap.`)})}function u(e,t,n){for(let s=0;s<t.length-1;s++){let c=t[s];if(c.endsWith("[]")){let d=c.slice(0,-2);if(!(d in e))if(Array.isArray(n))e[d]=Array.from({length:n.length},()=>({}));else throw Error(`Value must be a list given an array path ${c}`);if(Array.isArray(e[d])){let f=e[d];if(Array.isArray(n))for(let h=0;h<f.length;h++){let m=f[h];u(m,t.slice(s+1),n[h])}else for(let h of f)u(h,t.slice(s+1),n)}return}else if(c.endsWith("[0]")){let d=c.slice(0,-3);if(!(d in e))e[d]=[{}];let f=e[d];u(f[0],t.slice(s+1),n);return}if(!e[c]||typeof e[c]!=="object")e[c]={};e=e[c]}let i=t[t.length-1],o=e[i];if(o!==void 0){if(!n||typeof n==="object"&&Object.keys(n).length===0)return;if(n===o)return;if(typeof o==="object"&&typeof n==="object"&&o!==null&&n!==null)Object.assign(o,n);else throw Error(`Cannot set value for an existing key. Key: ${i}`)}else if(i==="_self"&&typeof n==="object"&&n!==null&&!Array.isArray(n))Object.assign(e,n);else e[i]=n}function l(e,t,n=void 0){try{if(t.length===1&&t[0]==="_self")return e;for(let i=0;i<t.length;i++){if(typeof e!=="object"||e===null)return n;let o=t[i];if(o.endsWith("[]")){let s=o.slice(0,-2);if(s in e){let c=e[s];if(!Array.isArray(c))return n;return c.map((d)=>l(d,t.slice(i+1),n))}else return n}else e=e[o]}return e}catch(i){if(i instanceof TypeError)return n;throw i}}function QT(e,t){for(let[n,i]of Object.entries(t)){let o=n.split("."),s=i.split("."),c=new Set,d=-1;for(let f=0;f<o.length;f++)if(o[f]==="*"){d=f;break}if(d!==-1&&s.length>d)for(let f=d;f<s.length;f++){let h=s[f];if(h!=="*"&&!h.endsWith("[]")&&!h.endsWith("[0]"))c.add(h)}vs(e,o,s,0,c)}}function vs(e,t,n,i,o){if(i>=t.length)return;if(typeof e!=="object"||e===null)return;let s=t[i];if(s.endsWith("[]")){let c=s.slice(0,-2),d=e;if(c in d&&Array.isArray(d[c]))for(let f of d[c])vs(f,t,n,i+1,o)}else if(s==="*"){if(typeof e==="object"&&e!==null&&!Array.isArray(e)){let c=e,d=Object.keys(c).filter((h)=>!h.startsWith("_")&&!o.has(h)),f={};for(let h of d)f[h]=c[h];for(let[h,m]of Object.entries(f)){let g=[];for(let _ of n.slice(i))if(_==="*")g.push(h);else g.push(_);u(c,g,m)}for(let h of d)delete c[h]}}else{let c=e;if(s in c)vs(c[s],t,n,i+1,o)}}function Fs(e){if(typeof e!=="string")throw Error("fromImageBytes must be a string");return e}function ZT(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["operationName"],n);let i=l(e,["resourceName"]);if(i!=null)u(t,["_url","resourceName"],i);return t}function jT(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["response","generateVideoResponse"]);if(c!=null)u(t,["response"],tA(c));return t}function eA(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["response"]);if(c!=null)u(t,["response"],nA(c));return t}function tA(e){let t={},n=l(e,["generatedSamples"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((c)=>rA(c));u(t,["generatedVideos"],s)}let i=l(e,["raiMediaFilteredCount"]);if(i!=null)u(t,["raiMediaFilteredCount"],i);let o=l(e,["raiMediaFilteredReasons"]);if(o!=null)u(t,["raiMediaFilteredReasons"],o);return t}function nA(e){let t={},n=l(e,["videos"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((c)=>iA(c));u(t,["generatedVideos"],s)}let i=l(e,["raiMediaFilteredCount"]);if(i!=null)u(t,["raiMediaFilteredCount"],i);let o=l(e,["raiMediaFilteredReasons"]);if(o!=null)u(t,["raiMediaFilteredReasons"],o);return t}function rA(e){let t={},n=l(e,["video"]);if(n!=null)u(t,["video"],cA(n));return t}function iA(e){let t={},n=l(e,["_self"]);if(n!=null)u(t,["video"],dA(n));return t}function oA(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["_url","operationName"],n);return t}function sA(e){let t={},n=l(e,["operationName"]);if(n!=null)u(t,["_url","operationName"],n);return t}function aA(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["response"]);if(c!=null)u(t,["response"],lA(c));return t}function lA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["parent"]);if(i!=null)u(t,["parent"],i);let o=l(e,["documentName"]);if(o!=null)u(t,["documentName"],o);return t}function Hs(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["response"]);if(c!=null)u(t,["response"],uA(c));return t}function uA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["parent"]);if(i!=null)u(t,["parent"],i);let o=l(e,["documentName"]);if(o!=null)u(t,["documentName"],o);return t}function cA(e){let t={},n=l(e,["uri"]);if(n!=null)u(t,["uri"],n);let i=l(e,["encodedVideo"]);if(i!=null)u(t,["videoBytes"],Fs(i));let o=l(e,["encoding"]);if(o!=null)u(t,["mimeType"],o);return t}function dA(e){let t={},n=l(e,["gcsUri"]);if(n!=null)u(t,["uri"],n);let i=l(e,["bytesBase64Encoded"]);if(i!=null)u(t,["videoBytes"],Fs(i));let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}var jf;(function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(jf||(jf={}));var ep;(function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"})(ep||(ep={}));var tp;(function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"})(tp||(tp={}));var on;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"})(on||(on={}));var np;(function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"})(np||(np={}));var rp;(function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(rp||(rp={}));var ip;(function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ip||(ip={}));var op;(function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(op||(op={}));var sp;(function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(sp||(sp={}));var ap;(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(ap||(ap={}));var lp;(function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"})(lp||(lp={}));var up;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(up||(up={}));var ln;(function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(ln||(ln={}));var cp;(function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"})(cp||(cp={}));var dp;(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(dp||(dp={}));var fp;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(fp||(fp={}));var pp;(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"})(pp||(pp={}));var hp;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"})(hp||(hp={}));var un;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"})(un||(un={}));var De;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER"})(De||(De={}));var mp;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(mp||(mp={}));var gp;(function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(gp||(gp={}));var _p;(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(_p||(_p={}));var yp;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"})(yp||(yp={}));var Ep;(function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Ep||(Ep={}));var vp;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"})(vp||(vp={}));var Tp;(function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"})(Tp||(Tp={}));var Ap;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Ap||(Ap={}));var Ui;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"})(Ui||(Ui={}));var Cp;(function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"})(Cp||(Cp={}));var Sp;(function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(Sp||(Sp={}));var Ip;(function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(Ip||(Ip={}));var wp;(function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(wp||(wp={}));var Rp;(function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Rp||(Rp={}));var Pp;(function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"})(Pp||(Pp={}));var Np;(function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"})(Np||(Np={}));var xp;(function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.HIGH="HIGH"})(xp||(xp={}));var Ts;(function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(Ts||(Ts={}));var kp;(function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(kp||(kp={}));var Dp;(function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"})(Dp||(Dp={}));var Mp;(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"})(Mp||(Mp={}));var Up;(function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"})(Up||(Up={}));var Gp;(function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"})(Gp||(Gp={}));var bp;(function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"})(bp||(bp={}));var Lp;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"})(Lp||(Lp={}));var qp;(function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"})(qp||(qp={}));var Op;(function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"})(Op||(Op={}));var Fp;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Fp||(Fp={}));var Hp;(function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"})(Hp||(Hp={}));var vr;(function(e){e.COLLECTION="COLLECTION"})(vr||(vr={}));var Vp;(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"})(Vp||(Vp={}));var Gi;(function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT"})(Gi||(Gi={}));var Bp;(function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})(Bp||(Bp={}));var $p;(function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"})($p||($p={}));var Jp;(function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Jp||(Jp={}));var Xp;(function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Xp||(Xp={}));var Kp;(function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Kp||(Kp={}));var Yp;(function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Yp||(Yp={}));var Wp;(function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"})(Wp||(Wp={}));var zp;(function(e){e.ASSET="ASSET",e.STYLE="STYLE"})(zp||(zp={}));var Qp;(function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"})(Qp||(Qp={}));var Zp;(function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"})(Zp||(Zp={}));var jp;(function(e){e.CROP="CROP",e.PAD="PAD"})(jp||(jp={}));var eh;(function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(eh||(eh={}));var th;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"})(th||(th={}));var nh;(function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"})(nh||(nh={}));var rh;(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(rh||(rh={}));var ih;(function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"})(ih||(ih={}));var oh;(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(oh||(oh={}));var sh;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"})(sh||(sh={}));var ah;(function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(ah||(ah={}));var lh;(function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(lh||(lh={}));var uh;(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"})(uh||(uh={}));var ch;(function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(ch||(ch={}));var dh;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"})(dh||(dh={}));var fh;(function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(fh||(fh={}));var ph;(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"})(ph||(ph={}));var Bn;(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"})(Bn||(Bn={}));class yn{constructor(e){let t={};for(let n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class Hn{get text(){var e,t,n,i,o,s,c,d;if(((i=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||i===void 0?void 0:i.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning text from the first one.");let f="",h=!1,m=[];for(let g of(d=(c=(s=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[_,E]of Object.entries(g))if(_!=="text"&&_!=="thought"&&_!=="thoughtSignature"&&(E!==null||E!==void 0))m.push(_);if(typeof g.text==="string"){if(typeof g.thought==="boolean"&&g.thought)continue;h=!0,f+=g.text}}if(m.length>0)console.warn(`there are non-text parts ${m} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);return h?f:void 0}get data(){var e,t,n,i,o,s,c,d;if(((i=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||i===void 0?void 0:i.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning data from the first one.");let f="",h=[];for(let m of(d=(c=(s=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[g,_]of Object.entries(m))if(g!=="inlineData"&&(_!==null||_!==void 0))h.push(g);if(m.inlineData&&typeof m.inlineData.data==="string")f+=atob(m.inlineData.data)}if(h.length>0)console.warn(`there are non-data parts ${h} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);return f.length>0?btoa(f):void 0}get functionCalls(){var e,t,n,i,o,s,c,d;if(((i=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||i===void 0?void 0:i.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning function calls from the first one.");let f=(d=(c=(s=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((h)=>h.functionCall).map((h)=>h.functionCall).filter((h)=>h!==void 0);if((f===null||f===void 0?void 0:f.length)===0)return;return f}get executableCode(){var e,t,n,i,o,s,c,d,f;if(((i=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||i===void 0?void 0:i.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning executable code from the first one.");let h=(d=(c=(s=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((m)=>m.executableCode).map((m)=>m.executableCode).filter((m)=>m!==void 0);if((h===null||h===void 0?void 0:h.length)===0)return;return(f=h===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.code}get codeExecutionResult(){var e,t,n,i,o,s,c,d,f;if(((i=(n=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||n===void 0?void 0:n.parts)===null||i===void 0?void 0:i.length)===0)return;if(this.candidates&&this.candidates.length>1)console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let h=(d=(c=(s=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter((m)=>m.codeExecutionResult).map((m)=>m.codeExecutionResult).filter((m)=>m!==void 0);if((h===null||h===void 0?void 0:h.length)===0)return;return(f=h===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.output}}class As{}class Qh{}class Zh{}class jh{}class em{}class tm{}class Cs{}class Ss{}class Is{}class nm{}class bi{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new bi,i,o=e;if(t)i=eA(o);else i=jT(o);return Object.assign(n,i),n}}class rm{}class ws{}class im{}class Rs{}class Ps{}class om{}class sm{}class am{}class Vs{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new Vs,o=aA(e);return Object.assign(n,o),n}}class lm{}class um{}class cm{}class dm{}class Ns{}class fm{get text(){var e,t,n;let i="",o=!1,s=[];for(let c of(n=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&n!==void 0?n:[]){for(let[d,f]of Object.entries(c))if(d!=="text"&&d!=="thought"&&f!==null)s.push(d);if(typeof c.text==="string"){if(typeof c.thought==="boolean"&&c.thought)continue;o=!0,i+=c.text}}if(s.length>0)console.warn(`there are non-text parts ${s} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);return o?i:void 0}get data(){var e,t,n;let i="",o=[];for(let s of(n=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&n!==void 0?n:[]){for(let[c,d]of Object.entries(s))if(c!=="inlineData"&&d!==null)o.push(c);if(s.inlineData&&typeof s.inlineData.data==="string")i+=atob(s.inlineData.data)}if(o.length>0)console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);return i.length>0?btoa(i):void 0}}class pm{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0];return}}class Hi{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let n=new Hi,o=Hs(e);return Object.assign(n,o),n}}function de(e,t){if(!t||typeof t!=="string")throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else if(t.indexOf("/")>=0){let n=t.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${t}`;else if(t.startsWith("models/")||t.startsWith("tunedModels/"))return t;else return`models/${t}`}function hm(e,t){let n=de(e,t);if(!n)return"";if(n.startsWith("publishers/")&&e.isVertexAI())return`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`;else if(n.startsWith("models/")&&e.isVertexAI())return`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`;else return n}function mm(e){if(Array.isArray(e))return e.map((t)=>Li(t));else return[Li(e)]}function Li(e){if(typeof e==="object"&&e!==null)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function gm(e){let t=Li(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function _m(e){let t=Li(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function hh(e){if(e===null||e===void 0)throw Error("PartUnion is required");if(typeof e==="object")return e;if(typeof e==="string")return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function ym(e){if(e===null||e===void 0||Array.isArray(e)&&e.length===0)throw Error("PartListUnion is required");if(Array.isArray(e))return e.map((t)=>hh(t));return[hh(e)]}function xs(e){return e!==null&&e!==void 0&&typeof e==="object"&&"parts"in e&&Array.isArray(e.parts)}function mh(e){return e!==null&&e!==void 0&&typeof e==="object"&&"functionCall"in e}function gh(e){return e!==null&&e!==void 0&&typeof e==="object"&&"functionResponse"in e}function qe(e){if(e===null||e===void 0)throw Error("ContentUnion is required");if(xs(e))return e;return{role:"user",parts:ym(e)}}function Bs(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap((n)=>{let i=qe(n);if(i.parts&&i.parts.length>0&&i.parts[0].text!==void 0)return[i.parts[0].text];return[]});else if(e.isVertexAI()){let n=qe(t);if(n.parts&&n.parts.length>0&&n.parts[0].text!==void 0)return[n.parts[0].text];return[]}if(Array.isArray(t))return t.map((n)=>qe(n));return[qe(t)]}function We(e){if(e===null||e===void 0||Array.isArray(e)&&e.length===0)throw Error("contents are required");if(!Array.isArray(e)){if(mh(e)||gh(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[qe(e)]}let t=[],n=[],i=xs(e[0]);for(let o of e){let s=xs(o);if(s!=i)throw 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)t.push(o);else if(mh(o)||gh(o))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else n.push(o)}if(!i)t.push({role:"user",parts:ym(n)});return t}function fA(e,t){if(e.includes("null"))t.nullable=!0;let n=e.filter((i)=>i!=="null");if(n.length===1)t.type=Object.values(on).includes(n[0].toUpperCase())?n[0].toUpperCase():on.TYPE_UNSPECIFIED;else{t.anyOf=[];for(let i of n)t.anyOf.push({type:Object.values(on).includes(i.toUpperCase())?i.toUpperCase():on.TYPE_UNSPECIFIED})}}function Jn(e){let t={},n=["items"],i=["anyOf"],o=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let s=e.anyOf;if(s!=null&&s.length==2){if(s[0].type==="null")t.nullable=!0,e=s[1];else if(s[1].type==="null")t.nullable=!0,e=s[0]}if(e.type instanceof Array)fA(e.type,t);for(let[c,d]of Object.entries(e)){if(d==null)continue;if(c=="type"){if(d==="null")throw Error("type: null can not be the only possible type for the field.");if(d instanceof Array)continue;t.type=Object.values(on).includes(d.toUpperCase())?d.toUpperCase():on.TYPE_UNSPECIFIED}else if(n.includes(c))t[c]=Jn(d);else if(i.includes(c)){let f=[];for(let h of d){if(h.type=="null"){t.nullable=!0;continue}f.push(Jn(h))}t[c]=f}else if(o.includes(c)){let f={};for(let[h,m]of Object.entries(d))f[h]=Jn(m);t[c]=f}else{if(c==="additionalProperties")continue;t[c]=d}}return t}function $s(e){return Jn(e)}function Yn(e){return e}function Js(e){if(typeof e==="object")return e;else if(typeof e==="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};else throw Error(`Unsupported speechConfig type: ${typeof e}`)}function Xs(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Wn(e){if(e.functionDeclarations)for(let t of e.functionDeclarations){if(t.parameters){if(!Object.keys(t.parameters).includes("$schema"))t.parameters=Jn(t.parameters);else if(!t.parametersJsonSchema)t.parametersJsonSchema=t.parameters,delete t.parameters}if(t.response){if(!Object.keys(t.response).includes("$schema"))t.response=Jn(t.response);else if(!t.responseJsonSchema)t.responseJsonSchema=t.response,delete t.response}}return e}function zn(e){if(e===void 0||e===null)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let n of e)t.push(n);return t}function pA(e,t,n,i=1){let o=!t.startsWith(`${n}/`)&&t.split("/").length===i;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${n}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(o)return`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`;else return t;if(o)return`${n}/${t}`;return t}function Ot(e,t){if(typeof t!=="string")throw Error("name must be a string");return pA(e,t,"cachedContents")}function Em(e){switch(e){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 e}}function En(e){return Fs(e)}function hA(e){return e!==null&&e!==void 0&&typeof e==="object"&&"name"in e}function vm(e){return e!==null&&e!==void 0&&typeof e==="object"&&"video"in e}function Tm(e){return e!==null&&e!==void 0&&typeof e==="object"&&"uri"in e}function Ks(e){var t;let n;if(hA(e))n=e.name;if(Tm(e)){if(n=e.uri,n===void 0)return}if(vm(e)){if(n=(t=e.video)===null||t===void 0?void 0:t.uri,n===void 0)return}if(typeof e==="string")n=e;if(n===void 0)throw 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 Error(`Could not extract file name from URI ${n}`);n=o[0]}else if(n.startsWith("files/"))n=n.split("files/")[1];return n}function Am(e,t){let n;if(e.isVertexAI())n=t?"publishers/google/models":"models";else n=t?"models":"tunedModels";return n}function Cm(e){for(let t of["models","tunedModels","publisherModels"])if(mA(e,t))return e[t];return[]}function mA(e,t){return e!==null&&typeof e==="object"&&t in e}function gA(e,t={}){let n=e,i={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};if(n.outputSchema)i.responseJsonSchema=n.outputSchema;if(t.behavior)i.behavior=t.behavior;return{functionDeclarations:[i]}}function _A(e,t={}){let n=[],i=new Set;for(let o of e){let s=o.name;if(i.has(s))throw Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);i.add(s);let c=gA(o,t);if(c.functionDeclarations)n.push(...c.functionDeclarations)}return{functionDeclarations:n}}function Sm(e,t){let n;if(typeof t==="string")if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))n={format:"vertex-dataset",vertexDatasetName:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))n={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;let i=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,o=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(o>0||i!==1)throw Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(i>0||o!==1)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function yA(e){if(typeof e!=="string")return e;let t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};else if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};else throw Error(`Unsupported destination: ${t}`)}function Im(e){if(typeof e!=="object"||e===null)return{};let t=e,n=t.inlinedResponses;if(typeof n!=="object"||n===null)return e;let o=n.inlinedResponses;if(!Array.isArray(o)||o.length===0)return e;let s=!1;for(let c of o){if(typeof c!=="object"||c===null)continue;let f=c.response;if(typeof f!=="object"||f===null)continue;if(f.embedding!==void 0){s=!0;break}}if(s)t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses;return e}function Qn(e,t){let n=t;if(!e.isVertexAI())if(/batches\/[^/]+$/.test(n))return n.split("/").pop();else throw Error(`Invalid batch job name: ${n}.`);if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();else if(/^\d+$/.test(n))return n;else throw Error(`Invalid batch job name: ${n}.`)}function wm(e){let t=e;if(t==="BATCH_STATE_UNSPECIFIED")return"JOB_STATE_UNSPECIFIED";else if(t==="BATCH_STATE_PENDING")return"JOB_STATE_PENDING";else if(t==="BATCH_STATE_RUNNING")return"JOB_STATE_RUNNING";else if(t==="BATCH_STATE_SUCCEEDED")return"JOB_STATE_SUCCEEDED";else if(t==="BATCH_STATE_FAILED")return"JOB_STATE_FAILED";else if(t==="BATCH_STATE_CANCELLED")return"JOB_STATE_CANCELLED";else if(t==="BATCH_STATE_EXPIRED")return"JOB_STATE_EXPIRED";else return t}function EA(e){return e.includes("gemini")&&e!=="gemini-embedding-001"||e.includes("maas")}function vA(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function TA(e){let t={},n=l(e,["responsesFile"]);if(n!=null)u(t,["fileName"],n);let i=l(e,["inlinedResponses","inlinedResponses"]);if(i!=null){let s=i;if(Array.isArray(s))s=s.map((c)=>tC(c));u(t,["inlinedResponses"],s)}let o=l(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["inlinedEmbedContentResponses"],s)}return t}function AA(e){let t={},n=l(e,["predictionsFormat"]);if(n!=null)u(t,["format"],n);let i=l(e,["gcsDestination","outputUriPrefix"]);if(i!=null)u(t,["gcsUri"],i);let o=l(e,["bigqueryDestination","outputUri"]);if(o!=null)u(t,["bigqueryUri"],o);let s=l(e,["vertexMultimodalDatasetDestination"]);if(s!=null)u(t,["vertexDataset"],fC(s));return t}function CA(e){let t={},n=l(e,["format"]);if(n!=null)u(t,["predictionsFormat"],n);let i=l(e,["gcsUri"]);if(i!=null)u(t,["gcsDestination","outputUriPrefix"],i);let o=l(e,["bigqueryUri"]);if(o!=null)u(t,["bigqueryDestination","outputUri"],o);let s=l(e,["vertexDataset"]);if(s!=null)u(t,["vertexMultimodalDatasetDestination"],pC(s));if(l(e,["fileName"])!==void 0)throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedResponses"])!==void 0)throw Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedEmbedContentResponses"])!==void 0)throw Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Di(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata","displayName"]);if(i!=null)u(t,["displayName"],i);let o=l(e,["metadata","state"]);if(o!=null)u(t,["state"],wm(o));let s=l(e,["metadata","createTime"]);if(s!=null)u(t,["createTime"],s);let c=l(e,["metadata","endTime"]);if(c!=null)u(t,["endTime"],c);let d=l(e,["metadata","updateTime"]);if(d!=null)u(t,["updateTime"],d);let f=l(e,["metadata","model"]);if(f!=null)u(t,["model"],f);let h=l(e,["metadata","output"]);if(h!=null)u(t,["dest"],TA(Im(h)));return t}function ks(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["displayName"]);if(i!=null)u(t,["displayName"],i);let o=l(e,["state"]);if(o!=null)u(t,["state"],wm(o));let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["createTime"]);if(c!=null)u(t,["createTime"],c);let d=l(e,["startTime"]);if(d!=null)u(t,["startTime"],d);let f=l(e,["endTime"]);if(f!=null)u(t,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(t,["updateTime"],h);let m=l(e,["model"]);if(m!=null)u(t,["model"],m);let g=l(e,["inputConfig"]);if(g!=null)u(t,["src"],SA(g));let _=l(e,["outputConfig"]);if(_!=null)u(t,["dest"],AA(Im(_)));let E=l(e,["outputInfo"]);if(E!=null)u(t,["outputInfo"],E);let y=l(e,["completionStats"]);if(y!=null)u(t,["completionStats"],y);return t}function SA(e){let t={},n=l(e,["instancesFormat"]);if(n!=null)u(t,["format"],n);let i=l(e,["gcsSource","uris"]);if(i!=null)u(t,["gcsUri"],i);let o=l(e,["bigquerySource","inputUri"]);if(o!=null)u(t,["bigqueryUri"],o);let s=l(e,["vertexMultimodalDatasetSource","datasetName"]);if(s!=null)u(t,["vertexDatasetName"],s);return t}function IA(e,t){let n={};if(l(t,["format"])!==void 0)throw Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["bigqueryUri"])!==void 0)throw Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["vertexDatasetName"])!==void 0)throw Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(t,["fileName"]);if(i!=null)u(n,["fileName"],i);let o=l(t,["inlinedRequests"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>eC(e,c));u(n,["requests","requests"],s)}return n}function wA(e){let t={},n=l(e,["format"]);if(n!=null)u(t,["instancesFormat"],n);let i=l(e,["gcsUri"]);if(i!=null)u(t,["gcsSource","uris"],i);let o=l(e,["bigqueryUri"]);if(o!=null)u(t,["bigquerySource","inputUri"],o);let s=l(e,["vertexDatasetName"]);if(s!=null)u(t,["vertexMultimodalDatasetSource","datasetName"],s);if(l(e,["fileName"])!==void 0)throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["inlinedRequests"])!==void 0)throw Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function RA(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function PA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function NA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function xA(e){let t={},n=l(e,["content"]);if(n!=null)u(t,["content"],n);let i=l(e,["citationMetadata"]);if(i!=null)u(t,["citationMetadata"],kA(i));let o=l(e,["tokenCount"]);if(o!=null)u(t,["tokenCount"],o);let s=l(e,["finishReason"]);if(s!=null)u(t,["finishReason"],s);let c=l(e,["groundingMetadata"]);if(c!=null)u(t,["groundingMetadata"],c);let d=l(e,["avgLogprobs"]);if(d!=null)u(t,["avgLogprobs"],d);let f=l(e,["index"]);if(f!=null)u(t,["index"],f);let h=l(e,["logprobsResult"]);if(h!=null)u(t,["logprobsResult"],h);let m=l(e,["safetyRatings"]);if(m!=null){let _=m;if(Array.isArray(_))_=_.map((E)=>E);u(t,["safetyRatings"],_)}let g=l(e,["urlContextMetadata"]);if(g!=null)u(t,["urlContextMetadata"],g);return t}function kA(e){let t={},n=l(e,["citationSources"]);if(n!=null){let i=n;if(Array.isArray(i))i=i.map((o)=>o);u(t,["citations"],i)}return t}function Rm(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>lC(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function DA(e,t){let n={},i=l(e,["displayName"]);if(t!==void 0&&i!=null)u(t,["batch","displayName"],i);if(l(e,["dest"])!==void 0)throw Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["webhookConfig"]);if(t!==void 0&&o!=null)u(t,["batch","webhookConfig"],o);return n}function MA(e,t){let n={},i=l(e,["displayName"]);if(t!==void 0&&i!=null)u(t,["displayName"],i);let o=l(e,["dest"]);if(t!==void 0&&o!=null)u(t,["outputConfig"],CA(yA(o)));if(l(e,["webhookConfig"])!==void 0)throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function _h(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["_url","model"],de(e,i));let o=l(t,["src"]);if(o!=null)u(n,["batch","inputConfig"],IA(e,Sm(e,o)));let s=l(t,["config"]);if(s!=null)DA(s,n);return n}function UA(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["model"],de(e,i));let o=l(t,["src"]);if(o!=null)u(n,["inputConfig"],wA(Sm(e,o)));let s=l(t,["config"]);if(s!=null)MA(s,n);return n}function GA(e,t){let n={},i=l(e,["displayName"]);if(t!==void 0&&i!=null)u(t,["batch","displayName"],i);return n}function bA(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["_url","model"],de(e,i));let o=l(t,["src"]);if(o!=null)u(n,["batch","inputConfig"],BA(e,o));let s=l(t,["config"]);if(s!=null)GA(s,n);return n}function LA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function qA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function OA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["name"]);if(i!=null)u(t,["name"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);return t}function FA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["name"]);if(i!=null)u(t,["name"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);return t}function HA(e,t){let n={},i=l(t,["contents"]);if(i!=null){let s=Bs(e,i);if(Array.isArray(s))s=s.map((c)=>c);u(n,["requests[]","request","content"],s)}let o=l(t,["config"]);if(o!=null)u(n,["_self"],VA(o,n)),QT(n,{"requests[].*":"requests[].request.*"});return n}function VA(e,t){let n={},i=l(e,["taskType"]);if(t!==void 0&&i!=null)u(t,["requests[]","taskType"],i);let o=l(e,["title"]);if(t!==void 0&&o!=null)u(t,["requests[]","title"],o);let s=l(e,["outputDimensionality"]);if(t!==void 0&&s!=null)u(t,["requests[]","outputDimensionality"],s);if(l(e,["mimeType"])!==void 0)throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["autoTruncate"])!==void 0)throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["documentOcr"])!==void 0)throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["audioTrackExtraction"])!==void 0)throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function BA(e,t){let n={},i=l(t,["fileName"]);if(i!=null)u(n,["file_name"],i);let o=l(t,["inlinedRequests"]);if(o!=null)u(n,["requests"],HA(e,o));return n}function $A(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function JA(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let i=l(e,["id"]);if(i!=null)u(t,["id"],i);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function XA(e){let t={},n=l(e,["allowedFunctionNames"]);if(n!=null)u(t,["allowedFunctionNames"],n);let i=l(e,["mode"]);if(i!=null)u(t,["mode"],i);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function KA(e,t,n){let i={},o=l(t,["serviceTier"]);if(n!==void 0&&o!=null)u(n,["serviceTier"],o);let s=l(t,["systemInstruction"]);if(n!==void 0&&s!=null)u(n,["systemInstruction"],Rm(qe(s)));let c=l(t,["temperature"]);if(c!=null)u(i,["temperature"],c);let d=l(t,["topP"]);if(d!=null)u(i,["topP"],d);let f=l(t,["topK"]);if(f!=null)u(i,["topK"],f);let h=l(t,["candidateCount"]);if(h!=null)u(i,["candidateCount"],h);let m=l(t,["maxOutputTokens"]);if(m!=null)u(i,["maxOutputTokens"],m);let g=l(t,["stopSequences"]);if(g!=null)u(i,["stopSequences"],g);let _=l(t,["responseLogprobs"]);if(_!=null)u(i,["responseLogprobs"],_);let E=l(t,["logprobs"]);if(E!=null)u(i,["logprobs"],E);let y=l(t,["presencePenalty"]);if(y!=null)u(i,["presencePenalty"],y);let v=l(t,["frequencyPenalty"]);if(v!=null)u(i,["frequencyPenalty"],v);let C=l(t,["seed"]);if(C!=null)u(i,["seed"],C);let T=l(t,["responseMimeType"]);if(T!=null)u(i,["responseMimeType"],T);let I=l(t,["responseSchema"]);if(I!=null)u(i,["responseSchema"],$s(I));let P=l(t,["responseJsonSchema"]);if(P!=null)u(i,["responseJsonSchema"],Yn(P));if(l(t,["routingConfig"])!==void 0)throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["modelSelectionConfig"])!==void 0)throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let N=l(t,["safetySettings"]);if(n!==void 0&&N!=null){let oe=N;if(Array.isArray(oe))oe=oe.map((se)=>uC(se));u(n,["safetySettings"],oe)}let D=l(t,["tools"]);if(n!==void 0&&D!=null){let oe=zn(D);if(Array.isArray(oe))oe=oe.map((se)=>dC(Wn(se)));u(n,["tools"],oe)}let q=l(t,["toolConfig"]);if(n!==void 0&&q!=null)u(n,["toolConfig"],cC(q));if(l(t,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let V=l(t,["cachedContent"]);if(n!==void 0&&V!=null)u(n,["cachedContent"],Ot(e,V));let J=l(t,["responseModalities"]);if(J!=null)u(i,["responseModalities"],J);let L=l(t,["mediaResolution"]);if(L!=null)u(i,["mediaResolution"],L);let Y=l(t,["speechConfig"]);if(Y!=null)u(i,["speechConfig"],Js(Y));if(l(t,["audioTimestamp"])!==void 0)throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Z=l(t,["thinkingConfig"]);if(Z!=null)u(i,["thinkingConfig"],Z);let ne=l(t,["audioTranscriptionConfig"]);if(ne!=null)u(i,["audioTranscriptionConfig"],ne);let W=l(t,["imageConfig"]);if(W!=null)u(i,["imageConfig"],jA(W));let H=l(t,["enableEnhancedCivicAnswers"]);if(H!=null)u(i,["enableEnhancedCivicAnswers"],H);if(l(t,["modelArmorConfig"])!==void 0)throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function YA(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["candidates"]);if(i!=null){let h=i;if(Array.isArray(h))h=h.map((m)=>xA(m));u(t,["candidates"],h)}let o=l(e,["modelVersion"]);if(o!=null)u(t,["modelVersion"],o);let s=l(e,["promptFeedback"]);if(s!=null)u(t,["promptFeedback"],s);let c=l(e,["responseId"]);if(c!=null)u(t,["responseId"],c);let d=l(e,["usageMetadata"]);if(d!=null)u(t,["usageMetadata"],d);let f=l(e,["modelStatus"]);if(f!=null)u(t,["modelStatus"],f);return t}function WA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function zA(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Qn(e,i));return n}function QA(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],vA(n));let i=l(e,["enableWidget"]);if(i!=null)u(t,["enableWidget"],i);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function ZA(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let i=l(e,["timeRangeFilter"]);if(i!=null)u(t,["timeRangeFilter"],i);return t}function jA(e){let t={},n=l(e,["aspectRatio"]);if(n!=null)u(t,["aspectRatio"],n);let i=l(e,["imageSize"]);if(i!=null)u(t,["imageSize"],i);if(l(e,["personGeneration"])!==void 0)throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputMimeType"])!==void 0)throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputCompressionQuality"])!==void 0)throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["imageOutputOptions"])!==void 0)throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["prominentPeople"])!==void 0)throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function eC(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["request","model"],de(e,i));let o=l(t,["contents"]);if(o!=null){let d=We(o);if(Array.isArray(d))d=d.map((f)=>Rm(f));u(n,["request","contents"],d)}let s=l(t,["metadata"]);if(s!=null)u(n,["metadata"],s);let c=l(t,["config"]);if(c!=null)u(n,["request","generationConfig"],KA(e,c,l(n,["request"],{})));return n}function tC(e){let t={},n=l(e,["response"]);if(n!=null)u(t,["response"],YA(n));let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["error"]);if(o!=null)u(t,["error"],o);return t}function nC(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);if(l(e,["filter"])!==void 0)throw Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function rC(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);let s=l(e,["filter"]);if(t!==void 0&&s!=null)u(t,["_query","filter"],s);return n}function iC(e){let t={},n=l(e,["config"]);if(n!=null)nC(n,t);return t}function oC(e){let t={},n=l(e,["config"]);if(n!=null)rC(n,t);return t}function sC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["operations"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>Di(c));u(t,["batchJobs"],s)}return t}function aC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["batchPredictionJobs"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>ks(c));u(t,["batchJobs"],s)}return t}function lC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let i=l(e,["toolCall"]);if(i!=null)u(t,["toolCall"],i);let o=l(e,["toolResponse"]);if(o!=null)u(t,["toolResponse"],o);let s=l(e,["audioTranscription"]);if(s!=null)u(t,["audioTranscription"],s);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],$A(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],JA(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],RA(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let E=l(e,["thought"]);if(E!=null)u(t,["thought"],E);let y=l(e,["thoughtSignature"]);if(y!=null)u(t,["thoughtSignature"],y);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);let C=l(e,["partMetadata"]);if(C!=null)u(t,["partMetadata"],C);let T=l(e,["mediaProcessing"]);if(T!=null)u(t,["mediaProcessing"],T);return t}function uC(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["threshold"]);if(i!=null)u(t,["threshold"],i);return t}function cC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],XA(n));let i=l(e,["retrievalConfig"]);if(i!=null)u(t,["retrievalConfig"],i);let o=l(e,["includeServerSideToolInvocations"]);if(o!=null)u(t,["includeServerSideToolInvocations"],o);return t}function dC(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],QA(n));let i=l(e,["mcpServers"]);if(i!=null){let g=i;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let o=l(e,["codeExecution"]);if(o!=null)u(t,["codeExecution"],o);let s=l(e,["computerUse"]);if(s!=null)u(t,["computerUse"],s);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],ZA(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function fC(e){let t={},n=l(e,["bigqueryDestination","outputUri"]);if(n!=null)u(t,["bigqueryDestination"],n);let i=l(e,["displayName"]);if(i!=null)u(t,["displayName"],i);return t}function pC(e){let t={},n=l(e,["bigqueryDestination"]);if(n!=null)u(t,["bigqueryDestination","outputUri"],n);let i=l(e,["displayName"]);if(i!=null)u(t,["displayName"],i);return t}var qt;(function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"})(qt||(qt={}));class pn{constructor(e,t,n,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,i)}init(e,t,n){var i,o;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t===null||t===void 0?void 0:t.sdkHttpResponse,this.idxInternal=0;let s={config:{}};if(!n||Object.keys(n).length===0)s={config:{}};else if(typeof n==="object")s=Object.assign({},n);else s=n;if(s.config)s.config.pageToken=t.nextPageToken;this.paramsInternal=s,this.pageInternalSize=(o=(i=s.config)===null||i===void 0?void 0:i.pageSize)!==null&&o!==void 0?o: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 Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;if(((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0)return!0;return!1}}class Pm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_BATCH_JOBS,(n)=>this.listInternal(n),await this.listInternal(t),t),this.create=async(t)=>{if(this.apiClient.isVertexAI())t.config=this.formatDestination(t.src,t.config);return this.createInternal(t)},this.createEmbeddings=async(t)=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){let t=_h(this.apiClient,e),n=t._url,i=z("{model}:batchGenerateContent",n),c=t.batch.inputConfig.requests,d=c.requests,f=[];for(let h of d){let m=Object.assign({},h);if(m.systemInstruction){let g=m.systemInstruction;delete m.systemInstruction;let _=m.request;_.systemInstruction=g,m.request=_}f.push(m)}return c.requests=f,delete t.config,delete t._url,delete t._query,{path:i,body:t}}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];return}getBigqueryUri(e){if(typeof e==="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri;return}formatDestination(e,t){let n=t?Object.assign({},t):{},i=Date.now().toString();if(!n.displayName)n.displayName=`genaiBatchJob_${i}`;if(n.dest===void 0){let o=this.getGcsUri(e),s=this.getBigqueryUri(e);if(o)if(o.endsWith(".jsonl"))n.dest=`${o.slice(0,-6)}/dest`;else n.dest=`${o}_dest_${i}`;else if(s)n.dest=`${s}_dest_${i}`;else throw Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return n}async createInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=UA(this.apiClient,e);return c=z("batchPredictionJobs",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>ks(h))}else{let f=_h(this.apiClient,e);return c=z("{model}:batchGenerateContent",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>Di(h))}}async createEmbeddingsInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=bA(this.apiClient,e);return o=z("{model}:asyncBatchEmbedContent",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>Di(d))}}async get(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=zA(this.apiClient,e);return c=z("batchPredictionJobs/{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>ks(h))}else{let f=WA(this.apiClient,e);return c=z("batches/{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>Di(h))}}async cancel(e){var t,n,i,o;let s="",c={};if(this.apiClient.isVertexAI()){let d=NA(this.apiClient,e);s=z("batchPredictionJobs/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}else{let d=PA(this.apiClient,e);s=z("batches/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=oC(e);return c=z("batchPredictionJobs",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=aC(h),g=new Ns;return Object.assign(g,m),g})}else{let f=iC(e);return c=z("batches",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=sC(h),g=new Ns;return Object.assign(g,m),g})}}async delete(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=qA(this.apiClient,e);return c=z("batchPredictionJobs/{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>FA(h))}else{let f=LA(this.apiClient,e);return c=z("batches/{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>OA(h))}}}function hC(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function mC(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function gC(e){let t={},n=l(e,["enablePromptInjectionDetection"]);if(n!=null)u(t,["enablePromptInjectionDetection"],n);let i=l(e,["environment"]);if(i!=null)u(t,["environment"],i);let o=l(e,["excludedPredefinedFunctions"]);if(o!=null)u(t,["excludedPredefinedFunctions"],o);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function yh(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>OC(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function Eh(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>FC(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function _C(e,t){let n={},i=l(e,["ttl"]);if(t!==void 0&&i!=null)u(t,["ttl"],i);let o=l(e,["expireTime"]);if(t!==void 0&&o!=null)u(t,["expireTime"],o);let s=l(e,["displayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);let c=l(e,["contents"]);if(t!==void 0&&c!=null){let m=We(c);if(Array.isArray(m))m=m.map((g)=>yh(g));u(t,["contents"],m)}let d=l(e,["systemInstruction"]);if(t!==void 0&&d!=null)u(t,["systemInstruction"],yh(qe(d)));let f=l(e,["tools"]);if(t!==void 0&&f!=null){let m=f;if(Array.isArray(m))m=m.map((g)=>BC(g));u(t,["tools"],m)}let h=l(e,["toolConfig"]);if(t!==void 0&&h!=null)u(t,["toolConfig"],HC(h));if(l(e,["kmsKeyName"])!==void 0)throw Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function yC(e,t){let n={},i=l(e,["ttl"]);if(t!==void 0&&i!=null)u(t,["ttl"],i);let o=l(e,["expireTime"]);if(t!==void 0&&o!=null)u(t,["expireTime"],o);let s=l(e,["displayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);let c=l(e,["contents"]);if(t!==void 0&&c!=null){let g=We(c);if(Array.isArray(g))g=g.map((_)=>Eh(_));u(t,["contents"],g)}let d=l(e,["systemInstruction"]);if(t!==void 0&&d!=null)u(t,["systemInstruction"],Eh(qe(d)));let f=l(e,["tools"]);if(t!==void 0&&f!=null){let g=f;if(Array.isArray(g))g=g.map((_)=>$C(_));u(t,["tools"],g)}let h=l(e,["toolConfig"]);if(t!==void 0&&h!=null)u(t,["toolConfig"],VC(h));let m=l(e,["kmsKeyName"]);if(t!==void 0&&m!=null)u(t,["encryption_spec","kmsKeyName"],m);return n}function EC(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["model"],hm(e,i));let o=l(t,["config"]);if(o!=null)_C(o,n);return n}function vC(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["model"],hm(e,i));let o=l(t,["config"]);if(o!=null)yC(o,n);return n}function TC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));return n}function AC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));return n}function CC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function SC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function IC(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function wC(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let i=l(e,["id"]);if(i!=null)u(t,["id"],i);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function RC(e){let t={},n=l(e,["allowedFunctionNames"]);if(n!=null)u(t,["allowedFunctionNames"],n);let i=l(e,["mode"]);if(i!=null)u(t,["mode"],i);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function PC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));return n}function NC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));return n}function xC(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],hC(n));let i=l(e,["enableWidget"]);if(i!=null)u(t,["enableWidget"],i);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function kC(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let i=l(e,["timeRangeFilter"]);if(i!=null)u(t,["timeRangeFilter"],i);return t}function DC(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);return n}function MC(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);return n}function UC(e){let t={},n=l(e,["config"]);if(n!=null)DC(n,t);return t}function GC(e){let t={},n=l(e,["config"]);if(n!=null)MC(n,t);return t}function bC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["cachedContents"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["cachedContents"],s)}return t}function LC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["cachedContents"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["cachedContents"],s)}return t}function qC(e){let t={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function OC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let i=l(e,["toolCall"]);if(i!=null)u(t,["toolCall"],i);let o=l(e,["toolResponse"]);if(o!=null)u(t,["toolResponse"],o);let s=l(e,["audioTranscription"]);if(s!=null)u(t,["audioTranscription"],s);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],IC(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],wC(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],mC(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let E=l(e,["thought"]);if(E!=null)u(t,["thought"],E);let y=l(e,["thoughtSignature"]);if(y!=null)u(t,["thoughtSignature"],y);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);let C=l(e,["partMetadata"]);if(C!=null)u(t,["partMetadata"],C);let T=l(e,["mediaProcessing"]);if(T!=null)u(t,["mediaProcessing"],T);return t}function FC(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=l(e,["audioTranscription"]);if(i!=null)u(t,["audioTranscription"],i);let o=l(e,["codeExecutionResult"]);if(o!=null)u(t,["codeExecutionResult"],o);let s=l(e,["executableCode"]);if(s!=null)u(t,["executableCode"],s);let c=l(e,["fileData"]);if(c!=null)u(t,["fileData"],c);let d=l(e,["functionCall"]);if(d!=null)u(t,["functionCall"],d);let f=l(e,["functionResponse"]);if(f!=null)u(t,["functionResponse"],f);let h=l(e,["inlineData"]);if(h!=null)u(t,["inlineData"],h);let m=l(e,["text"]);if(m!=null)u(t,["text"],m);let g=l(e,["thought"]);if(g!=null)u(t,["thought"],g);let _=l(e,["thoughtSignature"]);if(_!=null)u(t,["thoughtSignature"],_);let E=l(e,["videoMetadata"]);if(E!=null)u(t,["videoMetadata"],E);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let y=l(e,["mediaProcessing"]);if(y!=null)u(t,["mediaProcessing"],y);return t}function HC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],RC(n));let i=l(e,["retrievalConfig"]);if(i!=null)u(t,["retrievalConfig"],i);let o=l(e,["includeServerSideToolInvocations"]);if(o!=null)u(t,["includeServerSideToolInvocations"],o);return t}function VC(e){let t={},n=l(e,["functionCallingConfig"]);if(n!=null)u(t,["functionCallingConfig"],n);let i=l(e,["retrievalConfig"]);if(i!=null)u(t,["retrievalConfig"],i);if(l(e,["includeServerSideToolInvocations"])!==void 0)throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function BC(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],xC(n));let i=l(e,["mcpServers"]);if(i!=null){let g=i;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let o=l(e,["codeExecution"]);if(o!=null)u(t,["codeExecution"],o);let s=l(e,["computerUse"]);if(s!=null)u(t,["computerUse"],s);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],kC(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function $C(e){let t={},n=l(e,["retrieval"]);if(n!=null)u(t,["retrieval"],n);let i=l(e,["googleMaps"]);if(i!=null)u(t,["googleMaps"],i);let o=l(e,["mcpServers"]);if(o!=null){let y=o;if(Array.isArray(y))y=y.map((v)=>qC(v));u(t,["mcpServers"],y)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let c=l(e,["computerUse"]);if(c!=null)u(t,["computerUse"],gC(c));let d=l(e,["enterpriseWebSearch"]);if(d!=null)u(t,["enterpriseWebSearch"],d);let f=l(e,["exaAiSearch"]);if(f!=null)u(t,["exaAiSearch"],f);let h=l(e,["functionDeclarations"]);if(h!=null){let y=h;if(Array.isArray(y))y=y.map((v)=>v);u(t,["functionDeclarations"],y)}let m=l(e,["googleSearch"]);if(m!=null)u(t,["googleSearch"],m);let g=l(e,["googleSearchRetrieval"]);if(g!=null)u(t,["googleSearchRetrieval"],g);let _=l(e,["parallelAiSearch"]);if(_!=null)u(t,["parallelAiSearch"],_);let E=l(e,["urlContext"]);if(E!=null)u(t,["urlContext"],E);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function JC(e,t){let n={},i=l(e,["ttl"]);if(t!==void 0&&i!=null)u(t,["ttl"],i);let o=l(e,["expireTime"]);if(t!==void 0&&o!=null)u(t,["expireTime"],o);return n}function XC(e,t){let n={},i=l(e,["ttl"]);if(t!==void 0&&i!=null)u(t,["ttl"],i);let o=l(e,["expireTime"]);if(t!==void 0&&o!=null)u(t,["expireTime"],o);return n}function KC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));let o=l(t,["config"]);if(o!=null)JC(o,n);return n}function YC(e,t){let n={},i=l(t,["name"]);if(i!=null)u(n,["_url","name"],Ot(e,i));let o=l(t,["config"]);if(o!=null)XC(o,n);return n}class Nm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_CACHED_CONTENTS,(n)=>this.listInternal(n),await this.listInternal(t),t)}async create(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=vC(this.apiClient,e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}else{let f=EC(this.apiClient,e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}}async get(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=NC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}else{let f=PC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}}async delete(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=AC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=SC(h),g=new Rs;return Object.assign(g,m),g})}else{let f=TC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=CC(h),g=new Rs;return Object.assign(g,m),g})}}async update(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=YC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}else{let f=KC(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>h)}}async listInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=GC(e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=LC(h),g=new Ps;return Object.assign(g,m),g})}else{let f=UC(e);return c=z("cachedContents",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=bC(h),g=new Ps;return Object.assign(g,m),g})}}}function Ve(e,t){var n={};for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0)n[i]=e[i];if(e!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var o=0,i=Object.getOwnPropertySymbols(e);o<i.length;o++)if(t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o]))n[i[o]]=e[i[o]]}return n}function vh(e){var t=typeof Symbol==="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&i>=e.length)e=void 0;return{value:e&&e[i++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pe(e){return this instanceof Pe?(this.v=e,this):new Pe(e)}function Xn(e,t,n){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),o,s=[];return o=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),d("next"),d("throw"),d("return",c),o[Symbol.asyncIterator]=function(){return this},o;function c(E){return function(y){return Promise.resolve(y).then(E,g)}}function d(E,y){if(i[E]){if(o[E]=function(v){return new Promise(function(C,T){s.push([E,v,C,T])>1||f(E,v)})},y)o[E]=y(o[E])}}function f(E,y){try{h(i[E](y))}catch(v){_(s[0][3],v)}}function h(E){E.value instanceof Pe?Promise.resolve(E.value.v).then(m,g):_(s[0][2],E)}function m(E){f("next",E)}function g(E){f("throw",E)}function _(E,y){if(E(y),s.shift(),s.length)f(s[0][0],s[0][1])}}function mr(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof vh==="function"?vh(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(c){return new Promise(function(d,f){c=e[s](c),o(d,f,c.done,c.value)})}}function o(s,c,d,f){Promise.resolve(f).then(function(h){s({value:h,done:d})},c)}}function WC(e){var t;if(e.candidates==null||e.candidates.length===0)return!1;let n=(t=e.candidates[0])===null||t===void 0?void 0:t.content;if(n===void 0)return!1;return xm(n)}function xm(e){if(e.parts===void 0||e.parts.length===0)return!1;for(let t of e.parts)if(t===void 0||Object.keys(t).length===0)return!1;return!0}function zC(e){if(e.length===0)return;for(let t of e)if(t.role!=="user"&&t.role!=="model")throw Error(`Role must be user or model, but got ${t.role}.`)}function Th(e){if(e===void 0||e.length===0)return[];let t=[],n=e.length,i=0;while(i<n)if(e[i].role==="user")t.push(e[i]),i++;else{let o=[],s=!0;while(i<n&&e[i].role==="model"){if(o.push(e[i]),s&&!xm(e[i]))s=!1;i++}if(s)t.push(...o);else t.pop()}return t}class km{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new Dm(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class Dm{constructor(e,t,n,i={},o=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=i,this.history=o,this.sendPromise=Promise.resolve(),zC(o)}async sendMessage(e){var t;await this.sendPromise;let n=qe(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(n),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var o,s,c;let d=await i,f=(s=(o=d.candidates)===null||o===void 0?void 0:o[0])===null||s===void 0?void 0:s.content,h=d.automaticFunctionCallingHistory,m=this.getHistory(!0).length,g=[];if(h!=null)g=(c=h.slice(m))!==null&&c!==void 0?c:[];let _=f?[f]:[];this.recordHistory(n,_,g);return})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var t;await this.sendPromise;let n=qe(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(n),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=i.then(()=>{return}).catch(()=>{return});let o=await i;return this.processStreamResponse(o,n)}getHistory(e=!1){let t=e?Th(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return Xn(this,arguments,function*(){var i,o,s,c,d,f;let h=[];try{for(var m=!0,g=mr(e),_;_=yield Pe(g.next()),i=_.done,!i;m=!0){c=_.value,m=!1;let E=c;if(WC(E)){let y=(f=(d=E.candidates)===null||d===void 0?void 0:d[0])===null||f===void 0?void 0:f.content;if(y!==void 0)h.push(y)}yield yield Pe(E)}}catch(E){o={error:E}}finally{try{if(!m&&!i&&(s=g.return))yield Pe(s.call(g))}finally{if(o)throw o.error}}this.recordHistory(t,h)})}recordHistory(e,t,n){let i=[];if(t.length>0&&t.every((o)=>o.role!==void 0))i=t;else i.push({role:"model",parts:[]});if(n&&n.length>0)this.history.push(...Th(n));else this.history.push(e);this.history.push(...i)}}class Vi extends Error{constructor(e){super(e.message);this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,Vi.prototype)}}function QC(e){let t={},n=l(e,["file"]);if(n!=null)u(t,["file"],n);return t}function ZC(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function jC(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","file"],Ks(n));return t}function e0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}function t0(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","file"],Ks(n));return t}function n0(e){let t={},n=l(e,["uris"]);if(n!=null)u(t,["uris"],n);return t}function r0(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);return n}function i0(e){let t={},n=l(e,["config"]);if(n!=null)r0(n,t);return t}function o0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["files"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["files"],s)}return t}function s0(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["files"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>s);u(t,["files"],o)}return t}var a0=class extends xt{constructor(t){super();this.apiClient=t,this.list=async(n={})=>new pn(qt.PAGED_ITEM_FILES,(i)=>this.listInternal(i),await this.listInternal(n),n)}async upload(t){if(this.apiClient.isVertexAI())throw 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(t.file,t.config).then((n)=>n)}async download(t){await this.apiClient.downloadFile(t)}async registerFiles(t){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(t){return this.registerFilesInternal(t)}async listInternal(t){var n,i;let o,s="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=i0(t);return s=z("files",d._url),c=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal}).then((f)=>f.json().then((h)=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),o.then((f)=>{let h=o0(f),m=new lm;return Object.assign(m,h),m})}}async createInternal(t){var n,i;let o,s="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=QC(t);return s=z("upload/v1beta/files",d._url),c=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal}).then((f)=>f.json()),o.then((f)=>{let h=ZC(f),m=new um;return Object.assign(m,h),m})}}async get(t){var n,i;let o,s="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=t0(t);return s=z("files/{file}",d._url),c=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal}).then((f)=>f.json()),o.then((f)=>f)}}async delete(t){var n,i;let o,s="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=jC(t);return s=z("files/{file}",d._url),c=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal}).then((f)=>f.json().then((h)=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),o.then((f)=>{let h=e0(f),m=new cm;return Object.assign(m,h),m})}}async registerFilesInternal(t){var n,i;let o,s="",c={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let d=n0(t);return s=z("files:register",d._url),c=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal}).then((f)=>f.json()),o.then((f)=>{let h=s0(f),m=new dm;return Object.assign(m,h),m})}}};function l0(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Mi(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function u0(e){let t={},n=l(e,["enablePromptInjectionDetection"]);if(n!=null)u(t,["enablePromptInjectionDetection"],n);let i=l(e,["environment"]);if(i!=null)u(t,["environment"],i);let o=l(e,["excludedPredefinedFunctions"]);if(o!=null)u(t,["excludedPredefinedFunctions"],o);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function c0(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>P0(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function d0(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>N0(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function f0(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function p0(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let i=l(e,["id"]);if(i!=null)u(t,["id"],i);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function h0(e){let t={},n=l(e,["modelSelectionConfig"]);if(n!=null)u(t,["modelConfig"],n);let i=l(e,["responseJsonSchema"]);if(i!=null)u(t,["responseJsonSchema"],Yn(i));let o=l(e,["audioTranscriptionConfig"]);if(o!=null)u(t,["audioTranscriptionConfig"],o);let s=l(e,["audioTimestamp"]);if(s!=null)u(t,["audioTimestamp"],s);let c=l(e,["candidateCount"]);if(c!=null)u(t,["candidateCount"],c);let d=l(e,["enableAffectiveDialog"]);if(d!=null)u(t,["enableAffectiveDialog"],d);let f=l(e,["frequencyPenalty"]);if(f!=null)u(t,["frequencyPenalty"],f);let h=l(e,["logprobs"]);if(h!=null)u(t,["logprobs"],h);let m=l(e,["maxOutputTokens"]);if(m!=null)u(t,["maxOutputTokens"],m);let g=l(e,["mediaResolution"]);if(g!=null)u(t,["mediaResolution"],g);let _=l(e,["presencePenalty"]);if(_!=null)u(t,["presencePenalty"],_);let E=l(e,["responseFormat"]);if(E!=null){let Y=E;if(Array.isArray(Y))Y=Y.map((Z)=>Z);u(t,["responseFormat"],Y)}let y=l(e,["responseLogprobs"]);if(y!=null)u(t,["responseLogprobs"],y);let v=l(e,["responseMimeType"]);if(v!=null)u(t,["responseMimeType"],v);let C=l(e,["responseModalities"]);if(C!=null)u(t,["responseModalities"],C);let T=l(e,["responseSchema"]);if(T!=null)u(t,["responseSchema"],T);let I=l(e,["routingConfig"]);if(I!=null)u(t,["routingConfig"],I);let P=l(e,["seed"]);if(P!=null)u(t,["seed"],P);let N=l(e,["speechConfig"]);if(N!=null)u(t,["speechConfig"],Mm(N));let D=l(e,["stopSequences"]);if(D!=null)u(t,["stopSequences"],D);let q=l(e,["temperature"]);if(q!=null)u(t,["temperature"],q);let V=l(e,["thinkingConfig"]);if(V!=null)u(t,["thinkingConfig"],V);let J=l(e,["topK"]);if(J!=null)u(t,["topK"],J);let L=l(e,["topP"]);if(L!=null)u(t,["topP"],L);if(l(e,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["translationConfig"])!==void 0)throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function m0(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],l0(n));let i=l(e,["enableWidget"]);if(i!=null)u(t,["enableWidget"],i);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function g0(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let i=l(e,["timeRangeFilter"]);if(i!=null)u(t,["timeRangeFilter"],i);return t}function _0(e,t){let n={},i=l(e,["generationConfig"]);if(t!==void 0&&i!=null)u(t,["setup","generationConfig"],i);let o=l(e,["responseModalities"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig","responseModalities"],o);let s=l(e,["temperature"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","temperature"],s);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Xs(g));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let E=l(e,["enableAffectiveDialog"]);if(t!==void 0&&E!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],E);let y=l(e,["systemInstruction"]);if(t!==void 0&&y!=null)u(t,["setup","systemInstruction"],c0(qe(y)));let v=l(e,["tools"]);if(t!==void 0&&v!=null){let L=zn(v);if(Array.isArray(L))L=L.map((Y)=>U0(Wn(Y)));u(t,["setup","tools"],L)}let C=l(e,["sessionResumption"]);if(t!==void 0&&C!=null)u(t,["setup","sessionResumption"],D0(C));let T=l(e,["inputAudioTranscription"]);if(t!==void 0&&T!=null)u(t,["setup","inputAudioTranscription"],T);let I=l(e,["outputAudioTranscription"]);if(t!==void 0&&I!=null)u(t,["setup","outputAudioTranscription"],I);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);if(l(e,["explicitVadSignal"])!==void 0)throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let q=l(e,["avatarConfig"]);if(t!==void 0&&q!=null)u(t,["setup","avatarConfig"],q);let V=l(e,["safetySettings"]);if(t!==void 0&&V!=null){let L=V;if(Array.isArray(L))L=L.map((Y)=>k0(Y));u(t,["setup","safetySettings"],L)}let J=l(e,["translationConfig"]);if(t!==void 0&&J!=null)u(t,["setup","generationConfig","translationConfig"],J);return n}function y0(e,t){let n={},i=l(e,["generationConfig"]);if(t!==void 0&&i!=null)u(t,["setup","generationConfig"],h0(i));let o=l(e,["responseModalities"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig","responseModalities"],o);let s=l(e,["temperature"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","temperature"],s);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Mm(Xs(g)));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let E=l(e,["enableAffectiveDialog"]);if(t!==void 0&&E!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],E);let y=l(e,["systemInstruction"]);if(t!==void 0&&y!=null)u(t,["setup","systemInstruction"],d0(qe(y)));let v=l(e,["tools"]);if(t!==void 0&&v!=null){let Y=zn(v);if(Array.isArray(Y))Y=Y.map((Z)=>G0(Wn(Z)));u(t,["setup","tools"],Y)}let C=l(e,["sessionResumption"]);if(t!==void 0&&C!=null)u(t,["setup","sessionResumption"],C);let T=l(e,["inputAudioTranscription"]);if(t!==void 0&&T!=null)u(t,["setup","inputAudioTranscription"],T);let I=l(e,["outputAudioTranscription"]);if(t!==void 0&&I!=null)u(t,["setup","outputAudioTranscription"],I);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);let q=l(e,["explicitVadSignal"]);if(t!==void 0&&q!=null)u(t,["setup","explicitVadSignal"],q);let V=l(e,["avatarConfig"]);if(t!==void 0&&V!=null)u(t,["setup","avatarConfig"],V);let J=l(e,["safetySettings"]);if(t!==void 0&&J!=null){let Y=J;if(Array.isArray(Y))Y=Y.map((Z)=>Z);u(t,["setup","safetySettings"],Y)}let L=l(e,["translationConfig"]);if(t!==void 0&&L!=null)u(t,["setup","generationConfig","translationConfig"],L);return n}function E0(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["setup","model"],de(e,i));let o=l(t,["config"]);if(o!=null)u(n,["config"],_0(o,n));return n}function v0(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["setup","model"],de(e,i));let o=l(t,["config"]);if(o!=null)u(n,["config"],y0(o,n));return n}function T0(e){let t={},n=l(e,["musicGenerationConfig"]);if(n!=null)u(t,["musicGenerationConfig"],n);return t}function A0(e){let t={},n=l(e,["weightedPrompts"]);if(n!=null){let i=n;if(Array.isArray(i))i=i.map((o)=>o);u(t,["weightedPrompts"],i)}return t}function C0(e){let t={},n=l(e,["media"]);if(n!=null){let h=mm(n);if(Array.isArray(h))h=h.map((m)=>Mi(m));u(t,["mediaChunks"],h)}let i=l(e,["audio"]);if(i!=null)u(t,["audio"],Mi(_m(i)));let o=l(e,["audioStreamEnd"]);if(o!=null)u(t,["audioStreamEnd"],o);let s=l(e,["video"]);if(s!=null)u(t,["video"],Mi(gm(s)));let c=l(e,["text"]);if(c!=null)u(t,["text"],c);let d=l(e,["activityStart"]);if(d!=null)u(t,["activityStart"],d);let f=l(e,["activityEnd"]);if(f!=null)u(t,["activityEnd"],f);return t}function S0(e){let t={},n=l(e,["media"]);if(n!=null){let h=mm(n);if(Array.isArray(h))h=h.map((m)=>m);u(t,["mediaChunks"],h)}let i=l(e,["audio"]);if(i!=null)u(t,["audio"],_m(i));let o=l(e,["audioStreamEnd"]);if(o!=null)u(t,["audioStreamEnd"],o);let s=l(e,["video"]);if(s!=null)u(t,["video"],gm(s));let c=l(e,["text"]);if(c!=null)u(t,["text"],c);let d=l(e,["activityStart"]);if(d!=null)u(t,["activityStart"],d);let f=l(e,["activityEnd"]);if(f!=null)u(t,["activityEnd"],f);return t}function I0(e){let t={},n=l(e,["setupComplete"]);if(n!=null)u(t,["setupComplete"],n);let i=l(e,["serverContent"]);if(i!=null)u(t,["serverContent"],i);let o=l(e,["toolCall"]);if(o!=null)u(t,["toolCall"],o);let s=l(e,["toolCallCancellation"]);if(s!=null)u(t,["toolCallCancellation"],s);let c=l(e,["usageMetadata"]);if(c!=null)u(t,["usageMetadata"],b0(c));let d=l(e,["goAway"]);if(d!=null)u(t,["goAway"],d);let f=l(e,["sessionResumptionUpdate"]);if(f!=null)u(t,["sessionResumptionUpdate"],f);let h=l(e,["voiceActivityDetectionSignal"]);if(h!=null)u(t,["voiceActivityDetectionSignal"],h);let m=l(e,["voiceActivity"]);if(m!=null)u(t,["voiceActivity"],L0(m));return t}function w0(e){let t={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function R0(e){let t={},n=l(e,["speakerVoiceConfigs"]);if(n!=null){let i=n;if(Array.isArray(i))i=i.map((o)=>M0(o));u(t,["speakerVoiceConfigs"],i)}return t}function P0(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let i=l(e,["toolCall"]);if(i!=null)u(t,["toolCall"],i);let o=l(e,["toolResponse"]);if(o!=null)u(t,["toolResponse"],o);let s=l(e,["audioTranscription"]);if(s!=null)u(t,["audioTranscription"],s);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],f0(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],p0(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],Mi(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let E=l(e,["thought"]);if(E!=null)u(t,["thought"],E);let y=l(e,["thoughtSignature"]);if(y!=null)u(t,["thoughtSignature"],y);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);let C=l(e,["partMetadata"]);if(C!=null)u(t,["partMetadata"],C);let T=l(e,["mediaProcessing"]);if(T!=null)u(t,["mediaProcessing"],T);return t}function N0(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=l(e,["audioTranscription"]);if(i!=null)u(t,["audioTranscription"],i);let o=l(e,["codeExecutionResult"]);if(o!=null)u(t,["codeExecutionResult"],o);let s=l(e,["executableCode"]);if(s!=null)u(t,["executableCode"],s);let c=l(e,["fileData"]);if(c!=null)u(t,["fileData"],c);let d=l(e,["functionCall"]);if(d!=null)u(t,["functionCall"],d);let f=l(e,["functionResponse"]);if(f!=null)u(t,["functionResponse"],f);let h=l(e,["inlineData"]);if(h!=null)u(t,["inlineData"],h);let m=l(e,["text"]);if(m!=null)u(t,["text"],m);let g=l(e,["thought"]);if(g!=null)u(t,["thought"],g);let _=l(e,["thoughtSignature"]);if(_!=null)u(t,["thoughtSignature"],_);let E=l(e,["videoMetadata"]);if(E!=null)u(t,["videoMetadata"],E);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let y=l(e,["mediaProcessing"]);if(y!=null)u(t,["mediaProcessing"],y);return t}function x0(e){let t={},n=l(e,["mimeType"]);if(n!=null)u(t,["mimeType"],n);let i=l(e,["voiceSampleAudio"]);if(i!=null)u(t,["voiceSampleAudio"],i);if(l(e,["consentAudio"])!==void 0)throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["voiceConsentSignature"])!==void 0)throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function k0(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["threshold"]);if(i!=null)u(t,["threshold"],i);return t}function D0(e){let t={},n=l(e,["handle"]);if(n!=null)u(t,["handle"],n);if(l(e,["transparent"])!==void 0)throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function M0(e){let t={},n=l(e,["speaker"]);if(n!=null)u(t,["speaker"],n);let i=l(e,["voiceConfig"]);if(i!=null)u(t,["voiceConfig"],Um(i));return t}function Mm(e){let t={},n=l(e,["voiceConfig"]);if(n!=null)u(t,["voiceConfig"],Um(n));let i=l(e,["languageCode"]);if(i!=null)u(t,["languageCode"],i);let o=l(e,["multiSpeakerVoiceConfig"]);if(o!=null)u(t,["multiSpeakerVoiceConfig"],R0(o));return t}function U0(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],m0(n));let i=l(e,["mcpServers"]);if(i!=null){let g=i;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let o=l(e,["codeExecution"]);if(o!=null)u(t,["codeExecution"],o);let s=l(e,["computerUse"]);if(s!=null)u(t,["computerUse"],s);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],g0(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function G0(e){let t={},n=l(e,["retrieval"]);if(n!=null)u(t,["retrieval"],n);let i=l(e,["googleMaps"]);if(i!=null)u(t,["googleMaps"],i);let o=l(e,["mcpServers"]);if(o!=null){let y=o;if(Array.isArray(y))y=y.map((v)=>w0(v));u(t,["mcpServers"],y)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let c=l(e,["computerUse"]);if(c!=null)u(t,["computerUse"],u0(c));let d=l(e,["enterpriseWebSearch"]);if(d!=null)u(t,["enterpriseWebSearch"],d);let f=l(e,["exaAiSearch"]);if(f!=null)u(t,["exaAiSearch"],f);let h=l(e,["functionDeclarations"]);if(h!=null){let y=h;if(Array.isArray(y))y=y.map((v)=>v);u(t,["functionDeclarations"],y)}let m=l(e,["googleSearch"]);if(m!=null)u(t,["googleSearch"],m);let g=l(e,["googleSearchRetrieval"]);if(g!=null)u(t,["googleSearchRetrieval"],g);let _=l(e,["parallelAiSearch"]);if(_!=null)u(t,["parallelAiSearch"],_);let E=l(e,["urlContext"]);if(E!=null)u(t,["urlContext"],E);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function b0(e){let t={},n=l(e,["candidatesTokenCount"]);if(n!=null)u(t,["responseTokenCount"],n);let i=l(e,["candidatesTokensDetails"]);if(i!=null){let E=i;if(Array.isArray(E))E=E.map((y)=>y);u(t,["responseTokensDetails"],E)}let o=l(e,["cacheTokensDetails"]);if(o!=null){let E=o;if(Array.isArray(E))E=E.map((y)=>y);u(t,["cacheTokensDetails"],E)}let s=l(e,["cachedContentTokenCount"]);if(s!=null)u(t,["cachedContentTokenCount"],s);let c=l(e,["promptTokenCount"]);if(c!=null)u(t,["promptTokenCount"],c);let d=l(e,["promptTokensDetails"]);if(d!=null){let E=d;if(Array.isArray(E))E=E.map((y)=>y);u(t,["promptTokensDetails"],E)}let f=l(e,["thoughtsTokenCount"]);if(f!=null)u(t,["thoughtsTokenCount"],f);let h=l(e,["toolUsePromptTokenCount"]);if(h!=null)u(t,["toolUsePromptTokenCount"],h);let m=l(e,["toolUsePromptTokensDetails"]);if(m!=null){let E=m;if(Array.isArray(E))E=E.map((y)=>y);u(t,["toolUsePromptTokensDetails"],E)}let g=l(e,["totalTokenCount"]);if(g!=null)u(t,["totalTokenCount"],g);let _=l(e,["trafficType"]);if(_!=null)u(t,["trafficType"],_);return t}function L0(e){let t={},n=l(e,["type"]);if(n!=null)u(t,["voiceActivityType"],n);let i=l(e,["audioOffset"]);if(i!=null)u(t,["audioOffset"],i);return t}function Um(e){let t={},n=l(e,["replicatedVoiceConfig"]);if(n!=null)u(t,["replicatedVoiceConfig"],x0(n));let i=l(e,["prebuiltVoiceConfig"]);if(i!=null)u(t,["prebuiltVoiceConfig"],i);return t}function q0(e,t){let n={},i=l(e,["apiKey"]);if(i!=null)u(n,["apiKey"],i);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function O0(e,t){let n={},i=l(e,["data"]);if(i!=null)u(n,["data"],i);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["mimeType"]);if(o!=null)u(n,["mimeType"],o);return n}function F0(e,t){let n={},i=l(e,["content"]);if(i!=null)u(n,["content"],i);let o=l(e,["citationMetadata"]);if(o!=null)u(n,["citationMetadata"],H0(o));let s=l(e,["tokenCount"]);if(s!=null)u(n,["tokenCount"],s);let c=l(e,["finishReason"]);if(c!=null)u(n,["finishReason"],c);let d=l(e,["groundingMetadata"]);if(d!=null)u(n,["groundingMetadata"],d);let f=l(e,["avgLogprobs"]);if(f!=null)u(n,["avgLogprobs"],f);let h=l(e,["index"]);if(h!=null)u(n,["index"],h);let m=l(e,["logprobsResult"]);if(m!=null)u(n,["logprobsResult"],m);let g=l(e,["safetyRatings"]);if(g!=null){let E=g;if(Array.isArray(E))E=E.map((y)=>y);u(n,["safetyRatings"],E)}let _=l(e,["urlContextMetadata"]);if(_!=null)u(n,["urlContextMetadata"],_);return n}function H0(e,t){let n={},i=l(e,["citationSources"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>s);u(n,["citations"],o)}return n}function V0(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let c=We(s);if(Array.isArray(c))c=c.map((d)=>Zn(d));u(i,["contents"],c)}return i}function B0(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["tokensInfo"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(n,["tokensInfo"],s)}return n}function $0(e,t){let n={},i=l(e,["enablePromptInjectionDetection"]);if(i!=null)u(n,["enablePromptInjectionDetection"],i);let o=l(e,["environment"]);if(o!=null)u(n,["environment"],o);let s=l(e,["excludedPredefinedFunctions"]);if(s!=null)u(n,["excludedPredefinedFunctions"],s);if(l(e,["disabledSafetyPolicies"])!==void 0)throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function J0(e,t){let n={},i=l(e,["values"]);if(i!=null)u(n,["values"],i);let o=l(e,["statistics"]);if(o!=null)u(n,["statistics"],X0(o));return n}function X0(e,t){let n={},i=l(e,["truncated"]);if(i!=null)u(n,["truncated"],i);let o=l(e,["token_count"]);if(o!=null)u(n,["tokenCount"],o);let s=l(e,["tokensDetails"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>d);u(n,["tokensDetails"],c)}return n}function Sr(e,t){let n={},i=l(e,["parts"]);if(i!=null){let s=i;if(Array.isArray(s))s=s.map((c)=>QS(c));u(n,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(n,["role"],o);return n}function Zn(e,t){let n={},i=l(e,["parts"]);if(i!=null){let s=i;if(Array.isArray(s))s=s.map((c)=>ZS(c));u(n,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(n,["role"],o);return n}function K0(e,t){let n={},i=l(e,["controlType"]);if(i!=null)u(n,["controlType"],i);let o=l(e,["enableControlImageComputation"]);if(o!=null)u(n,["computeControl"],o);return n}function Y0(e,t){let n={};if(l(e,["systemInstruction"])!==void 0)throw Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tools"])!==void 0)throw Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["generationConfig"])!==void 0)throw Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function W0(e,t,n){let i={},o=l(e,["systemInstruction"]);if(t!==void 0&&o!=null)u(t,["systemInstruction"],Zn(qe(o)));let s=l(e,["tools"]);if(t!==void 0&&s!=null){let d=s;if(Array.isArray(d))d=d.map((f)=>qm(f));u(t,["tools"],d)}let c=l(e,["generationConfig"]);if(t!==void 0&&c!=null)u(t,["generationConfig"],GS(c));return i}function z0(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let d=We(s);if(Array.isArray(d))d=d.map((f)=>Sr(f));u(i,["contents"],d)}let c=l(t,["config"]);if(c!=null)Y0(c);return i}function Q0(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let d=We(s);if(Array.isArray(d))d=d.map((f)=>Zn(f));u(i,["contents"],d)}let c=l(t,["config"]);if(c!=null)W0(c,i);return i}function Z0(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["totalTokens"]);if(o!=null)u(n,["totalTokens"],o);let s=l(e,["cachedContentTokenCount"]);if(s!=null)u(n,["cachedContentTokenCount"],s);return n}function j0(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["totalTokens"]);if(o!=null)u(n,["totalTokens"],o);return n}function eS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","name"],de(e,o));return i}function tS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","name"],de(e,o));return i}function nS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);return n}function rS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);return n}function iS(e,t,n){let i={},o=l(e,["outputGcsUri"]);if(t!==void 0&&o!=null)u(t,["parameters","storageUri"],o);let s=l(e,["negativePrompt"]);if(t!==void 0&&s!=null)u(t,["parameters","negativePrompt"],s);let c=l(e,["numberOfImages"]);if(t!==void 0&&c!=null)u(t,["parameters","sampleCount"],c);let d=l(e,["aspectRatio"]);if(t!==void 0&&d!=null)u(t,["parameters","aspectRatio"],d);let f=l(e,["guidanceScale"]);if(t!==void 0&&f!=null)u(t,["parameters","guidanceScale"],f);let h=l(e,["seed"]);if(t!==void 0&&h!=null)u(t,["parameters","seed"],h);let m=l(e,["safetyFilterLevel"]);if(t!==void 0&&m!=null)u(t,["parameters","safetySetting"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["includeSafetyAttributes"]);if(t!==void 0&&_!=null)u(t,["parameters","includeSafetyAttributes"],_);let E=l(e,["includeRaiReason"]);if(t!==void 0&&E!=null)u(t,["parameters","includeRaiReason"],E);let y=l(e,["language"]);if(t!==void 0&&y!=null)u(t,["parameters","language"],y);let v=l(e,["outputMimeType"]);if(t!==void 0&&v!=null)u(t,["parameters","outputOptions","mimeType"],v);let C=l(e,["outputCompressionQuality"]);if(t!==void 0&&C!=null)u(t,["parameters","outputOptions","compressionQuality"],C);let T=l(e,["addWatermark"]);if(t!==void 0&&T!=null)u(t,["parameters","addWatermark"],T);let I=l(e,["labels"]);if(t!==void 0&&I!=null)u(t,["labels"],I);let P=l(e,["editMode"]);if(t!==void 0&&P!=null)u(t,["parameters","editMode"],P);let N=l(e,["baseSteps"]);if(t!==void 0&&N!=null)u(t,["parameters","editConfig","baseSteps"],N);return i}function oS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["prompt"]);if(s!=null)u(i,["instances[0]","prompt"],s);let c=l(t,["referenceImages"]);if(c!=null){let f=c;if(Array.isArray(f))f=f.map((h)=>iI(h));u(i,["instances[0]","referenceImages"],f)}let d=l(t,["config"]);if(d!=null)iS(d,i);return i}function sS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["predictions"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>Bi(c));u(n,["generatedImages"],s)}return n}function aS(e,t,n){let i={},o=l(e,["taskType"]);if(t!==void 0&&o!=null)u(t,["requests[]","taskType"],o);let s=l(e,["title"]);if(t!==void 0&&s!=null)u(t,["requests[]","title"],s);let c=l(e,["outputDimensionality"]);if(t!==void 0&&c!=null)u(t,["requests[]","outputDimensionality"],c);if(l(e,["mimeType"])!==void 0)throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["autoTruncate"])!==void 0)throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["documentOcr"])!==void 0)throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["audioTrackExtraction"])!==void 0)throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function lS(e,t,n){let i={},o=l(n,["embeddingApiType"]);if(o===void 0)o="PREDICT";if(o==="PREDICT"){let g=l(e,["taskType"]);if(t!==void 0&&g!=null)u(t,["instances[]","task_type"],g)}else if(o==="EMBED_CONTENT"){let g=l(e,["taskType"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","taskType"],g)}let s=l(n,["embeddingApiType"]);if(s===void 0)s="PREDICT";if(s==="PREDICT"){let g=l(e,["title"]);if(t!==void 0&&g!=null)u(t,["instances[]","title"],g)}else if(s==="EMBED_CONTENT"){let g=l(e,["title"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","title"],g)}let c=l(n,["embeddingApiType"]);if(c===void 0)c="PREDICT";if(c==="PREDICT"){let g=l(e,["outputDimensionality"]);if(t!==void 0&&g!=null)u(t,["parameters","outputDimensionality"],g)}else if(c==="EMBED_CONTENT"){let g=l(e,["outputDimensionality"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","outputDimensionality"],g)}let d=l(n,["embeddingApiType"]);if(d===void 0)d="PREDICT";if(d==="PREDICT"){let g=l(e,["mimeType"]);if(t!==void 0&&g!=null)u(t,["instances[]","mimeType"],g)}let f=l(n,["embeddingApiType"]);if(f===void 0)f="PREDICT";if(f==="PREDICT"){let g=l(e,["autoTruncate"]);if(t!==void 0&&g!=null)u(t,["parameters","autoTruncate"],g)}else if(f==="EMBED_CONTENT"){let g=l(e,["autoTruncate"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","autoTruncate"],g)}let h=l(n,["embeddingApiType"]);if(h===void 0)h="PREDICT";if(h==="EMBED_CONTENT"){let g=l(e,["documentOcr"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","documentOcr"],g)}let m=l(n,["embeddingApiType"]);if(m===void 0)m="PREDICT";if(m==="EMBED_CONTENT"){let g=l(e,["audioTrackExtraction"]);if(t!==void 0&&g!=null)u(t,["embedContentConfig","audioTrackExtraction"],g)}return i}function uS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let h=Bs(e,s);if(Array.isArray(h))h=h.map((m)=>m);u(i,["requests[]","content"],h)}let c=l(t,["content"]);if(c!=null)Sr(qe(c));let d=l(t,["config"]);if(d!=null)aS(d,i);let f=l(t,["model"]);if(f!==void 0)u(i,["requests[]","model"],de(e,f));return i}function cS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(n,["embeddingApiType"]);if(s===void 0)s="PREDICT";if(s==="PREDICT"){let f=l(t,["contents"]);if(f!=null){let h=Bs(e,f);if(Array.isArray(h))h=h.map((m)=>m);u(i,["instances[]","content"],h)}}let c=l(n,["embeddingApiType"]);if(c===void 0)c="PREDICT";if(c==="EMBED_CONTENT"){let f=l(t,["content"]);if(f!=null)u(i,["content"],Zn(qe(f)))}let d=l(t,["config"]);if(d!=null)lS(d,i,n);return i}function dS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["embeddings"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>d);u(n,["embeddings"],c)}let s=l(e,["metadata"]);if(s!=null)u(n,["metadata"],s);return n}function fS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["predictions[]","embeddings"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>J0(d));u(n,["embeddings"],c)}let s=l(e,["metadata"]);if(s!=null)u(n,["metadata"],s);if(t&&l(t,["embeddingApiType"])==="EMBED_CONTENT"){let c=l(e,["embedding"]),d=l(e,["usageMetadata"]),f=l(e,["truncated"]);if(c){let h={};if(d&&d.promptTokenCount)h.tokenCount=d.promptTokenCount;if(d&&d.promptTokensDetails)h.tokensDetails=d.promptTokensDetails;if(f)h.truncated=f;c.statistics=h,u(n,["embeddings"],[c])}}return n}function pS(e,t){let n={},i=l(e,["endpoint"]);if(i!=null)u(n,["name"],i);let o=l(e,["deployedModelId"]);if(o!=null)u(n,["deployedModelId"],o);return n}function hS(e,t){let n={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["fileUri"]);if(i!=null)u(n,["fileUri"],i);let o=l(e,["mimeType"]);if(o!=null)u(n,["mimeType"],o);return n}function mS(e,t){let n={},i=l(e,["args"]);if(i!=null)u(n,["args"],i);let o=l(e,["id"]);if(o!=null)u(n,["id"],o);let s=l(e,["name"]);if(s!=null)u(n,["name"],s);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function gS(e,t){let n={},i=l(e,["allowedFunctionNames"]);if(i!=null)u(n,["allowedFunctionNames"],i);let o=l(e,["mode"]);if(o!=null)u(n,["mode"],o);if(l(e,["streamFunctionCallArguments"])!==void 0)throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function _S(e,t,n,i){let o={},s=l(t,["serviceTier"]);if(n!==void 0&&s!=null)u(n,["serviceTier"],s);let c=l(t,["systemInstruction"]);if(n!==void 0&&c!=null)u(n,["systemInstruction"],Sr(qe(c)));let d=l(t,["temperature"]);if(d!=null)u(o,["temperature"],d);let f=l(t,["topP"]);if(f!=null)u(o,["topP"],f);let h=l(t,["topK"]);if(h!=null)u(o,["topK"],h);let m=l(t,["candidateCount"]);if(m!=null)u(o,["candidateCount"],m);let g=l(t,["maxOutputTokens"]);if(g!=null)u(o,["maxOutputTokens"],g);let _=l(t,["stopSequences"]);if(_!=null)u(o,["stopSequences"],_);let E=l(t,["responseLogprobs"]);if(E!=null)u(o,["responseLogprobs"],E);let y=l(t,["logprobs"]);if(y!=null)u(o,["logprobs"],y);let v=l(t,["presencePenalty"]);if(v!=null)u(o,["presencePenalty"],v);let C=l(t,["frequencyPenalty"]);if(C!=null)u(o,["frequencyPenalty"],C);let T=l(t,["seed"]);if(T!=null)u(o,["seed"],T);let I=l(t,["responseMimeType"]);if(I!=null)u(o,["responseMimeType"],I);let P=l(t,["responseSchema"]);if(P!=null)u(o,["responseSchema"],$s(P));let N=l(t,["responseJsonSchema"]);if(N!=null)u(o,["responseJsonSchema"],Yn(N));if(l(t,["routingConfig"])!==void 0)throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["modelSelectionConfig"])!==void 0)throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let D=l(t,["safetySettings"]);if(n!==void 0&&D!=null){let se=D;if(Array.isArray(se))se=se.map((Ne)=>sI(Ne));u(n,["safetySettings"],se)}let q=l(t,["tools"]);if(n!==void 0&&q!=null){let se=zn(q);if(Array.isArray(se))se=se.map((Ne)=>mI(Wn(Ne)));u(n,["tools"],se)}let V=l(t,["toolConfig"]);if(n!==void 0&&V!=null)u(n,["toolConfig"],pI(V));if(l(t,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let J=l(t,["cachedContent"]);if(n!==void 0&&J!=null)u(n,["cachedContent"],Ot(e,J));let L=l(t,["responseModalities"]);if(L!=null)u(o,["responseModalities"],L);let Y=l(t,["mediaResolution"]);if(Y!=null)u(o,["mediaResolution"],Y);let Z=l(t,["speechConfig"]);if(Z!=null)u(o,["speechConfig"],Js(Z));if(l(t,["audioTimestamp"])!==void 0)throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ne=l(t,["thinkingConfig"]);if(ne!=null)u(o,["thinkingConfig"],ne);let W=l(t,["audioTranscriptionConfig"]);if(W!=null)u(o,["audioTranscriptionConfig"],W);let H=l(t,["imageConfig"]);if(H!=null)u(o,["imageConfig"],FS(H));let oe=l(t,["enableEnhancedCivicAnswers"]);if(oe!=null)u(o,["enableEnhancedCivicAnswers"],oe);if(l(t,["modelArmorConfig"])!==void 0)throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function yS(e,t,n,i){let o={},s=l(t,["serviceTier"]);if(n!==void 0&&s!=null)u(n,["serviceTier"],s);let c=l(t,["systemInstruction"]);if(n!==void 0&&c!=null)u(n,["systemInstruction"],Zn(qe(c)));let d=l(t,["temperature"]);if(d!=null)u(o,["temperature"],d);let f=l(t,["topP"]);if(f!=null)u(o,["topP"],f);let h=l(t,["topK"]);if(h!=null)u(o,["topK"],h);let m=l(t,["candidateCount"]);if(m!=null)u(o,["candidateCount"],m);let g=l(t,["maxOutputTokens"]);if(g!=null)u(o,["maxOutputTokens"],g);let _=l(t,["stopSequences"]);if(_!=null)u(o,["stopSequences"],_);let E=l(t,["responseLogprobs"]);if(E!=null)u(o,["responseLogprobs"],E);let y=l(t,["logprobs"]);if(y!=null)u(o,["logprobs"],y);let v=l(t,["presencePenalty"]);if(v!=null)u(o,["presencePenalty"],v);let C=l(t,["frequencyPenalty"]);if(C!=null)u(o,["frequencyPenalty"],C);let T=l(t,["seed"]);if(T!=null)u(o,["seed"],T);let I=l(t,["responseMimeType"]);if(I!=null)u(o,["responseMimeType"],I);let P=l(t,["responseSchema"]);if(P!=null)u(o,["responseSchema"],$s(P));let N=l(t,["responseJsonSchema"]);if(N!=null)u(o,["responseJsonSchema"],Yn(N));let D=l(t,["routingConfig"]);if(D!=null)u(o,["routingConfig"],D);let q=l(t,["modelSelectionConfig"]);if(q!=null)u(o,["modelConfig"],q);let V=l(t,["safetySettings"]);if(n!==void 0&&V!=null){let Le=V;if(Array.isArray(Le))Le=Le.map((ze)=>ze);u(n,["safetySettings"],Le)}let J=l(t,["tools"]);if(n!==void 0&&J!=null){let Le=zn(J);if(Array.isArray(Le))Le=Le.map((ze)=>qm(Wn(ze)));u(n,["tools"],Le)}let L=l(t,["toolConfig"]);if(n!==void 0&&L!=null)u(n,["toolConfig"],hI(L));let Y=l(t,["labels"]);if(n!==void 0&&Y!=null)u(n,["labels"],Y);let Z=l(t,["cachedContent"]);if(n!==void 0&&Z!=null)u(n,["cachedContent"],Ot(e,Z));let ne=l(t,["responseModalities"]);if(ne!=null)u(o,["responseModalities"],ne);let W=l(t,["mediaResolution"]);if(W!=null)u(o,["mediaResolution"],W);let H=l(t,["speechConfig"]);if(H!=null)u(o,["speechConfig"],Lm(Js(H)));let oe=l(t,["audioTimestamp"]);if(oe!=null)u(o,["audioTimestamp"],oe);let se=l(t,["thinkingConfig"]);if(se!=null)u(o,["thinkingConfig"],se);let Ne=l(t,["audioTranscriptionConfig"]);if(Ne!=null)u(o,["audioTranscriptionConfig"],Ne);let Me=l(t,["imageConfig"]);if(Me!=null)u(o,["imageConfig"],HS(Me));if(l(t,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let Xe=l(t,["modelArmorConfig"]);if(n!==void 0&&Xe!=null)u(n,["modelArmorConfig"],Xe);return o}function Ah(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let d=We(s);if(Array.isArray(d))d=d.map((f)=>Sr(f));u(i,["contents"],d)}let c=l(t,["config"]);if(c!=null)u(i,["generationConfig"],_S(e,c,i));return i}function Ch(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["contents"]);if(s!=null){let d=We(s);if(Array.isArray(d))d=d.map((f)=>Zn(f));u(i,["contents"],d)}let c=l(t,["config"]);if(c!=null)u(i,["generationConfig"],yS(e,c,i));return i}function Sh(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["candidates"]);if(o!=null){let m=o;if(Array.isArray(m))m=m.map((g)=>F0(g));u(n,["candidates"],m)}let s=l(e,["modelVersion"]);if(s!=null)u(n,["modelVersion"],s);let c=l(e,["promptFeedback"]);if(c!=null)u(n,["promptFeedback"],c);let d=l(e,["responseId"]);if(d!=null)u(n,["responseId"],d);let f=l(e,["usageMetadata"]);if(f!=null)u(n,["usageMetadata"],f);let h=l(e,["modelStatus"]);if(h!=null)u(n,["modelStatus"],h);return n}function Ih(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["candidates"]);if(o!=null){let m=o;if(Array.isArray(m))m=m.map((g)=>g);u(n,["candidates"],m)}let s=l(e,["createTime"]);if(s!=null)u(n,["createTime"],s);let c=l(e,["modelVersion"]);if(c!=null)u(n,["modelVersion"],c);let d=l(e,["promptFeedback"]);if(d!=null)u(n,["promptFeedback"],d);let f=l(e,["responseId"]);if(f!=null)u(n,["responseId"],f);let h=l(e,["usageMetadata"]);if(h!=null)u(n,["usageMetadata"],h);return n}function ES(e,t,n){let i={},o=l(e,["outputGcsUri"]);if(t!==void 0&&o!=null)u(t,["parameters","storageUri"],o);let s=l(e,["negativePrompt"]);if(t!==void 0&&s!=null)u(t,["parameters","negativePrompt"],s);let c=l(e,["numberOfImages"]);if(t!==void 0&&c!=null)u(t,["parameters","sampleCount"],c);let d=l(e,["aspectRatio"]);if(t!==void 0&&d!=null)u(t,["parameters","aspectRatio"],d);let f=l(e,["guidanceScale"]);if(t!==void 0&&f!=null)u(t,["parameters","guidanceScale"],f);let h=l(e,["seed"]);if(t!==void 0&&h!=null)u(t,["parameters","seed"],h);let m=l(e,["safetyFilterLevel"]);if(t!==void 0&&m!=null)u(t,["parameters","safetySetting"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["includeSafetyAttributes"]);if(t!==void 0&&_!=null)u(t,["parameters","includeSafetyAttributes"],_);let E=l(e,["includeRaiReason"]);if(t!==void 0&&E!=null)u(t,["parameters","includeRaiReason"],E);let y=l(e,["language"]);if(t!==void 0&&y!=null)u(t,["parameters","language"],y);let v=l(e,["outputMimeType"]);if(t!==void 0&&v!=null)u(t,["parameters","outputOptions","mimeType"],v);let C=l(e,["outputCompressionQuality"]);if(t!==void 0&&C!=null)u(t,["parameters","outputOptions","compressionQuality"],C);let T=l(e,["addWatermark"]);if(t!==void 0&&T!=null)u(t,["parameters","addWatermark"],T);let I=l(e,["labels"]);if(t!==void 0&&I!=null)u(t,["labels"],I);let P=l(e,["imageSize"]);if(t!==void 0&&P!=null)u(t,["parameters","sampleImageSize"],P);let N=l(e,["enhancePrompt"]);if(t!==void 0&&N!=null)u(t,["parameters","enhancePrompt"],N);return i}function vS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["prompt"]);if(s!=null)u(i,["instances[0]","prompt"],s);let c=l(t,["config"]);if(c!=null)ES(c,i);return i}function TS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["predictions"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>Bi(d));u(n,["generatedImages"],c)}let s=l(e,["positivePromptSafetyAttributes"]);if(s!=null)u(n,["positivePromptSafetyAttributes"],bm(s));return n}function AS(e,t,n){let i={},o=l(e,["numberOfVideos"]);if(t!==void 0&&o!=null)u(t,["parameters","sampleCount"],o);if(l(e,["outputGcsUri"])!==void 0)throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["fps"])!==void 0)throw Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["durationSeconds"]);if(t!==void 0&&s!=null)u(t,["parameters","durationSeconds"],s);if(l(e,["seed"])!==void 0)throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["aspectRatio"]);if(t!==void 0&&c!=null)u(t,["parameters","aspectRatio"],c);let d=l(e,["resolution"]);if(t!==void 0&&d!=null)u(t,["parameters","resolution"],d);let f=l(e,["personGeneration"]);if(t!==void 0&&f!=null)u(t,["parameters","personGeneration"],f);if(l(e,["pubsubTopic"])!==void 0)throw Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["negativePrompt"]);if(t!==void 0&&h!=null)u(t,["parameters","negativePrompt"],h);let m=l(e,["enhancePrompt"]);if(t!==void 0&&m!=null)u(t,["parameters","enhancePrompt"],m);if(l(e,["generateAudio"])!==void 0)throw Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=l(e,["lastFrame"]);if(t!==void 0&&g!=null)u(t,["instances[0]","lastFrame"],$i(g));let _=l(e,["referenceImages"]);if(t!==void 0&&_!=null){let y=_;if(Array.isArray(y))y=y.map((v)=>PI(v));u(t,["instances[0]","referenceImages"],y)}if(l(e,["mask"])!==void 0)throw Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["compressionQuality"])!==void 0)throw Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let E=l(e,["webhookConfig"]);if(t!==void 0&&E!=null)u(t,["webhookConfig"],E);if(l(e,["resizeMode"])!==void 0)throw Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function CS(e,t,n){let i={},o=l(e,["numberOfVideos"]);if(t!==void 0&&o!=null)u(t,["parameters","sampleCount"],o);let s=l(e,["outputGcsUri"]);if(t!==void 0&&s!=null)u(t,["parameters","storageUri"],s);let c=l(e,["fps"]);if(t!==void 0&&c!=null)u(t,["parameters","fps"],c);let d=l(e,["durationSeconds"]);if(t!==void 0&&d!=null)u(t,["parameters","durationSeconds"],d);let f=l(e,["seed"]);if(t!==void 0&&f!=null)u(t,["parameters","seed"],f);let h=l(e,["aspectRatio"]);if(t!==void 0&&h!=null)u(t,["parameters","aspectRatio"],h);let m=l(e,["resolution"]);if(t!==void 0&&m!=null)u(t,["parameters","resolution"],m);let g=l(e,["personGeneration"]);if(t!==void 0&&g!=null)u(t,["parameters","personGeneration"],g);let _=l(e,["pubsubTopic"]);if(t!==void 0&&_!=null)u(t,["parameters","pubsubTopic"],_);let E=l(e,["negativePrompt"]);if(t!==void 0&&E!=null)u(t,["parameters","negativePrompt"],E);let y=l(e,["enhancePrompt"]);if(t!==void 0&&y!=null)u(t,["parameters","enhancePrompt"],y);let v=l(e,["generateAudio"]);if(t!==void 0&&v!=null)u(t,["parameters","generateAudio"],v);let C=l(e,["lastFrame"]);if(t!==void 0&&C!=null)u(t,["instances[0]","lastFrame"],Et(C));let T=l(e,["referenceImages"]);if(t!==void 0&&T!=null){let q=T;if(Array.isArray(q))q=q.map((V)=>NI(V));u(t,["instances[0]","referenceImages"],q)}let I=l(e,["mask"]);if(t!==void 0&&I!=null)u(t,["instances[0]","mask"],RI(I));let P=l(e,["compressionQuality"]);if(t!==void 0&&P!=null)u(t,["parameters","compressionQuality"],P);let N=l(e,["labels"]);if(t!==void 0&&N!=null)u(t,["labels"],N);if(l(e,["webhookConfig"])!==void 0)throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let D=l(e,["resizeMode"]);if(t!==void 0&&D!=null)u(t,["parameters","resizeMode"],D);return i}function SS(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["name"],i);let o=l(e,["metadata"]);if(o!=null)u(n,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(n,["done"],s);let c=l(e,["error"]);if(c!=null)u(n,["error"],c);let d=l(e,["response","generateVideoResponse"]);if(d!=null)u(n,["response"],PS(d));return n}function IS(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["name"],i);let o=l(e,["metadata"]);if(o!=null)u(n,["metadata"],o);let s=l(e,["done"]);if(s!=null)u(n,["done"],s);let c=l(e,["error"]);if(c!=null)u(n,["error"],c);let d=l(e,["response"]);if(d!=null)u(n,["response"],NS(d));return n}function wS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["prompt"]);if(s!=null)u(i,["instances[0]","prompt"],s);let c=l(t,["image"]);if(c!=null)u(i,["instances[0]","image"],$i(c));let d=l(t,["video"]);if(d!=null)u(i,["instances[0]","video"],Om(d));let f=l(t,["source"]);if(f!=null)xS(f,i);let h=l(t,["config"]);if(h!=null)AS(h,i);return i}function RS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["prompt"]);if(s!=null)u(i,["instances[0]","prompt"],s);let c=l(t,["image"]);if(c!=null)u(i,["instances[0]","image"],Et(c));let d=l(t,["video"]);if(d!=null)u(i,["instances[0]","video"],Fm(d));let f=l(t,["source"]);if(f!=null)kS(f,i);let h=l(t,["config"]);if(h!=null)CS(h,i);return i}function PS(e,t){let n={},i=l(e,["generatedSamples"]);if(i!=null){let c=i;if(Array.isArray(c))c=c.map((d)=>MS(d));u(n,["generatedVideos"],c)}let o=l(e,["raiMediaFilteredCount"]);if(o!=null)u(n,["raiMediaFilteredCount"],o);let s=l(e,["raiMediaFilteredReasons"]);if(s!=null)u(n,["raiMediaFilteredReasons"],s);return n}function NS(e,t){let n={},i=l(e,["videos"]);if(i!=null){let c=i;if(Array.isArray(c))c=c.map((d)=>US(d));u(n,["generatedVideos"],c)}let o=l(e,["raiMediaFilteredCount"]);if(o!=null)u(n,["raiMediaFilteredCount"],o);let s=l(e,["raiMediaFilteredReasons"]);if(s!=null)u(n,["raiMediaFilteredReasons"],s);return n}function xS(e,t,n){let i={},o=l(e,["prompt"]);if(t!==void 0&&o!=null)u(t,["instances[0]","prompt"],o);let s=l(e,["image"]);if(t!==void 0&&s!=null)u(t,["instances[0]","image"],$i(s));let c=l(e,["video"]);if(t!==void 0&&c!=null)u(t,["instances[0]","video"],Om(c));return i}function kS(e,t,n){let i={},o=l(e,["prompt"]);if(t!==void 0&&o!=null)u(t,["instances[0]","prompt"],o);let s=l(e,["image"]);if(t!==void 0&&s!=null)u(t,["instances[0]","image"],Et(s));let c=l(e,["video"]);if(t!==void 0&&c!=null)u(t,["instances[0]","video"],Fm(c));return i}function Bi(e,t){let n={},i=l(e,["_self"]);if(i!=null)u(n,["image"],Gm(i));let o=l(e,["raiFilteredReason"]);if(o!=null)u(n,["raiFilteredReason"],o);let s=l(e,["_self"]);if(s!=null)u(n,["safetyAttributes"],bm(s));let c=l(e,["prompt"]);if(c!=null)u(n,["enhancedPrompt"],c);return n}function DS(e,t){let n={},i=l(e,["_self"]);if(i!=null)u(n,["mask"],Gm(i));let o=l(e,["labels"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(n,["labels"],s)}return n}function MS(e,t){let n={},i=l(e,["video"]);if(i!=null)u(n,["video"],II(i));return n}function US(e,t){let n={},i=l(e,["_self"]);if(i!=null)u(n,["video"],wI(i));return n}function GS(e,t){let n={},i=l(e,["modelSelectionConfig"]);if(i!=null)u(n,["modelConfig"],i);let o=l(e,["responseJsonSchema"]);if(o!=null)u(n,["responseJsonSchema"],Yn(o));let s=l(e,["audioTranscriptionConfig"]);if(s!=null)u(n,["audioTranscriptionConfig"],s);let c=l(e,["audioTimestamp"]);if(c!=null)u(n,["audioTimestamp"],c);let d=l(e,["candidateCount"]);if(d!=null)u(n,["candidateCount"],d);let f=l(e,["enableAffectiveDialog"]);if(f!=null)u(n,["enableAffectiveDialog"],f);let h=l(e,["frequencyPenalty"]);if(h!=null)u(n,["frequencyPenalty"],h);let m=l(e,["logprobs"]);if(m!=null)u(n,["logprobs"],m);let g=l(e,["maxOutputTokens"]);if(g!=null)u(n,["maxOutputTokens"],g);let _=l(e,["mediaResolution"]);if(_!=null)u(n,["mediaResolution"],_);let E=l(e,["presencePenalty"]);if(E!=null)u(n,["presencePenalty"],E);let y=l(e,["responseFormat"]);if(y!=null){let Z=y;if(Array.isArray(Z))Z=Z.map((ne)=>ne);u(n,["responseFormat"],Z)}let v=l(e,["responseLogprobs"]);if(v!=null)u(n,["responseLogprobs"],v);let C=l(e,["responseMimeType"]);if(C!=null)u(n,["responseMimeType"],C);let T=l(e,["responseModalities"]);if(T!=null)u(n,["responseModalities"],T);let I=l(e,["responseSchema"]);if(I!=null)u(n,["responseSchema"],I);let P=l(e,["routingConfig"]);if(P!=null)u(n,["routingConfig"],P);let N=l(e,["seed"]);if(N!=null)u(n,["seed"],N);let D=l(e,["speechConfig"]);if(D!=null)u(n,["speechConfig"],Lm(D));let q=l(e,["stopSequences"]);if(q!=null)u(n,["stopSequences"],q);let V=l(e,["temperature"]);if(V!=null)u(n,["temperature"],V);let J=l(e,["thinkingConfig"]);if(J!=null)u(n,["thinkingConfig"],J);let L=l(e,["topK"]);if(L!=null)u(n,["topK"],L);let Y=l(e,["topP"]);if(Y!=null)u(n,["topP"],Y);if(l(e,["enableEnhancedCivicAnswers"])!==void 0)throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["translationConfig"])!==void 0)throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","name"],de(e,o));return i}function LS(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","name"],de(e,o));return i}function qS(e,t){let n={},i=l(e,["authConfig"]);if(i!=null)u(n,["authConfig"],q0(i));let o=l(e,["enableWidget"]);if(o!=null)u(n,["enableWidget"],o);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function OS(e,t){let n={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["searchTypes"]);if(i!=null)u(n,["searchTypes"],i);let o=l(e,["timeRangeFilter"]);if(o!=null)u(n,["timeRangeFilter"],o);return n}function FS(e,t){let n={},i=l(e,["aspectRatio"]);if(i!=null)u(n,["aspectRatio"],i);let o=l(e,["imageSize"]);if(o!=null)u(n,["imageSize"],o);if(l(e,["personGeneration"])!==void 0)throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputMimeType"])!==void 0)throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputCompressionQuality"])!==void 0)throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["imageOutputOptions"])!==void 0)throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["prominentPeople"])!==void 0)throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function HS(e,t){let n={},i=l(e,["aspectRatio"]);if(i!=null)u(n,["aspectRatio"],i);let o=l(e,["imageSize"]);if(o!=null)u(n,["imageSize"],o);let s=l(e,["personGeneration"]);if(s!=null)u(n,["personGeneration"],s);let c=l(e,["outputMimeType"]);if(c!=null)u(n,["imageOutputOptions","mimeType"],c);let d=l(e,["outputCompressionQuality"]);if(d!=null)u(n,["imageOutputOptions","compressionQuality"],d);let f=l(e,["imageOutputOptions"]);if(f!=null)u(n,["imageOutputOptions"],f);let h=l(e,["prominentPeople"]);if(h!=null)u(n,["prominentPeople"],h);return n}function Gm(e,t){let n={},i=l(e,["gcsUri"]);if(i!=null)u(n,["gcsUri"],i);let o=l(e,["bytesBase64Encoded"]);if(o!=null)u(n,["imageBytes"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function $i(e,t){let n={};if(l(e,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["imageBytes"]);if(i!=null)u(n,["bytesBase64Encoded"],En(i));let o=l(e,["mimeType"]);if(o!=null)u(n,["mimeType"],o);return n}function Et(e,t){let n={},i=l(e,["gcsUri"]);if(i!=null)u(n,["gcsUri"],i);let o=l(e,["imageBytes"]);if(o!=null)u(n,["bytesBase64Encoded"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function VS(e,t,n,i){let o={},s=l(t,["pageSize"]);if(n!==void 0&&s!=null)u(n,["_query","pageSize"],s);let c=l(t,["pageToken"]);if(n!==void 0&&c!=null)u(n,["_query","pageToken"],c);let d=l(t,["filter"]);if(n!==void 0&&d!=null)u(n,["_query","filter"],d);let f=l(t,["queryBase"]);if(n!==void 0&&f!=null)u(n,["_url","models_url"],Am(e,f));return o}function BS(e,t,n,i){let o={},s=l(t,["pageSize"]);if(n!==void 0&&s!=null)u(n,["_query","pageSize"],s);let c=l(t,["pageToken"]);if(n!==void 0&&c!=null)u(n,["_query","pageToken"],c);let d=l(t,["filter"]);if(n!==void 0&&d!=null)u(n,["_query","filter"],d);let f=l(t,["queryBase"]);if(n!==void 0&&f!=null)u(n,["_url","models_url"],Am(e,f));return o}function $S(e,t,n){let i={},o=l(t,["config"]);if(o!=null)VS(e,o,i);return i}function JS(e,t,n){let i={},o=l(t,["config"]);if(o!=null)BS(e,o,i);return i}function XS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["nextPageToken"]);if(o!=null)u(n,["nextPageToken"],o);let s=l(e,["_self"]);if(s!=null){let c=Cm(s);if(Array.isArray(c))c=c.map((d)=>Ds(d));u(n,["models"],c)}return n}function KS(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["nextPageToken"]);if(o!=null)u(n,["nextPageToken"],o);let s=l(e,["_self"]);if(s!=null){let c=Cm(s);if(Array.isArray(c))c=c.map((d)=>Ms(d));u(n,["models"],c)}return n}function YS(e,t){let n={},i=l(e,["maskMode"]);if(i!=null)u(n,["maskMode"],i);let o=l(e,["segmentationClasses"]);if(o!=null)u(n,["maskClasses"],o);let s=l(e,["maskDilation"]);if(s!=null)u(n,["dilation"],s);return n}function WS(e,t){let n={};if(l(e,["name"])!==void 0)throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["streamableHttpTransport"])!==void 0)throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Ds(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["name"],i);let o=l(e,["displayName"]);if(o!=null)u(n,["displayName"],o);let s=l(e,["description"]);if(s!=null)u(n,["description"],s);let c=l(e,["version"]);if(c!=null)u(n,["version"],c);let d=l(e,["_self"]);if(d!=null)u(n,["tunedModelInfo"],gI(d));let f=l(e,["inputTokenLimit"]);if(f!=null)u(n,["inputTokenLimit"],f);let h=l(e,["outputTokenLimit"]);if(h!=null)u(n,["outputTokenLimit"],h);let m=l(e,["supportedGenerationMethods"]);if(m!=null)u(n,["supportedActions"],m);let g=l(e,["temperature"]);if(g!=null)u(n,["temperature"],g);let _=l(e,["maxTemperature"]);if(_!=null)u(n,["maxTemperature"],_);let E=l(e,["topP"]);if(E!=null)u(n,["topP"],E);let y=l(e,["topK"]);if(y!=null)u(n,["topK"],y);let v=l(e,["thinking"]);if(v!=null)u(n,["thinking"],v);return n}function Ms(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["name"],i);let o=l(e,["displayName"]);if(o!=null)u(n,["displayName"],o);let s=l(e,["description"]);if(s!=null)u(n,["description"],s);let c=l(e,["versionId"]);if(c!=null)u(n,["version"],c);let d=l(e,["deployedModels"]);if(d!=null){let _=d;if(Array.isArray(_))_=_.map((E)=>pS(E));u(n,["endpoints"],_)}let f=l(e,["labels"]);if(f!=null)u(n,["labels"],f);let h=l(e,["_self"]);if(h!=null)u(n,["tunedModelInfo"],_I(h));let m=l(e,["defaultCheckpointId"]);if(m!=null)u(n,["defaultCheckpointId"],m);let g=l(e,["checkpoints"]);if(g!=null){let _=g;if(Array.isArray(_))_=_.map((E)=>E);u(n,["checkpoints"],_)}return n}function zS(e,t){let n={},i=l(e,["speakerVoiceConfigs"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>fI(s));u(n,["speakerVoiceConfigs"],o)}return n}function QS(e,t){let n={},i=l(e,["mediaResolution"]);if(i!=null)u(n,["mediaResolution"],i);let o=l(e,["toolCall"]);if(o!=null)u(n,["toolCall"],o);let s=l(e,["toolResponse"]);if(s!=null)u(n,["toolResponse"],s);let c=l(e,["audioTranscription"]);if(c!=null)u(n,["audioTranscription"],c);let d=l(e,["codeExecutionResult"]);if(d!=null)u(n,["codeExecutionResult"],d);let f=l(e,["executableCode"]);if(f!=null)u(n,["executableCode"],f);let h=l(e,["fileData"]);if(h!=null)u(n,["fileData"],hS(h));let m=l(e,["functionCall"]);if(m!=null)u(n,["functionCall"],mS(m));let g=l(e,["functionResponse"]);if(g!=null)u(n,["functionResponse"],g);let _=l(e,["inlineData"]);if(_!=null)u(n,["inlineData"],O0(_));let E=l(e,["text"]);if(E!=null)u(n,["text"],E);let y=l(e,["thought"]);if(y!=null)u(n,["thought"],y);let v=l(e,["thoughtSignature"]);if(v!=null)u(n,["thoughtSignature"],v);let C=l(e,["videoMetadata"]);if(C!=null)u(n,["videoMetadata"],C);let T=l(e,["partMetadata"]);if(T!=null)u(n,["partMetadata"],T);let I=l(e,["mediaProcessing"]);if(I!=null)u(n,["mediaProcessing"],I);return n}function ZS(e,t){let n={},i=l(e,["mediaResolution"]);if(i!=null)u(n,["mediaResolution"],i);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=l(e,["audioTranscription"]);if(o!=null)u(n,["audioTranscription"],o);let s=l(e,["codeExecutionResult"]);if(s!=null)u(n,["codeExecutionResult"],s);let c=l(e,["executableCode"]);if(c!=null)u(n,["executableCode"],c);let d=l(e,["fileData"]);if(d!=null)u(n,["fileData"],d);let f=l(e,["functionCall"]);if(f!=null)u(n,["functionCall"],f);let h=l(e,["functionResponse"]);if(h!=null)u(n,["functionResponse"],h);let m=l(e,["inlineData"]);if(m!=null)u(n,["inlineData"],m);let g=l(e,["text"]);if(g!=null)u(n,["text"],g);let _=l(e,["thought"]);if(_!=null)u(n,["thought"],_);let E=l(e,["thoughtSignature"]);if(E!=null)u(n,["thoughtSignature"],E);let y=l(e,["videoMetadata"]);if(y!=null)u(n,["videoMetadata"],y);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let v=l(e,["mediaProcessing"]);if(v!=null)u(n,["mediaProcessing"],v);return n}function jS(e,t){let n={},i=l(e,["productImage"]);if(i!=null)u(n,["image"],Et(i));return n}function eI(e,t,n){let i={},o=l(e,["numberOfImages"]);if(t!==void 0&&o!=null)u(t,["parameters","sampleCount"],o);let s=l(e,["baseSteps"]);if(t!==void 0&&s!=null)u(t,["parameters","baseSteps"],s);let c=l(e,["outputGcsUri"]);if(t!==void 0&&c!=null)u(t,["parameters","storageUri"],c);let d=l(e,["seed"]);if(t!==void 0&&d!=null)u(t,["parameters","seed"],d);let f=l(e,["safetyFilterLevel"]);if(t!==void 0&&f!=null)u(t,["parameters","safetySetting"],f);let h=l(e,["personGeneration"]);if(t!==void 0&&h!=null)u(t,["parameters","personGeneration"],h);let m=l(e,["addWatermark"]);if(t!==void 0&&m!=null)u(t,["parameters","addWatermark"],m);let g=l(e,["outputMimeType"]);if(t!==void 0&&g!=null)u(t,["parameters","outputOptions","mimeType"],g);let _=l(e,["outputCompressionQuality"]);if(t!==void 0&&_!=null)u(t,["parameters","outputOptions","compressionQuality"],_);let E=l(e,["enhancePrompt"]);if(t!==void 0&&E!=null)u(t,["parameters","enhancePrompt"],E);let y=l(e,["labels"]);if(t!==void 0&&y!=null)u(t,["labels"],y);return i}function tI(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["source"]);if(s!=null)rI(s,i);let c=l(t,["config"]);if(c!=null)eI(c,i);return i}function nI(e,t){let n={},i=l(e,["predictions"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>Bi(s));u(n,["generatedImages"],o)}return n}function rI(e,t,n){let i={},o=l(e,["prompt"]);if(t!==void 0&&o!=null)u(t,["instances[0]","prompt"],o);let s=l(e,["personImage"]);if(t!==void 0&&s!=null)u(t,["instances[0]","personImage","image"],Et(s));let c=l(e,["productImages"]);if(t!==void 0&&c!=null){let d=c;if(Array.isArray(d))d=d.map((f)=>jS(f));u(t,["instances[0]","productImages"],d)}return i}function iI(e,t){let n={},i=l(e,["referenceImage"]);if(i!=null)u(n,["referenceImage"],Et(i));let o=l(e,["referenceId"]);if(o!=null)u(n,["referenceId"],o);let s=l(e,["referenceType"]);if(s!=null)u(n,["referenceType"],s);let c=l(e,["maskImageConfig"]);if(c!=null)u(n,["maskImageConfig"],YS(c));let d=l(e,["controlImageConfig"]);if(d!=null)u(n,["controlImageConfig"],K0(d));let f=l(e,["styleImageConfig"]);if(f!=null)u(n,["styleImageConfig"],f);let h=l(e,["subjectImageConfig"]);if(h!=null)u(n,["subjectImageConfig"],h);return n}function oI(e,t){let n={},i=l(e,["mimeType"]);if(i!=null)u(n,["mimeType"],i);let o=l(e,["voiceSampleAudio"]);if(o!=null)u(n,["voiceSampleAudio"],o);if(l(e,["consentAudio"])!==void 0)throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["voiceConsentSignature"])!==void 0)throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bm(e,t){let n={},i=l(e,["safetyAttributes","categories"]);if(i!=null)u(n,["categories"],i);let o=l(e,["safetyAttributes","scores"]);if(o!=null)u(n,["scores"],o);let s=l(e,["contentType"]);if(s!=null)u(n,["contentType"],s);return n}function sI(e,t){let n={},i=l(e,["category"]);if(i!=null)u(n,["category"],i);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["threshold"]);if(o!=null)u(n,["threshold"],o);return n}function aI(e,t){let n={},i=l(e,["image"]);if(i!=null)u(n,["image"],Et(i));return n}function lI(e,t,n){let i={},o=l(e,["mode"]);if(t!==void 0&&o!=null)u(t,["parameters","mode"],o);let s=l(e,["maxPredictions"]);if(t!==void 0&&s!=null)u(t,["parameters","maxPredictions"],s);let c=l(e,["confidenceThreshold"]);if(t!==void 0&&c!=null)u(t,["parameters","confidenceThreshold"],c);let d=l(e,["maskDilation"]);if(t!==void 0&&d!=null)u(t,["parameters","maskDilation"],d);let f=l(e,["binaryColorThreshold"]);if(t!==void 0&&f!=null)u(t,["parameters","binaryColorThreshold"],f);let h=l(e,["labels"]);if(t!==void 0&&h!=null)u(t,["labels"],h);return i}function uI(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["source"]);if(s!=null)dI(s,i);let c=l(t,["config"]);if(c!=null)lI(c,i);return i}function cI(e,t){let n={},i=l(e,["predictions"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>DS(s));u(n,["generatedMasks"],o)}return n}function dI(e,t,n){let i={},o=l(e,["prompt"]);if(t!==void 0&&o!=null)u(t,["instances[0]","prompt"],o);let s=l(e,["image"]);if(t!==void 0&&s!=null)u(t,["instances[0]","image"],Et(s));let c=l(e,["scribbleImage"]);if(t!==void 0&&c!=null)u(t,["instances[0]","scribble"],aI(c));return i}function fI(e,t){let n={},i=l(e,["speaker"]);if(i!=null)u(n,["speaker"],i);let o=l(e,["voiceConfig"]);if(o!=null)u(n,["voiceConfig"],Hm(o));return n}function Lm(e,t){let n={},i=l(e,["voiceConfig"]);if(i!=null)u(n,["voiceConfig"],Hm(i));let o=l(e,["languageCode"]);if(o!=null)u(n,["languageCode"],o);let s=l(e,["multiSpeakerVoiceConfig"]);if(s!=null)u(n,["multiSpeakerVoiceConfig"],zS(s));return n}function pI(e,t){let n={},i=l(e,["functionCallingConfig"]);if(i!=null)u(n,["functionCallingConfig"],gS(i));let o=l(e,["retrievalConfig"]);if(o!=null)u(n,["retrievalConfig"],o);let s=l(e,["includeServerSideToolInvocations"]);if(s!=null)u(n,["includeServerSideToolInvocations"],s);return n}function hI(e,t){let n={},i=l(e,["functionCallingConfig"]);if(i!=null)u(n,["functionCallingConfig"],i);let o=l(e,["retrievalConfig"]);if(o!=null)u(n,["retrievalConfig"],o);if(l(e,["includeServerSideToolInvocations"])!==void 0)throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function mI(e,t){let n={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["googleMaps"]);if(i!=null)u(n,["googleMaps"],qS(i));let o=l(e,["mcpServers"]);if(o!=null){let _=o;if(Array.isArray(_))_=_.map((E)=>E);u(n,["mcpServers"],_)}let s=l(e,["codeExecution"]);if(s!=null)u(n,["codeExecution"],s);let c=l(e,["computerUse"]);if(c!=null)u(n,["computerUse"],c);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=l(e,["functionDeclarations"]);if(d!=null){let _=d;if(Array.isArray(_))_=_.map((E)=>E);u(n,["functionDeclarations"],_)}let f=l(e,["googleSearch"]);if(f!=null)u(n,["googleSearch"],OS(f));let h=l(e,["googleSearchRetrieval"]);if(h!=null)u(n,["googleSearchRetrieval"],h);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=l(e,["urlContext"]);if(m!=null)u(n,["urlContext"],m);let g=l(e,["fileSearch"]);if(g!=null)u(n,["fileSearch"],g);return n}function qm(e,t){let n={},i=l(e,["retrieval"]);if(i!=null)u(n,["retrieval"],i);let o=l(e,["googleMaps"]);if(o!=null)u(n,["googleMaps"],o);let s=l(e,["mcpServers"]);if(s!=null){let v=s;if(Array.isArray(v))v=v.map((C)=>WS(C));u(n,["mcpServers"],v)}let c=l(e,["codeExecution"]);if(c!=null)u(n,["codeExecution"],c);let d=l(e,["computerUse"]);if(d!=null)u(n,["computerUse"],$0(d));let f=l(e,["enterpriseWebSearch"]);if(f!=null)u(n,["enterpriseWebSearch"],f);let h=l(e,["exaAiSearch"]);if(h!=null)u(n,["exaAiSearch"],h);let m=l(e,["functionDeclarations"]);if(m!=null){let v=m;if(Array.isArray(v))v=v.map((C)=>C);u(n,["functionDeclarations"],v)}let g=l(e,["googleSearch"]);if(g!=null)u(n,["googleSearch"],g);let _=l(e,["googleSearchRetrieval"]);if(_!=null)u(n,["googleSearchRetrieval"],_);let E=l(e,["parallelAiSearch"]);if(E!=null)u(n,["parallelAiSearch"],E);let y=l(e,["urlContext"]);if(y!=null)u(n,["urlContext"],y);if(l(e,["fileSearch"])!==void 0)throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function gI(e,t){let n={},i=l(e,["baseModel"]);if(i!=null)u(n,["baseModel"],i);let o=l(e,["createTime"]);if(o!=null)u(n,["createTime"],o);let s=l(e,["updateTime"]);if(s!=null)u(n,["updateTime"],s);return n}function _I(e,t){let n={},i=l(e,["labels","google-vertex-llm-tuning-base-model-id"]);if(i!=null)u(n,["baseModel"],i);let o=l(e,["createTime"]);if(o!=null)u(n,["createTime"],o);let s=l(e,["updateTime"]);if(s!=null)u(n,["updateTime"],s);return n}function yI(e,t,n){let i={},o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["displayName"],o);let s=l(e,["description"]);if(t!==void 0&&s!=null)u(t,["description"],s);let c=l(e,["defaultCheckpointId"]);if(t!==void 0&&c!=null)u(t,["defaultCheckpointId"],c);return i}function EI(e,t,n){let i={},o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["displayName"],o);let s=l(e,["description"]);if(t!==void 0&&s!=null)u(t,["description"],s);let c=l(e,["defaultCheckpointId"]);if(t!==void 0&&c!=null)u(t,["defaultCheckpointId"],c);return i}function vI(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","name"],de(e,o));let s=l(t,["config"]);if(s!=null)yI(s,i);return i}function TI(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["config"]);if(s!=null)EI(s,i);return i}function AI(e,t,n){let i={},o=l(e,["outputGcsUri"]);if(t!==void 0&&o!=null)u(t,["parameters","storageUri"],o);let s=l(e,["safetyFilterLevel"]);if(t!==void 0&&s!=null)u(t,["parameters","safetySetting"],s);let c=l(e,["personGeneration"]);if(t!==void 0&&c!=null)u(t,["parameters","personGeneration"],c);let d=l(e,["includeRaiReason"]);if(t!==void 0&&d!=null)u(t,["parameters","includeRaiReason"],d);let f=l(e,["outputMimeType"]);if(t!==void 0&&f!=null)u(t,["parameters","outputOptions","mimeType"],f);let h=l(e,["outputCompressionQuality"]);if(t!==void 0&&h!=null)u(t,["parameters","outputOptions","compressionQuality"],h);let m=l(e,["enhanceInputImage"]);if(t!==void 0&&m!=null)u(t,["parameters","upscaleConfig","enhanceInputImage"],m);let g=l(e,["imagePreservationFactor"]);if(t!==void 0&&g!=null)u(t,["parameters","upscaleConfig","imagePreservationFactor"],g);let _=l(e,["labels"]);if(t!==void 0&&_!=null)u(t,["labels"],_);let E=l(e,["numberOfImages"]);if(t!==void 0&&E!=null)u(t,["parameters","sampleCount"],E);let y=l(e,["mode"]);if(t!==void 0&&y!=null)u(t,["parameters","mode"],y);return i}function CI(e,t,n){let i={},o=l(t,["model"]);if(o!=null)u(i,["_url","model"],de(e,o));let s=l(t,["image"]);if(s!=null)u(i,["instances[0]","image"],Et(s));let c=l(t,["upscaleFactor"]);if(c!=null)u(i,["parameters","upscaleConfig","upscaleFactor"],c);let d=l(t,["config"]);if(d!=null)AI(d,i);return i}function SI(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["predictions"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>Bi(c));u(n,["generatedImages"],s)}return n}function II(e,t){let n={},i=l(e,["uri"]);if(i!=null)u(n,["uri"],i);let o=l(e,["encodedVideo"]);if(o!=null)u(n,["videoBytes"],En(o));let s=l(e,["encoding"]);if(s!=null)u(n,["mimeType"],s);return n}function wI(e,t){let n={},i=l(e,["gcsUri"]);if(i!=null)u(n,["uri"],i);let o=l(e,["bytesBase64Encoded"]);if(o!=null)u(n,["videoBytes"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function RI(e,t){let n={},i=l(e,["image"]);if(i!=null)u(n,["_self"],Et(i));let o=l(e,["maskMode"]);if(o!=null)u(n,["maskMode"],o);return n}function PI(e,t){let n={},i=l(e,["image"]);if(i!=null)u(n,["image"],$i(i));let o=l(e,["referenceType"]);if(o!=null)u(n,["referenceType"],o);return n}function NI(e,t){let n={},i=l(e,["image"]);if(i!=null)u(n,["image"],Et(i));let o=l(e,["referenceType"]);if(o!=null)u(n,["referenceType"],o);return n}function Om(e,t){let n={},i=l(e,["uri"]);if(i!=null)u(n,["uri"],i);let o=l(e,["videoBytes"]);if(o!=null)u(n,["encodedVideo"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["encoding"],s);return n}function Fm(e,t){let n={},i=l(e,["uri"]);if(i!=null)u(n,["gcsUri"],i);let o=l(e,["videoBytes"]);if(o!=null)u(n,["bytesBase64Encoded"],En(o));let s=l(e,["mimeType"]);if(s!=null)u(n,["mimeType"],s);return n}function Hm(e,t){let n={},i=l(e,["replicatedVoiceConfig"]);if(i!=null)u(n,["replicatedVoiceConfig"],oI(i));let o=l(e,["prebuiltVoiceConfig"]);if(o!=null)u(n,["prebuiltVoiceConfig"],o);return n}function xI(e,t,n){let i={},o=l(t,["displayName"]);if(n!==void 0&&o!=null)u(n,["displayName"],o);let s=l(t,["embeddingModel"]);if(n!==void 0&&s!=null)u(n,["embeddingModel"],de(e,s));return i}function kI(e,t){let n={},i=l(t,["config"]);if(i!=null)xI(e,i,n);return n}function DI(e,t){let n={},i=l(e,["force"]);if(t!==void 0&&i!=null)u(t,["_query","force"],i);return n}function MI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);let i=l(e,["config"]);if(i!=null)DI(i,t);return t}function UI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);return t}function GI(e,t){let n={},i=l(e,["customMetadata"]);if(t!==void 0&&i!=null){let s=i;if(Array.isArray(s))s=s.map((c)=>c);u(t,["customMetadata"],s)}let o=l(e,["chunkingConfig"]);if(t!==void 0&&o!=null)u(t,["chunkingConfig"],o);return n}function bI(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["name"],n);let i=l(e,["metadata"]);if(i!=null)u(t,["metadata"],i);let o=l(e,["done"]);if(o!=null)u(t,["done"],o);let s=l(e,["error"]);if(s!=null)u(t,["error"],s);let c=l(e,["response"]);if(c!=null)u(t,["response"],qI(c));return t}function LI(e){let t={},n=l(e,["fileSearchStoreName"]);if(n!=null)u(t,["_url","file_search_store_name"],n);let i=l(e,["fileName"]);if(i!=null)u(t,["fileName"],i);let o=l(e,["config"]);if(o!=null)GI(o,t);return t}function qI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["parent"]);if(i!=null)u(t,["parent"],i);let o=l(e,["documentName"]);if(o!=null)u(t,["documentName"],o);return t}function OI(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);return n}function FI(e){let t={},n=l(e,["config"]);if(n!=null)OI(n,t);return t}function HI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["fileSearchStores"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["fileSearchStores"],s)}return t}function Vm(e,t){let n={},i=l(e,["mimeType"]);if(t!==void 0&&i!=null)u(t,["mimeType"],i);let o=l(e,["displayName"]);if(t!==void 0&&o!=null)u(t,["displayName"],o);let s=l(e,["customMetadata"]);if(t!==void 0&&s!=null){let d=s;if(Array.isArray(d))d=d.map((f)=>f);u(t,["customMetadata"],d)}let c=l(e,["chunkingConfig"]);if(t!==void 0&&c!=null)u(t,["chunkingConfig"],c);return n}function VI(e){let t={},n=l(e,["fileSearchStoreName"]);if(n!=null)u(t,["_url","file_search_store_name"],n);let i=l(e,["config"]);if(i!=null)Vm(i,t);return t}function BI(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);return t}var $I="Content-Type",JI="X-Server-Timeout",XI="User-Agent",Us="x-goog-api-client",KI="2.21.0",YI=`google-genai-sdk/${KI}`,WI="v1beta1",zI="v1beta",QI=new Set(["us","eu"]);function ZI(e){let n=globalThis[Symbol.for("undici.globalDispatcher.1")];if(!n)return;for(let i of Object.getOwnPropertySymbols(n)){let o=i.description;if((o===null||o===void 0?void 0:o.includes("headers timeout"))||(o===null||o===void 0?void 0:o.includes("body timeout"))){let s=n[i];if(typeof s==="number")n[i]=Math.max(s,e)}}}function jI(e,t){let n=()=>{};if(!(e&&e>0)&&!t)return{signal:void 0,dispose:n};let i=new AbortController,o;if(e&&e>0){if(o=setTimeout(()=>i.abort(),e),o&&typeof o.unref==="function")o.unref()}let s=()=>i.abort();if(t)if(t.aborted)i.abort();else t.addEventListener("abort",s);return{signal:i.signal,dispose:()=>{if(o!==void 0)clearTimeout(o);t===null||t===void 0||t.removeEventListener("abort",s)}}}var ew=5,tw=1,nw=60,rw=2,iw=1,ow=[408,429,500,502,503,504];class Bm{constructor(e){var t,n,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(t=e.httpOptions)===null||t===void 0?void 0:t.baseUrl;let o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl)this.clientOptions.location="global";if(!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let c=e.project&&e.location||!!e.apiKey;if(this.customBaseUrl&&!c)o.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0;else if(this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global")o.baseUrl="https://aiplatform.googleapis.com/";else if(this.clientOptions.project&&this.clientOptions.location&&QI.has(this.clientOptions.location))o.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`;else if(this.clientOptions.project&&this.clientOptions.location)o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`;o.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:WI}else{if(!this.clientOptions.apiKey)console.warn("API key should be set when using the Gemini API.");o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:zI,o.baseUrl="https://generativelanguage.googleapis.com/"}if(o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions)this.clientOptions.httpOptions=this.patchHttpOptions(o,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 Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw 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;else throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw Error("HTTP options are not correctly set.");let n=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];if(e.apiVersion&&e.apiVersion!=="")n.push(e.apiVersion);return n.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,n){let i=[this.getRequestUrlInternal(t)];if(n)i.push(this.getBaseResourcePath());if(e!=="")i.push(e);return new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e,t){if(t.baseUrl&&t.baseUrlResourceScope===vr.COLLECTION)return!1;if(!this.clientOptions.vertexai)return!1;if(!this.clientOptions.project||!this.clientOptions.location)return!1;if(e.path.startsWith("projects/"))return!1;if(e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))return!1;return!0}async request(e){let t=this.clientOptions.httpOptions;if(e.httpOptions)t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions);let n=this.shouldPrependVertexProjectPath(e,t),i=this.constructUrl(e.path,t,n);if(e.queryParams)for(let[s,c]of Object.entries(e.queryParams))i.searchParams.append(s,String(c));let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw Error("Request body should be empty for GET request, but got non empty request body")}else o.body=e.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,t,i.toString()),this.unaryApiCall(i,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal)}patchHttpOptions(e,t){let n=JSON.parse(JSON.stringify(e));for(let[i,o]of Object.entries(t))if(typeof o==="object")n[i]=Object.assign(Object.assign({},n[i]),o);else if(o!==void 0)n[i]=o;return n}async requestStream(e){let t=this.clientOptions.httpOptions;if(e.httpOptions)t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions);let n=this.shouldPrependVertexProjectPath(e,t),i=this.constructUrl(e.path,t,n);if(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")i.searchParams.set("alt","sse");let o={};return o.body=e.body,o=await this.includeExtraHttpOptionsToRequestInit(o,t,i.toString()),this.streamApiCall(i,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal)}async includeExtraHttpOptionsToRequestInit(e,t,n){if((t===null||t===void 0?void 0:t.timeout)&&t.timeout>0)ZI(t.timeout);if(t&&t.extraBody!==null)sw(e,t.extraBody);return e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n,i,o,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),i,o,s).then(async(c)=>(await _s(c),new yn(c))).catch((c)=>{if(c instanceof Error)throw c;else throw Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,t,n,i,o,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),i,o,s).then(async(c)=>(await _s(c),this.processStreamResponse(c))).catch((c)=>{if(c instanceof Error)throw c;else throw Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return Xn(this,arguments,function*(){var n;let i=(n=e===null||e===void 0?void 0:e.body)===null||n===void 0?void 0:n.getReader(),o=new TextDecoder("utf-8");if(!i)throw Error("Response body is empty");try{let s="",c="data:",d=[`
|
|
32
32
|
|
|
33
33
|
`,"\r\r",`\r
|
|
34
34
|
\r
|
|
35
|
-
`];while(!0){let{done:f,value:h}=yield Ne(o.read());if(f){if(a.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let m=s.decode(h,{stream:!0});try{let v=JSON.parse(m);if("error"in v){let E=JSON.parse(JSON.stringify(v.error)),{status:T,code:S}=E,A=`got status: ${T}. ${JSON.stringify(v)}`;if(S>=400&&S<600)throw new Vi({message:A,status:S})}}catch(v){if(v.name==="ApiError")throw v}a+=m;let g=-1,_=0;while(!0){g=-1,_=0;for(let T of d){let S=a.indexOf(T);if(S!==-1&&(g===-1||S<g))g=S,_=T.length}if(g===-1)break;let v=a.substring(0,g);a=a.substring(g+_);let E=v.trim();if(E.startsWith(c)){let T=E.substring(c.length).trim();try{let S=new Response(T,{headers:e===null||e===void 0?void 0:e.headers,status:e===null||e===void 0?void 0:e.status,statusText:e===null||e===void 0?void 0:e.statusText});yield yield Ne(new yn(S))}catch(S){throw Error(`exception parsing stream chunk ${T}. ${S}`)}}}}}finally{o.releaseLock()}})}async apiCall(e,t,n,o,s){var a,c,d,f,h,m;let g=(a=n===null||n===void 0?void 0:n.httpStatusCodes)!==null&&a!==void 0?a:ow,_=async()=>{let S=jI(o,s),A;try{A=await fetch(e,Object.assign(Object.assign({},t),{signal:S.signal}))}catch(w){throw S.dispose(),w}if(!n||A.ok||!g.includes(A.status))return A;try{await _s(A)}finally{S.dispose()}return A};if(!n)return _();let v=Math.max(1,(c=n.attempts)!==null&&c!==void 0?c:ew),E=Math.round(((d=n.initialDelay)!==null&&d!==void 0?d:tw)*1000),T=Math.max(E,Math.round(((f=n.maxDelay)!==null&&f!==void 0?f:nw)*1000));return Kh.default(_,{retries:v-1,factor:(h=n.expBase)!==null&&h!==void 0?h:rw,minTimeout:E,maxTimeout:T,randomize:((m=n.jitter)!==null&&m!==void 0?m:iw)>0,onFailedAttempt:(S)=>{var A;if(s===null||s===void 0?void 0:s.aborted)throw(A=S.error)!==null&&A!==void 0?A:S}})}getDefaultHeaders(){let e={},t=YI+" "+this.clientOptions.userAgentExtra;return e[XI]=t,e[Us]=t,e[$I]="application/json",e}async getHeadersInternal(e,t){let n=new Headers;if(e&&e.headers)for(let[o,s]of Object.entries(e.headers))n.append(o,s);if((e===null||e===void 0?void 0:e.timeout)&&e.timeout>0)n.append(JI,String(Math.ceil(e.timeout/1000)));return await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){var t;let n="";if(typeof e==="string")n=e.replace(/[/\\]+$/,""),n=(t=n.split(/[/\\]/).pop())!==null&&t!==void 0?t:"";return n}async uploadFile(e,t){var n;let o={};if(t!=null)o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName;if(o.name&&!o.name.startsWith("files/"))o.name=`files/${o.name}`;let s=this.clientOptions.uploader,a=await s.stat(e);o.sizeBytes=String(a.size);let c=(n=t===null||t===void 0?void 0:t.mimeType)!==null&&n!==void 0?n:a.type;if(c===void 0||c==="")throw Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=c;let d={file:o},f=this.getFileName(e),h=z("upload/v1beta/files",d._url),m=await this.fetchUploadUrl(h,o.sizeBytes,o.mimeType,f,d,t===null||t===void 0?void 0:t.httpOptions);return s.upload(e,m,this)}async uploadFileToFileSearchStore(e,t,n){var o;let s=this.clientOptions.uploader,a=await s.stat(t),c=String(a.size),d=(o=n===null||n===void 0?void 0:n.mimeType)!==null&&o!==void 0?o:a.type;if(d===void 0||d==="")throw Error("Can not determine mimeType. Please provide mimeType in the config.");let f=`upload/v1beta/${e}:uploadToFileSearchStore`,h=this.getFileName(t),m={};if(n!=null)Vm(n,m);let g=await this.fetchUploadUrl(f,c,d,h,m,n===null||n===void 0?void 0:n.httpOptions);return s.uploadToFileSearchStore(t,g,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,o,s,a){var c;let d={};if(a)d=a;else d={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`},o?{"X-Goog-Upload-File-Name":o}:{})};let f=await this.request({path:e,body:JSON.stringify(s),httpMethod:"POST",httpOptions:d});if(!f||!(f===null||f===void 0?void 0:f.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let h=(c=f===null||f===void 0?void 0:f.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(h===void 0)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return h}}async function _s(e){var t;if(e===void 0)throw Error("response is undefined");if(!e.ok){let n=e.status,o;if((t=e.headers.get("content-type"))===null||t===void 0?void 0:t.includes("application/json"))o=await e.json();else o={error:{message:await e.text(),code:e.status,status:e.statusText}};let s=JSON.stringify(o);if(n>=400&&n<600)throw new Vi({message:s,status:n});throw Error(s)}}function sw(e,t){if(!t||Object.keys(t).length===0)return;if(e.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 e.body==="string"&&e.body.length>0)try{let a=JSON.parse(e.body);if(typeof a==="object"&&a!==null&&!Array.isArray(a))n=a;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(a){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(a,c){let d=Object.assign({},a);for(let f in c)if(Object.prototype.hasOwnProperty.call(c,f)){let h=c[f],m=d[f];if(h&&typeof h==="object"&&!Array.isArray(h)&&m&&typeof m==="object"&&!Array.isArray(m))d[f]=o(m,h);else{if(m&&h&&typeof m!==typeof h)console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${f}". Original type: ${typeof m}, New type: ${typeof h}. Overwriting.`);d[f]=h}}return d}let s=o(n,t);e.body=JSON.stringify(s)}var aw="mcp_used/unknown",lw=!1;function $m(e){for(let t of e){if(uw(t))return!0;if(typeof t==="object"&&"inputSchema"in t)return!0}return lw}function Jm(e){var t;let n=(t=e[Us])!==null&&t!==void 0?t:"";e[Us]=(n+` ${aw}`).trimStart()}function uw(e){return e!==null&&typeof e==="object"&&e instanceof Ys}function cw(e){return Xn(this,arguments,function*(n,o=100){let s=void 0,a=0;while(a<o){let c=yield Ne(n.listTools({cursor:s}));for(let d of c.tools)yield yield Ne(d),a++;if(!c.nextCursor)break;s=c.nextCursor}})}class Ys{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new Ys(e,t)}async initialize(){var e,t,n,o;if(this.mcpTools.length>0)return;let s={},a=[];for(let h of this.mcpClients)try{for(var c=!0,d=(t=void 0,Er(cw(h))),f;f=await d.next(),e=f.done,!e;c=!0){o=f.value,c=!1;let m=o;a.push(m);let g=m.name;if(s[g])throw Error(`Duplicate function name ${g} found in MCP tools. Please ensure function names are unique.`);s[g]=h}}catch(m){t={error:m}}finally{try{if(!c&&!e&&(n=d.return))await n.call(d)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),_A(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let n of e)if(n.name in this.functionNameToMcpClient){let o=this.functionNameToMcpClient[n.name],s=void 0;if(this.config.timeout)s={timeout:this.config.timeout};let a=await o.callTool({name:n.name,arguments:n.args},void 0,s);t.push({functionResponse:{name:n.name,response:a.isError?{error:a}:a}})}return t}}async function dw(e,t,n){let o=new pm,s;if(n.data instanceof Blob)s=JSON.parse(await n.data.text());else s=JSON.parse(n.data);Object.assign(o,s),t(o)}class Xm{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){var t,n;if(this.apiClient.isVertexAI())throw 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(),a=pw(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${c}`,f=()=>{},h=new Promise((w)=>{f=w}),m=e.callbacks,g=function(){f({})},_=this.apiClient,v={onopen:g,onmessage:(w)=>{dw(_,m.onmessage,w)},onerror:(t=m===null||m===void 0?void 0:m.onerror)!==null&&t!==void 0?t:function(w){},onclose:(n=m===null||m===void 0?void 0:m.onclose)!==null&&n!==void 0?n:function(w){}},E=this.webSocketFactory.create(d,fw(a),v);E.connect(),await h;let A={setup:{model:pe(this.apiClient,e.model)}};return E.send(JSON.stringify(A)),new Km(E,this.apiClient)}}class Km{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw Error("Weighted prompts must be set and contain at least one entry.");let t=A0(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){if(!e.musicGenerationConfig)e.musicGenerationConfig={};let t=T0(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Bn.PLAY)}pause(){this.sendPlaybackControl(Bn.PAUSE)}stop(){this.sendPlaybackControl(Bn.STOP)}resetContext(){this.sendPlaybackControl(Bn.RESET_CONTEXT)}close(){this.conn.close()}}function fw(e){let t={};return e.forEach((n,o)=>{t[o]=n}),t}function pw(e){let t=new Headers;for(let[n,o]of Object.entries(e))t.append(n,o);return t}var hw="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function mw(e,t,n){let o=new fm,s;if(n.data instanceof Blob)s=await n.data.text();else if(n.data instanceof ArrayBuffer)s=new TextDecoder().decode(n.data);else s=n.data;let a=JSON.parse(s);if(e.isVertexAI()){let c=I0(a);Object.assign(o,c)}else Object.assign(o,a);t(o)}class Ym{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Xm(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,n,o,s,a,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),f=this.apiClient.getApiVersion(),h,m=this.apiClient.getHeaders();if(e.config&&e.config.tools&&$m(e.config.tools))Jm(m);let g=yw(m);if(this.apiClient.isVertexAI()){let W=this.apiClient.getProject(),V=this.apiClient.getLocation(),oe=this.apiClient.getApiKey(),se=!!W&&!!V||!!oe;if(this.apiClient.getCustomBaseUrl()&&!se)h=d;else h=`${d}/ws/google.cloud.aiplatform.${f}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(g,h)}else{let W=this.apiClient.getApiKey(),V="BidiGenerateContent",oe="key";if(W===null||W===void 0?void 0:W.startsWith("auth_tokens/")){if(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),f!=="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.");V="BidiGenerateContentConstrained",oe="access_token"}h=`${d}/ws/google.ai.generativelanguage.${f}.GenerativeService.${V}?${oe}=${W}`}let _=()=>{},v=new Promise((W)=>{_=W}),E=e.callbacks,T=function(){var W;(W=E===null||E===void 0?void 0:E.onopen)===null||W===void 0||W.call(E),_({})},S=this.apiClient,A=!1,w=[],P=()=>{},N=new Promise((W)=>{P=W}),D={onopen:T,onmessage:(W)=>{mw(S,(V)=>{if(V.setupComplete&&!ne.setupComplete)ne.setupComplete=V.setupComplete,P({});if(A)E.onmessage(V);else w.push(V)},W)},onerror:(t=E===null||E===void 0?void 0:E.onerror)!==null&&t!==void 0?t:function(W){},onclose:(n=E===null||E===void 0?void 0:E.onclose)!==null&&n!==void 0?n:function(W){}},O=this.webSocketFactory.create(h,_w(g),D);O.connect(),await v;let B=pe(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&B.startsWith("publishers/")){let W=this.apiClient.getProject(),V=this.apiClient.getLocation();if(W&&V)B=`projects/${W}/locations/${V}/`+B}let X={};if(this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0)if(e.config===void 0)e.config={responseModalities:[Ui.AUDIO]};else e.config.responseModalities=[Ui.AUDIO];if((s=e.config)===null||s===void 0?void 0:s.generationConfig)console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let q=(c=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[],Y=[];for(let W of q)if(this.isCallableTool(W)){let V=W;Y.push(await V.tool())}else Y.push(W);if(Y.length>0)e.config.tools=Y;let Z={model:B,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI())X=v0(this.apiClient,Z);else X=E0(this.apiClient,Z);delete X.config;let ne=new Wm(O,this.apiClient);O.send(JSON.stringify(X)),await N,A=!0;for(let W of w)E.onmessage(W);return ne}isCallableTool(e){return"callTool"in e&&typeof e.callTool==="function"}}var gw={turnComplete:!0};class Wm{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let n=[];try{if(n=We(t.turns),!e.isVertexAI())n=n.map((o)=>Cr(o))}catch(o){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(t.functionResponses==null)throw Error("functionResponses is required.");if(!Array.isArray(t.functionResponses))n=[t.functionResponses];else n=t.functionResponses;if(n.length===0)throw Error("functionResponses is required.");for(let s of n){if(typeof s!=="object"||s===null||!("name"in s)||!("response"in s))throw Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw Error(hw)}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},gw),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};if(this.apiClient.isVertexAI())t={realtimeInput:S0(e)};else t={realtimeInput:C0(e)};this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(e.functionResponses==null)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function _w(e){let t={};return e.forEach((n,o)=>{t[o]=n}),t}function yw(e){let t=new Headers;for(let[n,o]of Object.entries(e))t.append(n,o);return t}var wh=10;function Rh(e){var t,n,o;if((t=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||t===void 0?void 0:t.disable)return!0;let s=!1;for(let c of(n=e===null||e===void 0?void 0:e.tools)!==null&&n!==void 0?n:[])if(Kn(c)){s=!0;break}if(!s)return!0;let a=(o=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;if(a&&(a<0||!Number.isInteger(a))||a==0)return 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:",a),!0;return!1}function Kn(e){return"callTool"in e&&typeof e.callTool==="function"}function Ew(e){var t,n,o;return(o=(n=(t=e.config)===null||t===void 0?void 0:t.tools)===null||n===void 0?void 0:n.some((s)=>Kn(s)))!==null&&o!==void 0?o:!1}function Ph(e){var t;let n=[];if(!((t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.tools))return n;return e.config.tools.forEach((o,s)=>{if(Kn(o))return;let a=o;if(a.functionDeclarations&&a.functionDeclarations.length>0)n.push(s)}),n}function Nh(e){var t;return!((t=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||t===void 0?void 0:t.ignoreCallHistory)}class yt extends xt{constructor(e){super();this.apiClient=e,this.embedContent=async(t)=>{if(!this.apiClient.isVertexAI()){if(t.model.includes("gemini-embedding-2"))t.contents=We(t.contents);return await this.embedContentInternal(t)}if(t.model.includes("gemini")&&t.model!=="gemini-embedding-001"||t.model.includes("maas")){let o=We(t.contents);if(o.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let s=Object.assign(Object.assign({},t),{content:o[0],embeddingApiType:Gi.EMBED_CONTENT});return await this.embedContentInternal(s)}else{let o=Object.assign(Object.assign({},t),{embeddingApiType:Gi.PREDICT});return await this.embedContentInternal(o)}},this.generateContent=async(t)=>{var n,o,s,a,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchema(t),!Ew(t)||Rh(t.config))return await this.generateContentInternal(d);let f=Ph(t);if(f.length>0){let E=f.map((T)=>`tools[${T}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${E}.`)}let h,m,g=We(d.contents),_=(s=(o=(n=d.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:wh,v=0;while(v<_){if(h=await this.generateContentInternal(d),!h.functionCalls||h.functionCalls.length===0)break;let E=h.candidates[0].content,T=[];for(let S of(c=(a=t.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[])if(Kn(S)){let w=await S.callTool(h.functionCalls);T.push(...w)}if(v++,m={role:"user",parts:T},d.contents=We(d.contents),d.contents.push(E),d.contents.push(m),Nh(d.config))g.push(E),g.push(m)}if(Nh(d.config))h.automaticFunctionCallingHistory=g;return h},this.generateContentStream=async(t)=>{var n,o,s,a,c;if(this.maybeMoveToResponseJsonSchema(t),Rh(t.config)){let m=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(m)}let d=Ph(t);if(d.length>0){let m=d.map((g)=>`tools[${g}]`).join(", ");throw Error(`Incompatible tools found at ${m}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let f=(s=(o=(n=t===null||t===void 0?void 0:t.config)===null||n===void 0?void 0:n.toolConfig)===null||o===void 0?void 0:o.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,h=(c=(a=t===null||t===void 0?void 0:t.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(f&&!h)throw 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(t)},this.generateImages=async(t)=>{if(!yt.loggedGenerateImagesWarning)yt.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images");return await this.generateImagesInternal(t).then((n)=>{var o;let s,a=[];if(n===null||n===void 0?void 0:n.generatedImages)for(let d of n.generatedImages)if(d&&(d===null||d===void 0?void 0:d.safetyAttributes)&&((o=d===null||d===void 0?void 0:d.safetyAttributes)===null||o===void 0?void 0:o.contentType)==="Positive Prompt")s=d===null||d===void 0?void 0:d.safetyAttributes;else a.push(d);let c;if(s)c={generatedImages:a,positivePromptSafetyAttributes:s,sdkHttpResponse:n.sdkHttpResponse};else c={generatedImages:a,sdkHttpResponse:n.sdkHttpResponse};return c})},this.list=async(t)=>{var n;let a={config:Object.assign(Object.assign({},{queryBase:!0}),t===null||t===void 0?void 0:t.config)};if(this.apiClient.isVertexAI()){if(!a.config.queryBase)if((n=a.config)===null||n===void 0?void 0:n.filter)throw Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");else a.config.filter="labels.tune-type:*"}return new pn(qt.PAGED_ITEM_MODELS,(c)=>this.listInternal(c),await this.listInternal(a),a)},this.editImage=async(t)=>{if(!yt.loggedEditImageWarning)yt.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image");let n={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};if(t.referenceImages){if(t.referenceImages)n.referenceImages=t.referenceImages.map((o)=>o.toReferenceImageAPI())}return await this.editImageInternal(n)},this.upscaleImage=async(t)=>{let n={numberOfImages:1,mode:"upscale"};if(t.config)n=Object.assign(Object.assign({},n),t.config);let o={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:n};return await this.upscaleImageInternal(o)},this.generateVideos=async(t)=>{var n,o,s,a,c,d;if((t.prompt||t.image||t.video)&&t.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");if(t.prompt||t.image||t.video){if(!yt.loggedGenerateVideosWarning)yt.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead.")}if(!this.apiClient.isVertexAI()){if(((n=t.video)===null||n===void 0?void 0:n.uri)&&((o=t.video)===null||o===void 0?void 0:o.videoBytes))t.video={uri:t.video.uri,mimeType:t.video.mimeType};else if(((a=(s=t.source)===null||s===void 0?void 0:s.video)===null||a===void 0?void 0:a.uri)&&((d=(c=t.source)===null||c===void 0?void 0:c.video)===null||d===void 0?void 0:d.videoBytes))t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType}}return await this.generateVideosInternal(t)}}maybeMoveToResponseJsonSchema(e){if(e.config&&e.config.responseSchema){if(!e.config.responseJsonSchema){if(Object.keys(e.config.responseSchema).includes("$schema"))e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema}}return}async processParamsMaybeAddMcpUsage(e){var t,n,o;let s=(t=e.config)===null||t===void 0?void 0:t.tools;if(!s)return e;let a=await Promise.all(s.map(async(d)=>{if(Kn(d))return await d.tool();return d})),c={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(c.config.tools=a,e.config&&e.config.tools&&$m(e.config.tools)){let d=(o=(n=e.config.httpOptions)===null||n===void 0?void 0:n.headers)!==null&&o!==void 0?o:{},f=Object.assign({},d);if(Object.keys(f).length===0)f=this.apiClient.getDefaultHeaders();Jm(f),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:f})}return c}async initAfcToolsMap(e){var t,n,o;let s=new Map;for(let a of(n=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&n!==void 0?n:[])if(Kn(a)){let c=a,d=await c.tool();for(let f of(o=d.functionDeclarations)!==null&&o!==void 0?o:[]){if(!f.name)throw Error("Function declaration name is required.");if(s.has(f.name))throw Error(`Duplicate tool declaration name: ${f.name}`);s.set(f.name,c)}}return s}async processAfcStream(e){var t,n,o;let s=(o=(n=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||n===void 0?void 0:n.maximumRemoteCalls)!==null&&o!==void 0?o:wh,a=!1,c=0,d=await this.initAfcToolsMap(e);return function(f,h,m){return Xn(this,arguments,function*(){var g,_,v,E,T,S;while(c<s){if(a)c++,a=!1;let N=yield Ne(f.processParamsMaybeAddMcpUsage(m)),D=yield Ne(f.generateContentStreamInternal(N)),O=[],B=[];try{for(var A=!0,w=(_=void 0,Er(D)),P;P=yield Ne(w.next()),g=P.done,!g;A=!0){E=P.value,A=!1;let X=E;if(yield yield Ne(X),X.candidates&&((T=X.candidates[0])===null||T===void 0?void 0:T.content)){B.push(X.candidates[0].content);for(let q of(S=X.candidates[0].content.parts)!==null&&S!==void 0?S:[])if(c<s&&q.functionCall){if(!q.functionCall.name)throw Error("Function call name was not returned by the model.");if(!h.has(q.functionCall.name))throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${h.keys()}, missing tool: ${q.functionCall.name}`);else{let Y=yield Ne(h.get(q.functionCall.name).callTool([q.functionCall]));O.push(...Y)}}}}}catch(X){_={error:X}}finally{try{if(!A&&!g&&(v=w.return))yield Ne(v.call(w))}finally{if(_)throw _.error}}if(O.length>0){a=!0;let X=new Hn;X.candidates=[{content:{role:"user",parts:O}}],yield yield Ne(X);let q=[];q.push(...B),q.push({role:"user",parts:O});let Y=We(m.contents).concat(q);m.contents=Y}else break}})}(this,d,e)}async generateContentInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=Ch(this.apiClient,e);return c=z("{model}:generateContent",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=Ih(h),g=new Hn;return Object.assign(g,m),g})}else{let f=Ah(this.apiClient,e);return c=z("{model}:generateContent",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=Sh(h),g=new Hn;return Object.assign(g,m),g})}}async generateContentStreamInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=Ch(this.apiClient,e);return c=z("{model}:streamGenerateContent?alt=sse",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}),a.then(function(m){return Xn(this,arguments,function*(){var g,_,v,E;try{for(var T=!0,S=Er(m),A;A=yield Ne(S.next()),g=A.done,!g;T=!0){E=A.value,T=!1;let w=E,P=Ih(yield Ne(w.json()),e);P.sdkHttpResponse={headers:w.headers};let N=new Hn;Object.assign(N,P),yield yield Ne(N)}}catch(w){_={error:w}}finally{try{if(!T&&!g&&(v=S.return))yield Ne(v.call(S))}finally{if(_)throw _.error}}})})}else{let f=Ah(this.apiClient,e);return c=z("{model}:streamGenerateContent?alt=sse",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(f),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}),a.then(function(m){return Xn(this,arguments,function*(){var g,_,v,E;try{for(var T=!0,S=Er(m),A;A=yield Ne(S.next()),g=A.done,!g;T=!0){E=A.value,T=!1;let w=E,P=Sh(yield Ne(w.json()),e);P.sdkHttpResponse={headers:w.headers};let N=new Hn;Object.assign(N,P),yield yield Ne(N)}}catch(w){_={error:w}}finally{try{if(!T&&!g&&(v=S.return))yield Ne(v.call(S))}finally{if(_)throw _.error}}})})}}async embedContentInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=cS(this.apiClient,e,e),h=EA(e.model)?"{model}:embedContent":"{model}:predict";return c=z(h,f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((m)=>m.json().then((g)=>{let _=g;return _.sdkHttpResponse={headers:m.headers},_})),a.then((m)=>{let g=fS(m,e),_=new As;return Object.assign(_,g),_})}else{let f=uS(this.apiClient,e);return c=z("{model}:batchEmbedContents",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=dS(h),g=new As;return Object.assign(g,m),g})}}async generateImagesInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=vS(this.apiClient,e);return s=z("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=TS(d),h=new Qh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=oS(this.apiClient,e);return s=z("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=sS(d),h=new Zh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=CI(this.apiClient,e);return s=z("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=SI(d),h=new jh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=tI(this.apiClient,e);return s=z("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=nI(d),h=new em;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=uI(this.apiClient,e);return s=z("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=cI(d),h=new tm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=LS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>Ms(h))}else{let f=bS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>Ds(h))}}async listInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=JS(this.apiClient,e);return c=z("{models_url}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=KS(h),g=new Cs;return Object.assign(g,m),g})}else{let f=$S(this.apiClient,e);return c=z("{models_url}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=XS(h),g=new Cs;return Object.assign(g,m),g})}}async update(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=TI(this.apiClient,e);return c=z("{model}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>Ms(h))}else{let f=vI(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>Ds(h))}}async delete(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=tS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=rS(h),g=new Ss;return Object.assign(g,m),g})}else{let f=eS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=nS(h),g=new Ss;return Object.assign(g,m),g})}}async countTokens(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=Q0(this.apiClient,e);return c=z("{model}:countTokens",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=j0(h),g=new Is;return Object.assign(g,m),g})}else{let f=z0(this.apiClient,e);return c=z("{model}:countTokens",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=Z0(h),g=new Is;return Object.assign(g,m),g})}}async computeTokens(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=V0(this.apiClient,e);return s=z("{model}:computeTokens",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=B0(d),h=new nm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=RS(this.apiClient,e);return c=z("{model}:predictLongRunning",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a.then((h)=>{let m=IS(h),g=new bi;return Object.assign(g,m),g})}else{let f=wS(this.apiClient,e);return c=z("{model}:predictLongRunning",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a.then((h)=>{let m=SS(h),g=new bi;return Object.assign(g,m),g})}}}yt.loggedGenerateImagesWarning=!1;yt.loggedEditImageWarning=!1;yt.loggedGenerateVideosWarning=!1;class zm extends xt{constructor(e){super();this.apiClient=e}async getVideosOperation(e){let{operation:t,config:n}=e;if(t.name===void 0||t.name==="")throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s=void 0;if(n&&"httpOptions"in n)s=n.httpOptions;let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async get(e){let{operation:t,config:n}=e;if(t.name===void 0||t.name==="")throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s=void 0;if(n&&"httpOptions"in n)s=n.httpOptions;let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=sA(e);return c=z("{operationName}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),a}else{let f=oA(e);return c=z("{operationName}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json()),a}}async fetchPredictVideosOperationInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=ZT(e);return s=z("{resourceName}:fetchPredictOperation",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}function vw(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Tw(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function Aw(e){let t={},n=l(e,["parts"]);if(n!=null){let s=n;if(Array.isArray(s))s=s.map((a)=>kw(a));u(t,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(t,["role"],o);return t}function Cw(e,t,n){let o={},s=l(t,["expireTime"]);if(n!==void 0&&s!=null)u(n,["expireTime"],s);let a=l(t,["newSessionExpireTime"]);if(n!==void 0&&a!=null)u(n,["newSessionExpireTime"],a);let c=l(t,["uses"]);if(n!==void 0&&c!=null)u(n,["uses"],c);let d=l(t,["liveConnectConstraints"]);if(n!==void 0&&d!=null)u(n,["bidiGenerateContentSetup"],xw(e,d));let f=l(t,["lockAdditionalFields"]);if(n!==void 0&&f!=null)u(n,["fieldMask"],f);return o}function Sw(e,t){let n={},o=l(t,["config"]);if(o!=null)u(n,["config"],Cw(e,o,n));return n}function Iw(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let o=l(e,["mimeType"]);if(o!=null)u(t,["mimeType"],o);return t}function ww(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let o=l(e,["id"]);if(o!=null)u(t,["id"],o);let s=l(e,["name"]);if(s!=null)u(t,["name"],s);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Rw(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],vw(n));let o=l(e,["enableWidget"]);if(o!=null)u(t,["enableWidget"],o);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Pw(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let o=l(e,["timeRangeFilter"]);if(o!=null)u(t,["timeRangeFilter"],o);return t}function Nw(e,t){let n={},o=l(e,["generationConfig"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig"],o);let s=l(e,["responseModalities"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","responseModalities"],s);let a=l(e,["temperature"]);if(t!==void 0&&a!=null)u(t,["setup","generationConfig","temperature"],a);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Xs(g));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let v=l(e,["enableAffectiveDialog"]);if(t!==void 0&&v!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],v);let E=l(e,["systemInstruction"]);if(t!==void 0&&E!=null)u(t,["setup","systemInstruction"],Aw(Le(E)));let T=l(e,["tools"]);if(t!==void 0&&T!=null){let q=zn(T);if(Array.isArray(q))q=q.map((Y)=>Uw(Wn(Y)));u(t,["setup","tools"],q)}let S=l(e,["sessionResumption"]);if(t!==void 0&&S!=null)u(t,["setup","sessionResumption"],Mw(S));let A=l(e,["inputAudioTranscription"]);if(t!==void 0&&A!=null)u(t,["setup","inputAudioTranscription"],A);let w=l(e,["outputAudioTranscription"]);if(t!==void 0&&w!=null)u(t,["setup","outputAudioTranscription"],w);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);if(l(e,["explicitVadSignal"])!==void 0)throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let O=l(e,["avatarConfig"]);if(t!==void 0&&O!=null)u(t,["setup","avatarConfig"],O);let B=l(e,["safetySettings"]);if(t!==void 0&&B!=null){let q=B;if(Array.isArray(q))q=q.map((Y)=>Dw(Y));u(t,["setup","safetySettings"],q)}let X=l(e,["translationConfig"]);if(t!==void 0&&X!=null)u(t,["setup","generationConfig","translationConfig"],X);return n}function xw(e,t){let n={},o=l(t,["model"]);if(o!=null)u(n,["setup","model"],pe(e,o));let s=l(t,["config"]);if(s!=null)u(n,["config"],Nw(s,n));return n}function kw(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let o=l(e,["toolCall"]);if(o!=null)u(t,["toolCall"],o);let s=l(e,["toolResponse"]);if(s!=null)u(t,["toolResponse"],s);let a=l(e,["audioTranscription"]);if(a!=null)u(t,["audioTranscription"],a);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],Iw(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],ww(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],Tw(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let v=l(e,["thought"]);if(v!=null)u(t,["thought"],v);let E=l(e,["thoughtSignature"]);if(E!=null)u(t,["thoughtSignature"],E);let T=l(e,["videoMetadata"]);if(T!=null)u(t,["videoMetadata"],T);let S=l(e,["partMetadata"]);if(S!=null)u(t,["partMetadata"],S);let A=l(e,["mediaProcessing"]);if(A!=null)u(t,["mediaProcessing"],A);return t}function Dw(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["threshold"]);if(o!=null)u(t,["threshold"],o);return t}function Mw(e){let t={},n=l(e,["handle"]);if(n!=null)u(t,["handle"],n);if(l(e,["transparent"])!==void 0)throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Uw(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],Rw(n));let o=l(e,["mcpServers"]);if(o!=null){let g=o;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let s=l(e,["codeExecution"]);if(s!=null)u(t,["codeExecution"],s);let a=l(e,["computerUse"]);if(a!=null)u(t,["computerUse"],a);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],Pw(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function Gw(e){let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];if(typeof o==="object"&&o!=null&&Object.keys(o).length>0){let s=Object.keys(o).map((a)=>`${n}.${a}`);t.push(...s)}else t.push(n)}return t.join(",")}function bw(e,t){let n=null,o=e.bidiGenerateContentSetup;if(typeof o==="object"&&o!==null&&"setup"in o){let a=o.setup;if(typeof a==="object"&&a!==null)e.bidiGenerateContentSetup=a,n=a;else delete e.bidiGenerateContentSetup}else if(o!==void 0)delete e.bidiGenerateContentSetup;let s=e.fieldMask;if(n){let a=Gw(n);if(Array.isArray(t===null||t===void 0?void 0:t.lockAdditionalFields)&&(t===null||t===void 0?void 0:t.lockAdditionalFields.length)===0)if(a)e.fieldMask=a;else delete e.fieldMask;else if((t===null||t===void 0?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&s!==null&&Array.isArray(s)&&s.length>0){let c=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],d=[];if(s.length>0)d=s.map((h)=>{if(c.includes(h))return`generationConfig.${h}`;return h});let f=[];if(a)f.push(a);if(d.length>0)f.push(...d);if(f.length>0)e.fieldMask=f.join(",");else delete e.fieldMask}else delete e.fieldMask}else if(s!==null&&Array.isArray(s)&&s.length>0)e.fieldMask=s.join(",");else delete e.fieldMask;return e}class Qm extends xt{constructor(e){super();this.apiClient=e}async create(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");else{let c=Sw(this.apiClient,e);s=z("auth_tokens",c._url),a=c._query,delete c.config,delete c._url,delete c._query;let d=bw(c,e.config);return o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((f)=>f.json()),o.then((f)=>f)}}}function Lw(e,t){let n={},o=l(e,["force"]);if(t!==void 0&&o!=null)u(t,["_query","force"],o);return n}function qw(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);let o=l(e,["config"]);if(o!=null)Lw(o,t);return t}function Ow(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);return t}function Fw(e,t){let n={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);return n}function Hw(e){let t={},n=l(e,["parent"]);if(n!=null)u(t,["_url","parent"],n);let o=l(e,["config"]);if(o!=null)Fw(o,t);return t}function Vw(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let o=l(e,["nextPageToken"]);if(o!=null)u(t,["nextPageToken"],o);let s=l(e,["documents"]);if(s!=null){let a=s;if(Array.isArray(a))a=a.map((c)=>c);u(t,["documents"],a)}return t}class Zm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t)=>new pn(qt.PAGED_ITEM_DOCUMENTS,(n)=>this.listInternal({parent:t.parent,config:n.config}),await this.listInternal(t),t)}async get(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=Ow(e);return s=z("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>d)}}async delete(e){var t,n;let o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let a=qw(e);o=z("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=Hw(e);return s=z("{parent}/documents",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=Vw(d),h=new om;return Object.assign(h,f),h})}}}class jm extends xt{constructor(e,t=new Zm(e)){super();this.apiClient=e,this.documents=t,this.list=async(n={})=>new pn(qt.PAGED_ITEM_FILE_SEARCH_STORES,(o)=>this.listInternal(o),await this.listInternal(n),n)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw 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,t){if(this.apiClient.isVertexAI())throw Error("This method is only supported in the Gemini Developer client.");let n=new URL(e,"http://dummy.com"),o=n.pathname;if(o.startsWith("/"))o=o.slice(1);if(!o.includes("/media/"))throw Error(`Invalid uri format: ${e}. Expected to contain /media/`);let s={};n.searchParams.forEach((d,f)=>{s[f]=d}),s.alt="media";let a=Object.assign({},t===null||t===void 0?void 0:t.httpOptions),c=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:s,httpOptions:a});if(c instanceof yn){let d=await c.responseInternal.arrayBuffer();return new Uint8Array(d)}else throw Error("Unexpected response type from downloadMedia")}async create(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=kI(this.apiClient,e);return s=z("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>d)}}async get(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=UI(e);return s=z("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>d)}}async delete(e){var t,n;let o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let a=MI(e);o=z("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=FI(e);return s=z("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=HI(d),h=new sm;return Object.assign(h,f),h})}}async uploadToFileSearchStoreInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=VI(e);return s=z("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=BI(d),h=new am;return Object.assign(h,f),h})}}async importFile(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=LI(e);return s=z("{file_search_store_name}:importFile",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),o.then((d)=>{let f=bI(d),h=new Vs;return Object.assign(h,f),h})}}}function Bw(){if("Deno"in globalThis)return!0;return!1}var Pi=void 0;function Tr(){var e,t,n,o,s,a;if(Pi)return Pi;let c=globalThis,d={};if(Bw())d=(o=(n=(t=(e=c.Deno)===null||e===void 0?void 0:e.env)===null||t===void 0?void 0:t.toObject)===null||n===void 0?void 0:n.call(t))!==null&&o!==void 0?o:{};else d=(a=(s=c.process)===null||s===void 0?void 0:s.env)!==null&&a!==void 0?a:{};return Pi=d,Pi}function $w(e){var t,n;let o=Object.assign({},e),s=Tr();if(typeof s.GOOGLE_GENAI_API_VERSION<"u")(t=o.api_version)!==null&&t!==void 0||(o.api_version=s.GOOGLE_GENAI_API_VERSION);if(typeof s.GOOGLE_GENAI_USER_PROJECT<"u")(n=o.user_project)!==null&&n!==void 0||(o.user_project=s.GOOGLE_GENAI_USER_PROJECT);return o}class eg{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return Yw(await this.options.getAuthHeaders(e))}}class tg{beforeCreateRequest(e,t){return Object.assign(Object.assign({},t),{url:Jw(t.url)})}async beforeRequest(e,t){if(kh(t.headers,Kw(e.security_source)),Ww(e,t.headers),Qw(t.headers))return t;let n=await Xw(e.security_source,t.url);return kh(t.headers,n===null||n===void 0?void 0:n.default_headers),zw(t.headers,n),t}}function Jw(e){let[,t,...n]=e.pathname.split("/");if(!t)return e;let o=decodeURIComponent(t);if(!o.includes("/"))return e;let s=new URL(e);return s.pathname=`/${o}/${n.join("/")}`,s}async function Xw(e,t){if(rg(e))return e.resolveGoogleGenAISecurity(t);let n=typeof e==="function"?await e():e;if(ng(n))return xh(n);return xh(void 0)}function Kw(e){var t,n;if(rg(e))return(n=(t=e.getDefaultHeaders)===null||t===void 0?void 0:t.call(e))!==null&&n!==void 0?n:e.defaultHeaders;if(ng(e))return e.default_headers;return}function xh(e){var t,n;let o=Tr(),s=Object.assign(Object.assign({},e),{api_key:(t=e===null||e===void 0?void 0:e.api_key)!==null&&t!==void 0?t:o.GOOGLE_GENAI_API_KEY,access_token:(n=e===null||e===void 0?void 0:e.access_token)!==null&&n!==void 0?n:o.GOOGLE_GENAI_ACCESS_TOKEN});return ig(s)?s:void 0}function Yw(e){var t,n;let o={};for(let[a,c]of e){let d=a.toLowerCase();if(d!=="authorization"&&d!=="x-goog-api-key")o[a]=c}let s={access_token:(t=e.get("authorization"))!==null&&t!==void 0?t:void 0,api_key:(n=e.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(o).length?o:void 0};return ig(s)?s:void 0}function kh(e,t){if(!t)return;for(let[n,o]of new Headers(t))if(e.get(n)===null)e.set(n,o)}function Ww(e,t){if(e.options.user_project!==void 0&&t.get("x-goog-user-project")===null)t.set("x-goog-user-project",e.options.user_project)}function zw(e,t){if(!t)return;if(t.api_key){e.set("x-goog-api-key",t.api_key);return}if(t.access_token)e.set("Authorization",Zw(t.access_token))}function Qw(e){return e.get("authorization")!==null||e.get("x-goog-api-key")!==null}function Zw(e){return e.slice(0,7).toLowerCase()==="bearer "?e:`Bearer ${e}`}function ng(e){return typeof e==="object"&&e!==null}function rg(e){return typeof e==="object"&&e!==null&&"resolveGoogleGenAISecurity"in e&&typeof e.resolveGoogleGenAISecurity==="function"}function ig(e){return e.api_key!==void 0||e.access_token!==void 0||e.default_headers!==void 0}class vn extends Error{constructor(e,t){let n=e;if(t===null||t===void 0?void 0:t.cause)n+=`: ${t.cause}`;super(n,t);if(this.name="HTTPClientError",typeof this.cause>"u")this.cause=t===null||t===void 0?void 0:t.cause}}class Gs extends vn{constructor(){super(...arguments);this.name="UnexpectedClientError"}}class mr extends vn{constructor(){super(...arguments);this.name="InvalidRequestError"}}class Ws extends vn{constructor(){super(...arguments);this.name="RequestAbortedError"}}class zs extends vn{constructor(){super(...arguments);this.name="RequestTimeoutError"}}class Qs extends vn{constructor(){super(...arguments);this.name="ConnectionError"}}class vt extends Error{constructor(e,t){var n,o,s,a;super(e);this.statusCode=(n=t===null||t===void 0?void 0:t.response)===null||n===void 0?void 0:n.status,this.body=(o=t===null||t===void 0?void 0:t.body)!==null&&o!==void 0?o:"",this.headers=(s=t===null||t===void 0?void 0:t.response)===null||s===void 0?void 0:s.headers,this.contentType=((a=t===null||t===void 0?void 0:t.response)===null||a===void 0?void 0:a.headers.get("content-type"))||"",this.rawResponse=t===null||t===void 0?void 0:t.response,this.name="GoogleGenAiError"}}class og extends Error{}class Je extends og{constructor(e,t,n,o){super(Je.makeMessage(e,t,n));this.status=e,this.headers=o,this.error=t,this.statusCode=e,this.body=Mh(t),this.contentType=(o===null||o===void 0?void 0:o.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,t,n){var o;let s=t&&nR(t)&&typeof t.message==="string"?t.message:void 0,a=Mh(t),c=(o=s!==null&&s!==void 0?s:n)!==null&&o!==void 0?o:a||"An error occurred";return`${e?`${e} `:""}${c}`}static generate(e,t,n,o){if(!e||!o)return new Ar({message:n,cause:t instanceof Error?t:void 0});if(e===400)return new lg(e,t,n,o);if(e===401)return new ug(e,t,n,o);if(e===403)return new cg(e,t,n,o);if(e===404)return new dg(e,t,n,o);if(e===409)return new fg(e,t,n,o);if(e===422)return new pg(e,t,n,o);if(e===429)return new hg(e,t,n,o);if(e>=500)return new mg(e,t,n,o);return new Je(e,t,n,o)}}class sg extends Je{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ar extends Je{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);this.cause=t}}class ag extends Ar{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."})}}class lg extends Je{}class ug extends Je{}class cg extends Je{}class dg extends Je{}class fg extends Je{}class pg extends Je{}class hg extends Je{}class mg extends Je{}function $n(e){if(rR(e))return e;if(e instanceof vt)return jw(e);if(e instanceof vn)return eR(e);return e}function jw(e){let t=tR(e),n=Je.generate(e.statusCode,t,e.message,e.headers);return pr(n,"body",e.body),pr(n,"contentType",e.contentType),pr(n,"rawResponse",e.rawResponse),pr(n,"statusCode",e.statusCode),pr(n,"cause",e),n}function eR(e){if(e instanceof zs)return new ag({message:e.message});if(e instanceof Ws)return new sg({message:e.message});if(e instanceof Qs)return new Ar({message:e.message,cause:e});return new Ar({message:e.message,cause:e})}function tR(e){let t=Dh(e,"data$");if(t&&typeof t==="object")return t;try{let o=JSON.parse(e.body);if(o&&typeof o==="object")return o}catch(o){}let n=Dh(e,"error");return n&&typeof n==="object"?n:void 0}function Dh(e,t){return e&&typeof e==="object"?e[t]:void 0}function Mh(e){if(!e)return"";try{return JSON.stringify(e)}catch(t){return String(e)}}function nR(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function rR(e){return typeof e==="object"&&e!==null?Je.prototype.isPrototypeOf(e):!1}function pr(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!1})}function iR(e){let t=new tg;e.registerBeforeCreateRequestHook(t),e.registerBeforeRequestHook(t)}class bs{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let t of e){if("sdkInit"in t)this.registerSDKInitHook(t);if("beforeCreateRequest"in t)this.registerBeforeCreateRequestHook(t);if("beforeRequest"in t)this.registerBeforeRequestHook(t);if("afterSuccess"in t)this.registerAfterSuccessHook(t);if("afterError"in t)this.registerAfterErrorHook(t)}iR(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((t,n)=>n.sdkInit(t),e)}beforeCreateRequest(e,t){let n=t;for(let o of this.beforeCreateRequestHooks)n=o.beforeCreateRequest(e,n);return n}async beforeRequest(e,t){let n=t;for(let o of this.beforeRequestHooks)n=await o.beforeRequest(e,n);return n}async afterSuccess(e,t){let n=t;for(let o of this.afterSuccessHooks)n=await o.afterSuccess(e,n);return n}async afterError(e,t,n){let o=t,s=n;for(let a of this.afterErrorHooks){let c=await a.afterError(e,o,s);o=c.response,s=c.error}return{response:o,error:s}}}function Uh(e){return{ok:!0,value:e}}function Lt(e){return{ok:!1,error:e}}function Zs(e){return btoa(String.fromCodePoint(...e))}function oR(e){return new TextEncoder().encode(e)}function sR(e){return Zs(oR(e))}var aR=Object.prototype.hasOwnProperty;function ve(e,t){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(s={}){return e.replace(n,function(a,c){if(!aR.call(s,c))throw Error(`Parameter '${c}' is required`);let d=s[c];if(typeof d!=="string"&&typeof d!=="number")throw Error(`Parameter '${c}' must be a string or number`);return`${d}`}).replace(/^\/+/,"")}}var Gh=["https://generativelanguage.googleapis.com"];function lR(e){var t;let n=e.server_url,o={};if(!n){let a=(t=e.server_idx)!==null&&t!==void 0?t:0;if(a<0||a>=Gh.length)throw Error(`Invalid server index ${a}`);n=Gh[a]||""}let s=ve(n)(o);return new URL(s)}var uR={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function cR(...e){let t=[];for(let n of e)if(n)t.push(n);switch(t.length){case 0:case 1:return t[0]||null;default:if("any"in AbortSignal&&typeof AbortSignal.any==="function")return AbortSignal.any(t);return dR(t)}}function dR(e){let t=new AbortController,n=t.signal;if(!e.length)return t.signal;if(e.length===1)return e[0]||t.signal;for(let c of e)if(c.aborted)return c;function o(){t.abort(this.reason),a()}let s=[];function a(){for(let c of s){let d=c.deref();if(d)d.removeEventListener("abort",o)}}for(let c of e)s.push(new WeakRef(c)),c.addEventListener("abort",o);return n}function Ae(e){let t={};for(let[n,o]of Object.entries(e))if(typeof o<"u")t[n]=o;return t}function cn(e){if(e===null||typeof e!=="object")return!1;if(Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;try{return Object.getPrototypeOf(t)===null}catch(n){return!1}}function fR(e){return(t,n,o)=>{let s="",a=(o===null||o===void 0?void 0:o.explode)?_g(t,n):[[t,n]];if(a.every(([h,m])=>m==null))return;let c=(h)=>(o===null||o===void 0?void 0:o.charEncoding)==="percent"?encodeURIComponent(h):h,d=(h)=>c(yg(h)),f=c(e);return a.forEach(([h,m])=>{var g,_;let v="",E=null;if(m==null)return;else if(Array.isArray(m))E=(g=vg(m,(T)=>`${d(T)}`))===null||g===void 0?void 0:g.join(f);else if(cn(m))E=(_=Tg(Object.entries(m),([T,S])=>`${c(T)}${f}${d(S)}`))===null||_===void 0?void 0:_.join(f);else E=`${d(m)}`;if(E==null)return;if(v=`${c(h)}=${E}`,!v||v==="=")return;s+=`&${v}`}),s.slice(1)}}var gg=fR(",");function Ft(e,t,n){if(typeof t>"u")return;let o=(a)=>(n===null||n===void 0?void 0:n.charEncoding)==="percent"?encodeURIComponent(a):a,s=o(JSON.stringify(t,Eg));return(n===null||n===void 0?void 0:n.explode)?s:`${o(e)}=${s}`}var re=(e,t,n)=>{let o="",s=(n===null||n===void 0?void 0:n.explode)?_g(e,t):[[e,t]];if(s.every(([d,f])=>f==null))return;let a=(d)=>(n===null||n===void 0?void 0:n.charEncoding)==="percent"?encodeURIComponent(d):d,c=(d)=>a(yg(d));return s.forEach(([d,f])=>{var h;let m="";if(f==null)return;else if(Array.isArray(f))m=(h=vg(f,(g)=>`${c(g)}`))===null||h===void 0?void 0:h.join(",");else if(cn(f)){let g=Tg(Object.entries(f),([_,v])=>`,${a(_)},${c(v)}`);m=g===null||g===void 0?void 0:g.join("").slice(1)}else m=`${(n===null||n===void 0?void 0:n.explode)&&cn(t)?`${d}=`:""}${c(f)}`;o+=m?`,${m}`:""}),o.slice(1)};function _g(e,t){if(Array.isArray(t))return t.map((n)=>[e,n]);else if(cn(t))return Object.entries(t!==null&&t!==void 0?t:{}).map(([o,s])=>[o,s]);else return[[e,t]]}function yg(e){if(e==null)return"";else if(e instanceof Date)return e.toISOString();else if(e instanceof Uint8Array)return Zs(e);else if(typeof e==="object")return JSON.stringify(e,Eg);return`${e}`}function Eg(e,t){if(t instanceof Uint8Array)return Zs(t);else return t}function vg(e,t){let n=e.reduce((o,s)=>{if(s==null)return o;let a=t(s);if(a==null)return o;return o.push(a),o},[]);return n.length?n:null}function Tg(e,t){let n=[];for(let[o,s]of e){if(s==null)continue;let a=t([o,s]);if(a==null)continue;n.push(a)}return n.length?n:null}function pR(...e){return e.filter(Boolean).join("&")}function hR(e){return function(n,o){var s,a,c;let d=Object.assign(Object.assign({},o),{explode:(s=o===null||o===void 0?void 0:o.explode)!==null&&s!==void 0?s:!0,charEncoding:(a=o===null||o===void 0?void 0:o.charEncoding)!==null&&a!==void 0?a:"percent"}),f=new Set((c=o===null||o===void 0?void 0:o.allowEmptyValue)!==null&&c!==void 0?c:[]),h=Object.entries(n).map(([m,g])=>{if(f.has(m)){if(g===void 0||g===null||g===""||Array.isArray(g)&&g.length===0)return`${encodeURIComponent(m)}=`}return e(m,g,d)});return pR(...h)}}var hn=hR(gg),mR=(e,t)=>{if(t==null)return fetch(e);else return fetch(e,t)};class js{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||mR}async request(e){let t=e;for(let n of this.requestHooks){let o=await n(t);if(o)t=o}try{let n=await this.fetcher(t);for(let o of this.responseHooks)await o(n,t);return n}catch(n){for(let o of this.requestErrorHooks)await o(n,t);throw n}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let t;if(e[0]==="beforeRequest")t=this.requestHooks;else if(e[0]==="requestError")t=this.requestErrorHooks;else if(e[0]==="response")t=this.responseHooks;else throw Error(`Invalid hook type: ${e[0]}`);let n=t.findIndex((o)=>o===e[1]);if(n>=0)t.splice(n,1);return this}clone(){let e=new js(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}}var bh=/\s*;\s*/g;function Vn(e,t){var n;if(t==="*")return!0;let o=((n=e.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";o=o.toLowerCase();let s=t.toLowerCase().trim().split(bh),[a="",...c]=s;if(a.split("/").length!==2)return!1;let d=o.split(bh),[f="",...h]=d,[m="",g=""]=f.split("/");if(!m||!g)return!1;if(a!=="*/*"&&f!==a&&`${m}/*`!==a&&`*/${g}`!==a)return!1;if(h.length<c.length)return!1;let _=new Set(h);for(let v of c)if(!_.has(v))return!1;return!0}var gR=new RegExp("^[0-9]xx$","i");function _e(e,t){let n=`${e.status}`,o=Array.isArray(t)?t:[t];if(!o.length)return!1;return o.some((s)=>{let a=`${s}`;if(a==="default")return!0;if(!gR.test(`${a}`))return a===n;let c=a.charAt(0);if(!c)throw Error("Invalid status code range");let d=n.charAt(0);if(!d)throw Error(`Invalid response status code: ${n}`);return d===c})}function _R(e,t,n){return _e(e,t)&&Vn(e,n)}function Ag(e){if(typeof e!=="object"||e==null)return!1;let t=e instanceof TypeError&&e.message.toLowerCase().startsWith("failed to fetch"),n=e instanceof TypeError&&e.message.toLowerCase().startsWith("fetch failed"),o="name"in e&&e.name==="ConnectionError",s="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnreset";return t||n||s||o}function Cg(e){if(typeof e!=="object"||e==null)return!1;let t="name"in e&&e.name==="TimeoutError",n="code"in e&&e.code===23,o="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnaborted";return t||n||o}function yR(e){if(typeof e!=="object"||e==null)return!1;let t="name"in e&&e.name==="AbortError",n="code"in e&&e.code===20,o="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnaborted";return t||n||o}var Lh={initialInterval:500,maxInterval:60000,exponent:1.5,maxElapsedTime:3600000};class Ir extends Error{constructor(e,t){let n=e;if(t===null||t===void 0?void 0:t.cause)n+=`: ${t.cause}`;super(n,t);if(this.name="PermanentError",typeof this.cause>"u")this.cause=t===null||t===void 0?void 0:t.cause;Object.setPrototypeOf(this,Ir.prototype)}}class dn extends Error{constructor(e,t){super(e);this.response=t,this.name="TemporaryError",Object.setPrototypeOf(this,dn.prototype)}}async function ER(e,t){var n;switch(t.config.strategy){case"backoff":return AR(qh(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),(n=t.config.backoff)!==null&&n!==void 0?n:Lh);case"attempt-count-backoff":return CR(qh(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),Object.assign(Object.assign({},Lh),t.config.backoff),t.config);default:return await e(0)}}function qh(e,t){return async(n)=>{try{let o=await e(n);if(TR(o,t.statusCodes))throw new dn("Response failed with retryable status code",o);return o}catch(o){if(o instanceof dn)throw o;if(t.retryConnectionErrors&&(Cg(o)||Ag(o)))throw o;throw new Ir("Permanent error",{cause:o})}}}var vR=new RegExp("^[0-9]xx$","i");function TR(e,t){let n=`${e.status}`;return t.some((o)=>{if(!vR.test(o))return o===n;let s=o.charAt(0);if(!s)throw Error("Invalid status code range");let a=n.charAt(0);if(!a)throw Error(`Invalid response status code: ${n}`);return a===s})}async function AR(e,t){let{maxElapsedTime:n,initialInterval:o,exponent:s,maxInterval:a}=t,c=Date.now(),d=0;while(!0)try{return await e(d)}catch(f){if(f instanceof Ir)throw f.cause;if(Date.now()-c>n){if(f instanceof dn)return f.response;throw f}let m=0;if(f instanceof dn)m=Sg(f.response);if(m<=0)m=o*Math.pow(d,s)+Math.random()*1000;let g=Math.min(m,a);await Ig(g),d++}}async function CR(e,t,n){let o=0;while(!0)try{return await e(o)}catch(s){if(s instanceof Ir)throw s.cause;if(o>=n.maxRetries){if(s instanceof dn)return s.response;throw s}let a=0;if(s instanceof dn)a=Sg(s.response);if(a<=0)a=t.initialInterval*Math.pow(t.exponent,o)*(1-Math.random()*0.25);let c=Math.min(a,t.maxInterval);await Ig(c),o++}}function Sg(e){let t=e.headers.get("retry-after-ms");if(t){let a=Number(t);if(Number.isFinite(a)&&a>=0)return a}let n=e.headers.get("retry-after")||"";if(!n)return 0;let o=Number(n);if(Number.isInteger(o))return o*1000;let s=Date.parse(n);if(Number.isInteger(s)){let a=s-Date.now();return a>0?Math.ceil(a):0}return 0}async function Ig(e){return new Promise((t)=>setTimeout(t,e))}var Ni=typeof globalThis>"u"?null:globalThis,SR=typeof Ni==="object"&&Ni!=null&&"importScripts"in Ni&&typeof Ni.importScripts==="function",IR=SR||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window==="object"&&typeof window.document<"u";class mn{constructor(e={}){let t=e;if(typeof t==="object"&&t!=null&&"hooks"in t&&t.hooks instanceof bs)this._hooks=t.hooks;else this._hooks=new bs;let n=new js;e.http_client=e.http_client||n,e=this._hooks.sdkInit(e);let o=lR(e);if(o)o.pathname=o.pathname.replace(/\/+$/,"")+"/";if(this._baseURL=o,this._httpClient=e.http_client||n,this._options=Object.assign(Object.assign({},$w(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Tr().GOOGLE_GENAI_DEBUG)this._logger=console}_createRequest(e,t,n){var o,s,a,c,d;let{method:f,path:h,query:m,headers:g,security:_}=t,v=(o=t.baseURL)!==null&&o!==void 0?o:this._baseURL;if(!v)return Lt(new mr("No base URL provided for operation"));let E=new URL(v),T;if(h){if(E.pathname=E.pathname.replace(/\/+$/,"")+"/",T=new URL(h,E),!T.search&&E.search)T.search=E.search}else T=E;T.hash="";let S=(W,V)=>{if(!V)return W;let oe=new Set(V.split("&").filter((xe)=>xe!=="").map((xe)=>{var Ue;return(Ue=xe.split("=")[0])!==null&&Ue!==void 0?Ue:""}));return[...W.split("&").filter((xe)=>{var Ue;return xe!==""&&!oe.has((Ue=xe.split("=")[0])!==null&&Ue!==void 0?Ue:"")}),V].join("&")},A=(W)=>Object.entries(W).map(([V,oe])=>{if(oe==null)return;let se=cn(oe)?JSON.stringify(oe):oe;return gg(V,se,{explode:Array.isArray(se),charEncoding:"percent"})}).filter((V)=>typeof V<"u").join("&"),w=[m||"",A((n===null||n===void 0?void 0:n.extra_query)||{}),A((_===null||_===void 0?void 0:_.queryParams)||{})].reduce(S,T.search.slice(1));if(w)T.search=`?${w}`;let P=new Headers(g),N=_===null||_===void 0?void 0:_.basic.username,D=_===null||_===void 0?void 0:_.basic.password;if(N!=null||D!=null){let W=sR([N||"",D||""].join(":"));P.set("Authorization",`Basic ${W}`)}let O=new Headers((_===null||_===void 0?void 0:_.headers)||{});for(let[W,V]of O)P.set(W,V);let B=P.get("cookie")||"";for(let[W,V]of Object.entries((_===null||_===void 0?void 0:_.cookies)||{}))B+=`; ${W}=${V}`;B=B.startsWith("; ")?B.slice(2):B,P.set("cookie",B);let X=new Headers((s=n===null||n===void 0?void 0:n.headers)!==null&&s!==void 0?s:(a=n===null||n===void 0?void 0:n.fetch_options)===null||a===void 0?void 0:a.headers);for(let[W,V]of X)P.set(W,V);if(!IR)P.set((c=t.uaHeader)!==null&&c!==void 0?c:"user-agent",(d=t.userAgent)!==null&&d!==void 0?d:uR.userAgent);let q=t.body,Y=Object.fromEntries(Object.entries((n===null||n===void 0?void 0:n.extra_body)||{}).filter(([,W])=>typeof W<"u"));if(Object.keys(Y).length>0){let W=new Headers(g).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(W)||typeof q!=="string"&&q!=null)return Lt(new mr("extra_body can only be merged into JSON object request bodies"));let oe;try{oe=q?JSON.parse(q):{}}catch(se){return Lt(new mr("extra_body can only be merged into JSON object request bodies",{cause:se}))}if(!cn(oe))return Lt(new mr("extra_body can only be merged into JSON object request bodies"));q=JSON.stringify(Object.assign(Object.assign({},oe),Y)),P.delete("content-length")}let Z=Object.assign(Object.assign({},n===null||n===void 0?void 0:n.fetch_options),n);if(!(Z===null||Z===void 0?void 0:Z.signal)&&t.timeout_ms!=null&&t.timeout_ms>0)e.timeout_ms=t.timeout_ms;if(t.body instanceof ReadableStream)Object.assign(Z,{duplex:"half"});let ne;try{ne=this._hooks.beforeCreateRequest(e,{url:T,options:Object.assign(Object.assign({},Z),{body:q!==null&&q!==void 0?q:null,headers:P,method:f})})}catch(W){return Lt(new Gs("Create request hook failed to execute",{cause:W}))}return Uh(new Request(ne.url,ne.options))}async _do(e,t){let{context:n,isErrorStatusCode:o}=t,s=n.timeout_ms;return ER(async()=>{var a;let c=e.clone(),d=c;if(s!=null&&s>0){let m=AbortSignal.timeout(s),g=(a=cR(c.signal,m))!==null&&a!==void 0?a:m;d=new Request(c,{signal:g})}let f=await this._hooks.beforeRequest(n,d);await wR(this._logger,f).catch((m)=>{var g;return(g=this._logger)===null||g===void 0?void 0:g.log("Failed to log request:",m)});let h=await this._httpClient.request(f);try{if(o(h.status)){let m=await this._hooks.afterError(n,h,null);if(m.error)throw m.error;h=m.response||h}else h=await this._hooks.afterSuccess(n,h)}finally{await RR(this._logger,h,f).catch((m)=>{var g;return(g=this._logger)===null||g===void 0?void 0:g.log("Failed to log response:",m)})}return h},{config:t.retryConfig,statusCodes:t.retryCodes}).then((a)=>Uh(a),(a)=>{switch(!0){case yR(a):return Lt(new Ws("Request aborted by client",{cause:a}));case Cg(a):return Lt(new zs("Request timed out",{cause:a}));case Ag(a):return Lt(new Qs("Unable to make request",{cause:a}));default:return Lt(new Gs("Unexpected HTTP client error",{cause:a}))}})}}var wg=/^(application|text)\/([^+]+\+)*json.*/,Oh=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function wR(e,t){if(!e)return;let n=t.headers.get("content-type"),o=(n===null||n===void 0?void 0:n.split(";")[0])||"";e.group(`> Request: ${t.method} ${t.url}`),e.group("Headers:");for(let[s,a]of t.headers.entries())e.log(`${s}: ${a}`);switch(e.groupEnd(),e.group("Body:"),!0){case wg.test(o):e.log(await t.clone().json());break;case o.startsWith("text/"):e.log(await t.clone().text());break;case o==="multipart/form-data":{let s=await t.clone().formData();for(let[a,c]of s){let d=c instanceof Blob?"<Blob>":c;e.log(`${a}: ${d}`)}break}default:e.log(`<${n}>`);break}e.groupEnd(),e.groupEnd()}async function RR(e,t,n){if(!e)return;let o=t.headers.get("content-type"),s=(o===null||o===void 0?void 0:o.split(";")[0])||"";e.group(`< Response: ${n.method} ${n.url}`),e.log("Status Code:",t.status,t.statusText),e.group("Headers:");for(let[a,c]of t.headers.entries())e.log(`${a}: ${c}`);switch(e.groupEnd(),e.group("Body:"),!0){case(Vn(t,"application/json")||wg.test(s)&&!Oh.test(s)):e.log(await t.clone().json());break;case(Vn(t,"application/jsonl")||Oh.test(s)):case Vn(t,"text/event-stream"):e.log(`<${o}>`);break;case Vn(t,"text/*"):e.log(await t.clone().text());break;case Vn(t,"multipart/form-data"):{let a=await t.clone().formData();for(let[c,d]of a){let f=d instanceof Blob?"<Blob>":d;e.log(`${c}: ${f}`)}break}default:e.log(`<${o}>`);break}e.groupEnd(),e.groupEnd()}class Ls extends vt{constructor(e,t){if(e)e+=": ";e+=`Status ${t.response.status}`;let n=t.response.headers.get("content-type")||'""';if(n!=="application/json")e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`;let o=t.body||'""';e+=o.length>100?`
|
|
36
|
-
`:". ";let
|
|
37
|
-
`);else if(o)return;return t(d)}var DR={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function fn(e,t,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:e,errorClass:t})}function Pe(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function Ng(e,t,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:e}),t?{sse:t}:{})}function MR(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function ie(e){return{enc:"fail",codes:e}}function Ce(...e){return async function(n,o,s){let a,c;for(let _ of e){let{codes:v}=_,E="ctype"in _?_.ctype:DR[_.enc];if(E&&_R(n,v,E)){c=_;break}else if(!E&&_e(n,v)){c=_;break}}if(!c)return[{ok:!1,error:new Ls("Unexpected Status or Content-Type",{response:n,request:o,body:await n.text().catch(()=>"")})},a];let d=c.enc,f="";switch(d){case"json":f=await n.text();try{a=JSON.parse(f)}catch(_){if(!("err"in c))throw _;a=f}break;case"jsonl":a=n.body;break;case"bytes":a=new Uint8Array(await n.arrayBuffer());break;case"stream":a=n.body;break;case"text":f=await n.text(),a=f;break;case"sse":if(n.body){let _="sse"in c&&c.sse||{};a=PR(n.body,_)}else a=null;break;case"nil":f=await n.text(),a=void 0;break;case"fail":f=await n.text(),a=f;break;default:throw Error(`Unsupported response type: ${d}`)}if(c.enc==="fail")return[{ok:!1,error:new Ls("API error occurred",{request:o,response:n,body:f})},a];let h=c.key||(s===null||s===void 0?void 0:s.resultKey),m,g=c.hdrs?{headers:GR(n.headers)}:null;if("err"in c)m=Object.assign(Object.assign(Object.assign({},s===null||s===void 0?void 0:s.extraFields),g),cn(a)?a:null);else if(h)m=Object.assign(Object.assign(Object.assign({},s===null||s===void 0?void 0:s.extraFields),g),{[h]:a});else if(c.hdrs)m=Object.assign(Object.assign(Object.assign({},s===null||s===void 0?void 0:s.extraFields),g),cn(a)?a:null);else m=a;if("err"in c)return[{ok:!1,error:c.errorClass?new c.errorClass(m,{request:o,response:n,body:f}):m},a];return[{ok:!0,value:m},a]}}var UR=/, */;function GR(e){let t={};for(let[n,o]of e.entries())t[n]=o.split(UR);return t}var Hh={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"};class qi extends Error{constructor(e,t){super(t);this.code=e,this.name="SecurityError"}static incomplete(){return new qi(Hh.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new qi(Hh.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}}function bR(...e){let t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=e.find((o)=>o.every((s)=>{if(s.value==null)return!1;else if(s.type==="http:basic")return s.value.username!=null||s.value.password!=null;else if(s.type==="http:custom")return null;else if(s.type==="oauth2:password")return typeof s.value==="string"&&!!s.value;else if(s.type==="oauth2:client_credentials"){if(typeof s.value=="string")return!!s.value;return s.value.client_id!=null||s.value.client_secret!=null}else if(typeof s.value==="string")return!!s.value;else throw Error(`Unrecognized security type: ${s.type} (value type: ${typeof s.value})`)}));if(n==null)return null;return n.forEach((o)=>{if(o.value==null)return;let{type:s}=o;switch(s){case"apiKey:header":t.headers[o.fieldName]=o.value;break;case"apiKey:query":t.queryParams[o.fieldName]=o.value;break;case"apiKey:cookie":t.cookies[o.fieldName]=o.value;break;case"http:basic":LR(t,o);break;case"http:custom":break;case"http:bearer":xi(t,o);break;case"oauth2":xi(t,o);break;case"oauth2:password":xi(t,o);break;case"oauth2:client_credentials":break;case"openIdConnect":xi(t,o);break;default:throw qi.unrecognizedType(s)}}),t}function LR(e,t){if(t.value==null)return;e.basic=t.value}function xi(e,t){if(typeof t.value!=="string"||!t.value)return;let n=t.value;if(n.slice(0,7).toLowerCase()!=="bearer ")n=`Bearer ${n}`;if(t.fieldName!==void 0)e.headers[t.fieldName]=n}function Se(e,t){var n,o;let s=[[{fieldName:"accessToken",type:"http:custom",value:(n=e===null||e===void 0?void 0:e.access_token)!==null&&n!==void 0?n:Tr().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(o=e===null||e===void 0?void 0:e.api_key)!==null&&o!==void 0?o:Tr().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:e===null||e===void 0?void 0:e.default_headers}]];return bR(...s)}async function Ie(e){if(e==null)return;return typeof e==="function"?e():e}var xg;class he{constructor(e,t){this[xg]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=t!==null&&t!==void 0?t:null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([t])=>t)}then(e,t){return this._promise.then(e?([n])=>e(n):void 0,t)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,n])=>n)).then((n)=>{if(!n.response)throw Error("APIPromise.asResponse: response unavailable");return n.response})}async withResponse(){let[[e],t]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:t}}_thenUnwrap(e){var t;let n=this._promise.then(([o,s])=>[e(o),s]);return n.catch(()=>{}),new he(n,(t=this._callSource)!==null&&t!==void 0?t:void 0)}}xg=Symbol.toStringTag;function Te(e){let t=e.$inspect(),n=t.then(([s,a])=>{if(!s.ok)throw s.error;return[s.value,a]}),o=t.then(([s,a])=>{var c;if(!s.ok&&!((c=a.response)===null||c===void 0?void 0:c.ok))throw s.error;return a});return n.catch(()=>{}),o.catch(()=>{}),new he(n,o)}function kg(e,t,n,o){return new he(qR(e,t,n,o))}async function qR(e,t,n,o){var s,a,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/agents")(m),_=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function Dg(e,t,n,o){return new he(OR(e,t,n,o))}async function OR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/agents/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"DELETE",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function Mg(e,t,n,o){return new he(FR(e,t,n,o))}async function FR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/agents/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function Ug(e,t,n,o,s,a){return new he(HR(e,t,n,o,s,a))}async function HR(e,t,n,o,s,a){var c,d,f;let m={api_version:t,page_size:n,page_token:o,parent:s},g=null,_={api_version:re("api_version",(c=m===null||m===void 0?void 0:m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"})},v=ve("/{api_version}/agents")(_),E=hn({page_size:m===null||m===void 0?void 0:m.page_size,page_token:m===null||m===void 0?void 0:m.page_token,parent:m===null||m===void 0?void 0:m.parent}),T=new Headers(Ae({Accept:"application/json"})),S=await Ie(e._options.security),A=Se(S),w={options:e._options,base_url:(f=(d=a===null||a===void 0?void 0:a.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(a===null||a===void 0?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(a===null||a===void 0?void 0:a.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(w,{security:A,method:"GET",baseURL:a===null||a===void 0?void 0:a.server_url,path:v,headers:T,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(a===null||a===void 0?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:w,isErrorStatusCode:(X)=>_e({status:X},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let O=D.value,[B]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(O,N);if(!B.ok)return[B,{status:"complete",request:N,response:O}];return[B,{status:"complete",request:N,response:O}]}class Gg extends mn{list(e,t){return Te(Ug(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,e===null||e===void 0?void 0:e.parent,t))}create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Te(kg(this,o,n,t))}delete(e,t,n){return Te(Dg(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Te(Mg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function bg(e,t,n,o){return new he(VR(e,t,n,o))}async function VR(e,t,n,o){var s,a,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/environments")(m),_=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function Lg(e,t,n,o){return new he(BR(e,t,n,o))}async function BR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/environments/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"DELETE",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function qg(e,t,n,o){return new he($R(e,t,n,o))}async function $R(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/environments/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function Og(e,t,n,o,s){return new he(JR(e,t,n,o,s))}async function JR(e,t,n,o,s){var a,c,d;let h={api_version:t,page_size:n,page_token:o},m=null,g={api_version:re("api_version",(a=h===null||h===void 0?void 0:h.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/environments")(g),v=hn({page_size:h===null||h===void 0?void 0:h.page_size,page_token:h===null||h===void 0?void 0:h.page_token}),E=new Headers(Ae({Accept:"application/json"})),T=await Ie(e._options.security),S=Se(T),A={options:e._options,base_url:(d=(c=s===null||s===void 0?void 0:s.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:S,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},w=e._createRequest(A,{security:S,method:"GET",baseURL:s===null||s===void 0?void 0:s.server_url,path:_,headers:E,query:v,body:null,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!w.ok)return[w,{status:"invalid"}];let P=w.value,N=await e._do(P,{context:A,isErrorStatusCode:(B)=>_e({status:B},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!N.ok)return[N,{status:"request-error",request:P}];let D=N.value,[O]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(D,P);if(!O.ok)return[O,{status:"complete",request:P,response:D}];return[O,{status:"complete",request:P,response:D}]}function Fg(e,t,n,o,s,a,c,d){return new he(XR(e,t,n,o,s,a,c,d))}async function XR(e,t,n,o,s,a,c,d){var f,h,m;let _={environment:t,path:n,api_version:o,page_size:s,page_token:a,recursive:c},v=null,E={api_version:re("api_version",(f=_.api_version)!==null&&f!==void 0?f:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:re("environment",_.environment,{explode:!1,charEncoding:"percent"}),path:re("path",_.path,{explode:!1,charEncoding:"percent"})},T=ve("/{api_version}/environments/{environment}/files/{path}")(E),S=hn({page_size:_.page_size,page_token:_.page_token,recursive:_.recursive}),A=new Headers(Ae({Accept:"application/json"})),w=await Ie(e._options.security),P=Se(w),N={options:e._options,base_url:(m=(h=d===null||d===void 0?void 0:d.server_url)!==null&&h!==void 0?h:e._baseURL)!==null&&m!==void 0?m:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:P,security_source:e._options.security,retry_config:(d===null||d===void 0?void 0:d.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(d===null||d===void 0?void 0:d.retry_codes)||["408","409","429","5XX"]},D=e._createRequest(N,{security:P,method:"GET",baseURL:d===null||d===void 0?void 0:d.server_url,path:T,headers:A,query:S,body:null,userAgent:e._options.user_agent,timeout_ms:(d===null||d===void 0?void 0:d.timeout_ms)||e._options.timeout_ms||-1},d);if(!D.ok)return[D,{status:"invalid"}];let O=D.value,B=await e._do(O,{context:N,isErrorStatusCode:(Y)=>_e({status:Y},["4XX","5XX"]),retryConfig:N.retry_config,retryCodes:N.retry_codes});if(!B.ok)return[B,{status:"request-error",request:O}];let X=B.value,[q]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(X,O);if(!q.ok)return[q,{status:"complete",request:O,response:X}];return[q,{status:"complete",request:O,response:X}]}class Hg extends mn{list(e,t,n,o){return Te(Fg(this,e,t,n===null||n===void 0?void 0:n.api_version,n===null||n===void 0?void 0:n.page_size,n===null||n===void 0?void 0:n.page_token,n===null||n===void 0?void 0:n.recursive,o))}}class Vg extends mn{get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new Hg(this._options)}listEnvironments(e,t){return Te(Og(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}createEnvironment(e,t,n){return Te(bg(this,e,t,n))}deleteEnvironment(e,t,n){return Te(Lg(this,e,t===null||t===void 0?void 0:t.api_version,n))}getEnvironment(e,t,n){return Te(qg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}class Bg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}}class $g extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}}class Jg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}}class Xg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}}class Kg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}}class Yg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}}class Wg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}}class zg extends vt{constructor(e,t){var n;let o=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,t);this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}}function Qg(e,t,n,o){return new he(KR(e,t,n,o))}async function KR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/interactions/{id}/cancel")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(O)=>_e({status:O},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,N={httpMeta:{response:P,request:A}},[D]=await Ce(Pe(200),fn("4XX",$g),fn("5XX",Bg))(P,A,{extraFields:N});if(!D.ok)return[D,{status:"complete",request:A,response:P}];return[D,{status:"complete",request:A,response:P}]}function Zg(e,t,n,o){return new he(YR(e,t,n,o))}async function YR(e,t,n,o){var s,a,c,d;let f={body:t,api_version:n},h=f,m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(s=h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/interactions")(g),v=new Headers(Ae({"Content-Type":"application/json",Accept:((a=f===null||f===void 0?void 0:f.body)===null||a===void 0?void 0:a.stream)?"text/event-stream":"application/json"})),E=await Ie(e._options.security),T=Se(E),S={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},A=e._createRequest(S,{security:T,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:v,body:m,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let w=A.value,P=await e._do(w,{context:S,isErrorStatusCode:(B)=>_e({status:B},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!P.ok)return[P,{status:"request-error",request:w}];let N=P.value,D={httpMeta:{response:N,request:w}},[O]=await Ce(Pe(200),Ng(200,{sentinel:"[DONE]",flattened:!0}),fn("4XX",Xg),fn("5XX",Jg))(N,w,{extraFields:D});if(!O.ok)return[O,{status:"complete",request:w,response:N}];return[O,{status:"complete",request:w,response:N}]}function WR(e,t,n,o){return new he(zR(e,t,n,o))}async function zR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/interactions/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"DELETE",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(O)=>_e({status:O},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,N={httpMeta:{response:P,request:A}},[D]=await Ce(MR(200),fn("4XX",Yg),fn("5XX",Kg))(P,A,{extraFields:N});if(!D.ok)return[D,{status:"complete",request:A,response:P}];return[D,{status:"complete",request:A,response:P}]}function jg(e,t,n,o,s,a,c){return new he(QR(e,t,n,o,s,a,c))}async function QR(e,t,n,o,s,a,c){var d,f,h;let m={id:t,api_version:n,include_input:o,last_event_id:s,stream:a},g=m,_=null,v={api_version:re("api_version",(d=g.api_version)!==null&&d!==void 0?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",g.id,{explode:!1,charEncoding:"percent"})},E=ve("/{api_version}/interactions/{id}")(v),T=hn({include_input:g.include_input,last_event_id:g.last_event_id,stream:g.stream}),S=new Headers(Ae({Accept:(m===null||m===void 0?void 0:m.stream)?"text/event-stream":"application/json"})),A=await Ie(e._options.security),w=Se(A),P={options:e._options,base_url:(h=(f=c===null||c===void 0?void 0:c.server_url)!==null&&f!==void 0?f:e._baseURL)!==null&&h!==void 0?h:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:w,security_source:e._options.security,retry_config:(c===null||c===void 0?void 0:c.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(c===null||c===void 0?void 0:c.retry_codes)||["408","409","429","5XX"]},N=e._createRequest(P,{security:w,method:"GET",baseURL:c===null||c===void 0?void 0:c.server_url,path:E,headers:S,query:T,body:null,userAgent:e._options.user_agent,timeout_ms:(c===null||c===void 0?void 0:c.timeout_ms)||e._options.timeout_ms||-1},c);if(!N.ok)return[N,{status:"invalid"}];let D=N.value,O=await e._do(D,{context:P,isErrorStatusCode:(Y)=>_e({status:Y},["4XX","5XX"]),retryConfig:P.retry_config,retryCodes:P.retry_codes});if(!O.ok)return[O,{status:"request-error",request:D}];let B=O.value,X={httpMeta:{response:B,request:D}},[q]=await Ce(Pe(200),Ng(200,{sentinel:"[DONE]",flattened:!0}),fn("4XX",zg),fn("5XX",Wg))(B,D,{extraFields:X});if(!q.ok)return[q,{status:"complete",request:D,response:B}];return[q,{status:"complete",request:D,response:B}]}class e_ extends mn{create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Te(Zg(this,o,n,t))}delete(e,t,n){return Te(WR(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Te(jg(this,e,t===null||t===void 0?void 0:t.api_version,t===null||t===void 0?void 0:t.include_input,t===null||t===void 0?void 0:t.last_event_id,t===null||t===void 0?void 0:t.stream,n))}cancel(e,t,n){return Te(Qg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function t_(e,t,n,o){return new he(ZR(e,t,n,o))}async function ZR(e,t,n,o){var s,a,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/triggers")(m),_=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function n_(e,t,n,o){return new he(jR(e,t,n,o))}async function jR(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/triggers/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"DELETE",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function r_(e,t,n,o){return new he(eP(e,t,n,o))}async function eP(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/triggers/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function i_(e,t,n,o,s,a){return new he(tP(e,t,n,o,s,a))}async function tP(e,t,n,o,s,a){var c,d,f;let m={trigger_id:t,api_version:n,page_size:o,page_token:s},g=null,_={api_version:re("api_version",(c=m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:re("trigger_id",m.trigger_id,{explode:!1,charEncoding:"percent"})},v=ve("/{api_version}/triggers/{trigger_id}/executions")(_),E=hn({page_size:m.page_size,page_token:m.page_token}),T=new Headers(Ae({Accept:"application/json"})),S=await Ie(e._options.security),A=Se(S),w={options:e._options,base_url:(f=(d=a===null||a===void 0?void 0:a.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(a===null||a===void 0?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(a===null||a===void 0?void 0:a.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(w,{security:A,method:"GET",baseURL:a===null||a===void 0?void 0:a.server_url,path:v,headers:T,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(a===null||a===void 0?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:w,isErrorStatusCode:(X)=>_e({status:X},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let O=D.value,[B]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(O,N);if(!B.ok)return[B,{status:"complete",request:N,response:O}];return[B,{status:"complete",request:N,response:O}]}function o_(e,t,n,o,s,a){return new he(nP(e,t,n,o,s,a))}async function nP(e,t,n,o,s,a){var c,d,f;let m={api_version:t,filter:n,page_size:o,page_token:s},g=null,_={api_version:re("api_version",(c=m===null||m===void 0?void 0:m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"})},v=ve("/{api_version}/triggers")(_),E=hn({filter:m===null||m===void 0?void 0:m.filter,page_size:m===null||m===void 0?void 0:m.page_size,page_token:m===null||m===void 0?void 0:m.page_token}),T=new Headers(Ae({Accept:"application/json"})),S=await Ie(e._options.security),A=Se(S),w={options:e._options,base_url:(f=(d=a===null||a===void 0?void 0:a.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(a===null||a===void 0?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(a===null||a===void 0?void 0:a.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(w,{security:A,method:"GET",baseURL:a===null||a===void 0?void 0:a.server_url,path:v,headers:T,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(a===null||a===void 0?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:w,isErrorStatusCode:(X)=>_e({status:X},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let O=D.value,[B]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(O,N);if(!B.ok)return[B,{status:"complete",request:N,response:O}];return[B,{status:"complete",request:N,response:O}]}function s_(e,t,n,o){return new he(rP(e,t,n,o))}async function rP(e,t,n,o){var s,a,c;let f={trigger_id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:re("trigger_id",f.trigger_id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/triggers/{trigger_id}/executions")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function a_(e,t,n,o,s){return new he(iP(e,t,n,o,s))}async function iP(e,t,n,o,s){var a,c,d;let h={id:t,body:n,api_version:o},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(a=h.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/triggers/{id}")(g),v=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),E=await Ie(e._options.security),T=Se(E),S={options:e._options,base_url:(d=(c=s===null||s===void 0?void 0:s.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},A=e._createRequest(S,{security:T,method:"PATCH",baseURL:s===null||s===void 0?void 0:s.server_url,path:_,headers:v,body:m,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!A.ok)return[A,{status:"invalid"}];let w=A.value,P=await e._do(w,{context:S,isErrorStatusCode:(O)=>_e({status:O},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!P.ok)return[P,{status:"request-error",request:w}];let N=P.value,[D]=await Ce(Pe(200),ie("4XX"),ie("5XX"))(N,w);if(!D.ok)return[D,{status:"complete",request:w,response:N}];return[D,{status:"complete",request:w,response:N}]}class l_ extends mn{list(e,t){return Te(o_(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.filter,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Te(t_(this,o,n,t))}delete(e,t,n){return Te(n_(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Te(r_(this,e,t===null||t===void 0?void 0:t.api_version,n))}update(e,t,n){let{api_version:o}=t,s=Ve(t,["api_version"]);return Te(a_(this,e,s,o,n))}listExecutions(e,t,n){return Te(i_(this,e,t===null||t===void 0?void 0:t.api_version,t===null||t===void 0?void 0:t.page_size,t===null||t===void 0?void 0:t.page_token,n))}run(e,t,n){return Te(s_(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function u_(e,t,n,o){return new he(oP(e,t,n,o))}async function oP(e,t,n,o){var s,a,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/webhooks")(m),_=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function c_(e,t,n,o){return new he(sP(e,t,n,o))}async function sP(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/webhooks/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"DELETE",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function d_(e,t,n,o){return new he(aP(e,t,n,o))}async function aP(e,t,n,o){var s,a,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(s=f.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ve("/{api_version}/webhooks/{id}")(m),_=new Headers(Ae({Accept:"application/json"})),v=await Ie(e._options.security),E=Se(v),T={options:e._options,base_url:(c=(a=o===null||o===void 0?void 0:o.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:E,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},S=e._createRequest(T,{security:E,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!S.ok)return[S,{status:"invalid"}];let A=S.value,w=await e._do(A,{context:T,isErrorStatusCode:(D)=>_e({status:D},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!w.ok)return[w,{status:"request-error",request:A}];let P=w.value,[N]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(P,A);if(!N.ok)return[N,{status:"complete",request:A,response:P}];return[N,{status:"complete",request:A,response:P}]}function f_(e,t,n,o,s){return new he(lP(e,t,n,o,s))}async function lP(e,t,n,o,s){var a,c,d;let h={api_version:t,page_size:n,page_token:o},m=null,g={api_version:re("api_version",(a=h===null||h===void 0?void 0:h.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/webhooks")(g),v=hn({page_size:h===null||h===void 0?void 0:h.page_size,page_token:h===null||h===void 0?void 0:h.page_token}),E=new Headers(Ae({Accept:"application/json"})),T=await Ie(e._options.security),S=Se(T),A={options:e._options,base_url:(d=(c=s===null||s===void 0?void 0:s.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:S,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},w=e._createRequest(A,{security:S,method:"GET",baseURL:s===null||s===void 0?void 0:s.server_url,path:_,headers:E,query:v,body:null,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!w.ok)return[w,{status:"invalid"}];let P=w.value,N=await e._do(P,{context:A,isErrorStatusCode:(B)=>_e({status:B},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!N.ok)return[N,{status:"request-error",request:P}];let D=N.value,[O]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(D,P);if(!O.ok)return[O,{status:"complete",request:P,response:D}];return[O,{status:"complete",request:P,response:D}]}function p_(e,t,n,o,s){return new he(uP(e,t,n,o,s))}async function uP(e,t,n,o,s){var a,c,d;let h={id:t,api_version:n,body:o},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(a=h.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/webhooks/{id}:ping")(g),v=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),E=await Ie(e._options.security),T=Se(E),S={options:e._options,base_url:(d=(c=s===null||s===void 0?void 0:s.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},A=e._createRequest(S,{security:T,method:"POST",baseURL:s===null||s===void 0?void 0:s.server_url,path:_,headers:v,body:m,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!A.ok)return[A,{status:"invalid"}];let w=A.value,P=await e._do(w,{context:S,isErrorStatusCode:(O)=>_e({status:O},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!P.ok)return[P,{status:"request-error",request:w}];let N=P.value,[D]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(N,w);if(!D.ok)return[D,{status:"complete",request:w,response:N}];return[D,{status:"complete",request:w,response:N}]}function h_(e,t,n,o,s){return new he(cP(e,t,n,o,s))}async function cP(e,t,n,o,s){var a,c,d;let h={id:t,api_version:n,body:o},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(a=h.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ve("/{api_version}/webhooks/{id}:rotateSigningSecret")(g),v=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),E=await Ie(e._options.security),T=Se(E),S={options:e._options,base_url:(d=(c=s===null||s===void 0?void 0:s.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},A=e._createRequest(S,{security:T,method:"POST",baseURL:s===null||s===void 0?void 0:s.server_url,path:_,headers:v,body:m,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!A.ok)return[A,{status:"invalid"}];let w=A.value,P=await e._do(w,{context:S,isErrorStatusCode:(O)=>_e({status:O},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!P.ok)return[P,{status:"request-error",request:w}];let N=P.value,[D]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(N,w);if(!D.ok)return[D,{status:"complete",request:w,response:N}];return[D,{status:"complete",request:w,response:N}]}function m_(e,t,n,o,s,a){return new he(dP(e,t,n,o,s,a))}async function dP(e,t,n,o,s,a){var c,d,f;let m={id:t,api_version:n,update_mask:o,body:s},g=Ft("body",m.body,{explode:!0}),_={api_version:re("api_version",(c=m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",m.id,{explode:!1,charEncoding:"percent"})},v=ve("/{api_version}/webhooks/{id}")(_),E=hn({update_mask:m.update_mask}),T=new Headers(Ae({"Content-Type":"application/json",Accept:"application/json"})),S=await Ie(e._options.security),A=Se(S),w={options:e._options,base_url:(f=(d=a===null||a===void 0?void 0:a.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(a===null||a===void 0?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(a===null||a===void 0?void 0:a.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(w,{security:A,method:"PATCH",baseURL:a===null||a===void 0?void 0:a.server_url,path:v,headers:T,query:E,body:g,userAgent:e._options.user_agent,timeout_ms:(a===null||a===void 0?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:w,isErrorStatusCode:(X)=>_e({status:X},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let O=D.value,[B]=await Ce(ie("4XX"),ie("5XX"),Pe("default"))(O,N);if(!B.ok)return[B,{status:"complete",request:N,response:O}];return[B,{status:"complete",request:N,response:O}]}class g_ extends mn{list(e,t){return Te(f_(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Te(u_(this,o,n,t))}delete(e,t,n){return Te(c_(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Te(d_(this,e,t===null||t===void 0?void 0:t.api_version,n))}update(e,t,n){let o=t!==null&&t!==void 0?t:{},{api_version:s,update_mask:a}=o,c=Ve(o,["api_version","update_mask"]),d=t===void 0||Object.keys(c).length===0?void 0:c;return Te(m_(this,e,s,a,d,n))}ping(e,t,n,o){return Te(p_(this,e,t,n,o))}rotateSigningSecret(e,t,n,o){return Te(h_(this,e,t,n,o))}}var fP=class extends mn{get agents(){var t;return(t=this._agents)!==null&&t!==void 0?t:this._agents=new Gg(this._options)}get environments(){var t;return(t=this._environments)!==null&&t!==void 0?t:this._environments=new Vg(this._options)}get interactions(){var t;return(t=this._interactions)!==null&&t!==void 0?t:this._interactions=new e_(this._options)}get triggers(){var t;return(t=this._triggers)!==null&&t!==void 0?t:this._triggers=new l_(this._options)}get webhooks(){var t;return(t=this._webhooks)!==null&&t!==void 0?t:this._webhooks=new g_(this._options)}},pP=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function hP(e){let t=e.getBaseUrl();if(!t)throw Error("Base URL must be set.");return t.replace(/\/+$/,"")}function mP(e){let t=gP(e.getApiVersion()),n=e.getProject(),o=e.getLocation();if(e.isVertexAI()&&t&&n&&o)return`${t}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(o)}`;return t}function Nt(e,t={}){var n,o,s,a,c;return new fP(Object.assign(Object.assign({},t),{api_version:(n=t.api_version)!==null&&n!==void 0?n:mP(e),security:(o=t.security)!==null&&o!==void 0?o:new eg({defaultHeaders:Object.assign(Object.assign({},(s=e.getDefaultHeaders)===null||s===void 0?void 0:s.call(e)),(a=e.getHeaders)===null||a===void 0?void 0:a.call(e)),getAuthHeaders:(f)=>e.getAuthHeaders(f)}),server_url:(c=t.server_url)!==null&&c!==void 0?c:hP(e)}))}class __{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);if(o.stream===!0){let a=await ys(()=>this.getClient(n).interactions.create(Object.assign(Object.assign({},o),{stream:!0,api_version:n}),me(t,!0)));return Bh(a)}let s=await Re(Zg(this.getClient(n),o,n,me(t)));return Es(s)}async get(e,t={},n){let{api_version:o,stream:s=!1,last_event_id:a,include_input:c}=t!==null&&t!==void 0?t:{};if(s===!0){let f=await ys(()=>this.getClient(o).interactions.get(e,{stream:s,last_event_id:a,include_input:c,api_version:o},me(n,!0)));return Bh(f)}let d=await Re(jg(this.getClient(o),e,o,c,a,s,me(n)));return Es(d)}async delete(e,t={},n){return ys(()=>this.getClient(t===null||t===void 0?void 0:t.api_version).interactions.delete(e,{api_version:t===null||t===void 0?void 0:t.api_version},me(n)))}async cancel(e,t={},n){return Es(await Re(Qg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n))))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class y_{constructor(e){this.parentClient=e}async create(e={},t){let n=e!==null&&e!==void 0?e:{},{api_version:o}=n,s=Ve(n,["api_version"]);return Re(kg(this.getClient(o),s,o,me(t)))}async list(e={},t){let{api_version:n,pageSize:o,pageToken:s,parent:a}=e!==null&&e!==void 0?e:{};return Re(Ug(this.getClient(n),n,o,s,a,me(t)))}async get(e,t={},n){return Re(Mg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async delete(e,t={},n){return Re(Dg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class E_{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Re(u_(this.getClient(),o,n,me(t)))}async list(e={},t){let{api_version:n,page_size:o,page_token:s}=e!==null&&e!==void 0?e:{};return Re(f_(this.getClient(),n,o,s,me(t)))}async get(e,t={},n){return Re(d_(this.getClient(),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async update(e,t={},n){let o=t!==null&&t!==void 0?t:{},{api_version:s,update_mask:a}=o,c=Ve(o,["api_version","update_mask"]);return Re(m_(this.getClient(),e,s,a,c,me(n)))}async delete(e,t={},n){return Re(c_(this.getClient(),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async rotateSigningSecret(e,t={},n){let o=t!==null&&t!==void 0?t:{},{api_version:s}=o,a=Ve(o,["api_version"]);return Re(h_(this.getClient(),e,s,a,me(n)))}async ping(e,t=void 0,n){let{api_version:o,body:s}=t!==null&&t!==void 0?t:{};return Re(p_(this.getClient(),e,o,s,me(n)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class v_{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Re(t_(this.getClient(n),o,n,me(t)))}async list(e={},t){let{api_version:n,filter:o,pageSize:s,pageToken:a}=e!==null&&e!==void 0?e:{};return Re(o_(this.getClient(n),n,o,s,a,me(t)))}async get(e,t={},n){return Re(r_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async update(e,t,n){let{api_version:o}=t,s=Ve(t,["api_version"]);return Re(a_(this.getClient(o),e,s,o,me(n)))}async delete(e,t={},n){return Re(n_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async run(e,t={},n){return Re(s_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async listExecutions(e,t={},n){let{api_version:o,pageSize:s,pageToken:a}=t!==null&&t!==void 0?t:{};return Re(i_(this.getClient(o),e,o,s,a,me(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}function gP(e){return e.replace(/^\/+|\/+$/g,"")}function me(e,t=!1){var n,o,s,a;if(!e&&!t)return;let c=e!==null&&e!==void 0?e:{},{timeout:d,maxRetries:f,defaultBaseURL:h,query:m,body:g,fetchOptions:_}=c,v=Ve(c,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),E=Object.assign({},v);if(Oi(m))E.extra_query=m;else Vh("query",m);if(Oi(g))E.extra_body=g;else Vh("body",g);let T=(n=v.fetch_options)!==null&&n!==void 0?n:_;if(T)E.fetch_options=T;let S=(o=v.server_url)!==null&&o!==void 0?o:h;if(S)E.server_url=S;let A=(s=v.timeout_ms)!==null&&s!==void 0?s:d;if(A!==void 0)E.timeout_ms=A;if(f!==void 0)E.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:f};if(t){let w=new Headers((a=E.headers)!==null&&a!==void 0?a:T===null||T===void 0?void 0:T.headers);w.set("Accept","text/event-stream"),E.headers=w}return E}function Vh(e,t){if(t!==void 0&&t!==null)console.warn(`GoogleGenAI.interactions: request option ${e} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function Re(e){let[t,n]=await e.$inspect();if(!t.ok)throw $n(t.error);return _P(t.value,n)}async function ys(e){try{return await e()}catch(t){throw $n(t)}}function Bh(e){let t=e;return new Proxy(e,{get(n,o){if(o!==Symbol.asyncIterator){let s=Reflect.get(n,o,n);return typeof s==="function"?s.bind(n):s}return function(){let a=t[Symbol.asyncIterator]();return{async next(...c){try{return await a.next(...c)}catch(d){throw $n(d)}},async return(c){if(!a.return)return{done:!0,value:c};try{return await a.return(c)}catch(d){throw $n(d)}},async throw(c){if(!a.throw)throw $n(c);try{return await a.throw(c)}catch(d){throw $n(d)}},[Symbol.asyncIterator](){return this}}}}})}function _P(e,t){if(!Oi(e)||t.status!=="complete")return e;return Object.assign(Object.assign({},e),{sdkHttpResponse:yP(t.response,e)})}function yP(e,t){let n={};for(let[o,s]of e.headers.entries())n[o]=s;return{headers:n,responseInternal:e,json:async()=>t}}function Es(e){let t=EP(e);if(!t)return e;return TP(t)}function EP(e){if(!Oi(e))return;if(Array.isArray(e.steps))return e;if(vP(e)){let t=e.outputs;if(Array.isArray(t)){let{outputs:n}=e,o=Ve(e,["outputs"]);return Object.assign(Object.assign({},o),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}function vP(e){let t=e.model;return typeof t==="string"&&pP.has(t)}function Oi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function TP(e){var t,n;let o=AP(e),s=(t=o.steps)!==null&&t!==void 0?t:[],a=[],c=!1;e:for(let g=s.length-1;g>=0;g--){let _=s[g];if(_.type==="user_input")break;if(_.type!=="model_output"||!_.content){if(c)break;continue}let v=_.content;for(let E=v.length-1;E>=0;E--){let T=v[E];if(T.type==="text")c=!0,a.push((n=T.text)!==null&&n!==void 0?n:"");else if(c)break e}}let d,f,h;for(let g=s.length-1;g>=0;g--){let _=s[g];if(_.type==="user_input")break;if(_.type==="model_output"&&_.content)for(let v=_.content.length-1;v>=0;v--){let E=_.content[v];if(E.type==="image"&&!d)d=E;if(E.type==="audio"&&!f)f=E;if(E.type==="video"&&!h)h=E}}let m=a.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},o),m&&{output_text:m}),d?{output_image:d}:{}),f?{output_audio:f}:{}),h?{output_video:h}:{})}function AP(e){return Object.assign(Object.assign({},e),{created:$h(e.created),updated:$h(e.updated)})}function $h(e){return e instanceof Date?e.toISOString():e}class T_{constructor(e){this.resolveClient=e}async list(e,t){let{environment:n,path:o,page_size:s,page_token:a,recursive:c,api_version:d}=e;return Re(Fg(this.resolveClient(d),n,o,d,s,a,c,me(t)))}}class A_{constructor(e){this.parentClient=e,this.files=new T_((t)=>this.getClient(t))}async create(e,t){let{api_version:n}=e,o=Ve(e,["api_version"]);return Re(bg(this.getClient(n),o,n,me(t)))}async list(e={},t){let{api_version:n,page_size:o,page_token:s}=e!==null&&e!==void 0?e:{};return Re(Og(this.getClient(n),n,o,s,me(t)))}async get(e,t={},n){return Re(qg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}async delete(e,t={},n){return Re(Lg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,me(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}var Jh="x-goog-api-key",hr="https://www.googleapis.com/auth/cloud-platform";class C_{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let t=CP(e.googleAuthOptions);this.googleAuth=new Yh.GoogleAuth(t)}async addAuthHeaders(e,t){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(e.get(Jh)!==null)return;if(this.apiKey===void 0)throw Error("Trying to set API key header but apiKey is not set");e.append(Jh,this.apiKey)}async addGoogleAuthHeaders(e,t){if(this.googleAuth===void 0)throw Error("Trying to set google-auth headers but googleAuth is unset");let n=await this.googleAuth.getRequestHeaders(t);for(let[o,s]of n){if(e.get(o)!==null)continue;e.append(o,s)}}}function CP(e){let t;if(!e)return t={scopes:[hr]},t;else{if(t=e,!t.scopes)return t.scopes=[hr],t;else if(typeof t.scopes==="string"&&t.scopes!==hr||Array.isArray(t.scopes)&&t.scopes.indexOf(hr)<0)throw Error(`Invalid auth scopes. Scopes must include: ${hr}`);return t}}class S_{async download(e,t){if(e.downloadPath){let n=await SP(e,t);if(n instanceof yn){let o=BT(e.downloadPath);JT.fromWeb(n.responseInternal.body).pipe(o),await XT(o)}else try{await $T(e.downloadPath,n,{encoding:"base64"})}catch(o){throw Error(`Failed to write file to ${e.downloadPath}: ${o}`)}}}}async function SP(e,t){var n,o,s;let a=Ks(e.file);if(a!==void 0)return await t.request({path:`files/${a}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal});else if(vm(e.file)){let c=(s=e.file.video)===null||s===void 0?void 0:s.videoBytes;if(typeof c==="string")return c;else throw Error("Failed to download generated video, Uri or videoBytes not found.")}else if(Tm(e.file)){let c=e.file.videoBytes;if(typeof c==="string")return c;else throw Error("Failed to download video, Uri or videoBytes not found.")}else throw Error("Unsupported file type")}class I_{create(e,t,n){return new w_(e,t,n)}}class w_{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}connect(){this.ws=new Wh.WebSocket(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 Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw Error("WebSocket is not connected");this.ws.close()}}function IP(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["_url","name"],o);return n}function wP(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["_url","name"],o);return n}function RP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);return n}function PP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);return n}function qs(e,t){let n={},o=l(e,["parts"]);if(o!=null){let a=o;if(Array.isArray(a))a=a.map((c)=>HP(c));u(n,["parts"],a)}let s=l(e,["role"]);if(s!=null)u(n,["role"],s);return n}function NP(e,t,n){let o={};if(l(e,["validationDataset"])!==void 0)throw Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["tunedModelDisplayName"]);if(t!==void 0&&s!=null)u(t,["displayName"],s);if(l(e,["description"])!==void 0)throw Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=l(e,["epochCount"]);if(t!==void 0&&a!=null)u(t,["tuningTask","hyperparameters","epochCount"],a);let c=l(e,["learningRateMultiplier"]);if(c!=null)u(o,["tuningTask","hyperparameters","learningRateMultiplier"],c);if(l(e,["exportLastCheckpointOnly"])!==void 0)throw Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["preTunedModelCheckpointId"])!==void 0)throw Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["adapterSize"])!==void 0)throw Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tuningMode"])!==void 0)throw Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["customBaseModel"])!==void 0)throw Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=l(e,["batchSize"]);if(t!==void 0&&d!=null)u(t,["tuningTask","hyperparameters","batchSize"],d);let f=l(e,["learningRate"]);if(t!==void 0&&f!=null)u(t,["tuningTask","hyperparameters","learningRate"],f);if(l(e,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["beta"])!==void 0)throw Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["baseTeacherModel"])!==void 0)throw Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tunedTeacherModelSource"])!==void 0)throw Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["sftLossWeightMultiplier"])!==void 0)throw Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputUri"])!==void 0)throw Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["rewardConfig"])!==void 0)throw Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["compositeRewardConfig"])!==void 0)throw Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["samplesPerPrompt"])!==void 0)throw Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["evaluateInterval"])!==void 0)throw Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["checkpointInterval"])!==void 0)throw Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["maxOutputTokens"])!==void 0)throw Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["thinkingLevel"])!==void 0)throw Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["validationDatasetUri"])!==void 0)throw Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["encryptionSpec"])!==void 0)throw Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function xP(e,t,n){let o={},s=l(n,["config","method"]);if(s===void 0)s="SUPERVISED_FINE_TUNING";if(s==="SUPERVISED_FINE_TUNING"){let V=l(e,["validationDataset"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec"],ki(V))}else if(s==="PREFERENCE_TUNING"){let V=l(e,["validationDataset"]);if(t!==void 0&&V!=null)u(t,["preferenceOptimizationSpec"],ki(V))}else if(s==="DISTILLATION"){let V=l(e,["validationDataset"]);if(t!==void 0&&V!=null)u(t,["distillationSpec"],ki(V))}else if(s==="REINFORCEMENT_TUNING"){let V=l(e,["validationDataset"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec"],ki(V))}let a=l(e,["tunedModelDisplayName"]);if(t!==void 0&&a!=null)u(t,["tunedModelDisplayName"],a);let c=l(e,["description"]);if(t!==void 0&&c!=null)u(t,["description"],c);let d=l(n,["config","method"]);if(d===void 0)d="SUPERVISED_FINE_TUNING";if(d==="SUPERVISED_FINE_TUNING"){let V=l(e,["epochCount"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","hyperParameters","epochCount"],V)}else if(d==="PREFERENCE_TUNING"){let V=l(e,["epochCount"]);if(t!==void 0&&V!=null)u(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],V)}else if(d==="DISTILLATION"){let V=l(e,["epochCount"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","hyperParameters","epochCount"],V)}else if(d==="REINFORCEMENT_TUNING"){let V=l(e,["epochCount"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec","hyperParameters","epochCount"],V)}let f=l(n,["config","method"]);if(f===void 0)f="SUPERVISED_FINE_TUNING";if(f==="SUPERVISED_FINE_TUNING"){let V=l(e,["learningRateMultiplier"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],V)}else if(f==="PREFERENCE_TUNING"){let V=l(e,["learningRateMultiplier"]);if(t!==void 0&&V!=null)u(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],V)}else if(f==="DISTILLATION"){let V=l(e,["learningRateMultiplier"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","hyperParameters","learningRateMultiplier"],V)}else if(f==="REINFORCEMENT_TUNING"){let V=l(e,["learningRateMultiplier"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],V)}let h=l(n,["config","method"]);if(h===void 0)h="SUPERVISED_FINE_TUNING";if(h==="SUPERVISED_FINE_TUNING"){let V=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","exportLastCheckpointOnly"],V)}else if(h==="PREFERENCE_TUNING"){let V=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&V!=null)u(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],V)}else if(h==="DISTILLATION"){let V=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","exportLastCheckpointOnly"],V)}let m=l(n,["config","method"]);if(m===void 0)m="SUPERVISED_FINE_TUNING";if(m==="SUPERVISED_FINE_TUNING"){let V=l(e,["adapterSize"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","hyperParameters","adapterSize"],V)}else if(m==="PREFERENCE_TUNING"){let V=l(e,["adapterSize"]);if(t!==void 0&&V!=null)u(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],V)}else if(m==="DISTILLATION"){let V=l(e,["adapterSize"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","hyperParameters","adapterSize"],V)}else if(m==="REINFORCEMENT_TUNING"){let V=l(e,["adapterSize"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],V)}let g=l(n,["config","method"]);if(g===void 0)g="SUPERVISED_FINE_TUNING";if(g==="SUPERVISED_FINE_TUNING"){let V=l(e,["tuningMode"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","tuningMode"],V)}else if(g==="DISTILLATION"){let V=l(e,["tuningMode"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","tuningMode"],V)}let _=l(e,["customBaseModel"]);if(t!==void 0&&_!=null)u(t,["customBaseModel"],_);let v=l(n,["config","method"]);if(v===void 0)v="SUPERVISED_FINE_TUNING";if(v==="SUPERVISED_FINE_TUNING"){let V=l(e,["batchSize"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","hyperParameters","batchSize"],V)}else if(v==="DISTILLATION"){let V=l(e,["batchSize"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","hyperParameters","batchSize"],V)}else if(v==="REINFORCEMENT_TUNING"){let V=l(e,["batchSize"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec","hyperParameters","batchSize"],V)}let E=l(n,["config","method"]);if(E===void 0)E="SUPERVISED_FINE_TUNING";if(E==="SUPERVISED_FINE_TUNING"){let V=l(e,["learningRate"]);if(t!==void 0&&V!=null)u(t,["supervisedTuningSpec","hyperParameters","learningRate"],V)}else if(E==="DISTILLATION"){let V=l(e,["learningRate"]);if(t!==void 0&&V!=null)u(t,["distillationSpec","hyperParameters","learningRate"],V)}let T=l(e,["labels"]);if(t!==void 0&&T!=null)u(t,["labels"],T);let S=l(e,["beta"]);if(t!==void 0&&S!=null)u(t,["preferenceOptimizationSpec","hyperParameters","beta"],S);let A=l(e,["baseTeacherModel"]);if(t!==void 0&&A!=null)u(t,["distillationSpec","baseTeacherModel"],A);let w=l(e,["tunedTeacherModelSource"]);if(t!==void 0&&w!=null)u(t,["distillationSpec","tunedTeacherModelSource"],w);let P=l(e,["sftLossWeightMultiplier"]);if(t!==void 0&&P!=null)u(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],P);let N=l(e,["outputUri"]);if(t!==void 0&&N!=null)u(t,["outputUri"],N);let D=l(e,["rewardConfig"]);if(t!==void 0&&D!=null)u(t,["reinforcementTuningSpec","singleRewardConfig"],D);let O=l(e,["compositeRewardConfig"]);if(t!==void 0&&O!=null)u(t,["reinforcementTuningSpec","compositeRewardConfig"],O);let B=l(e,["samplesPerPrompt"]);if(t!==void 0&&B!=null)u(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],B);let X=l(e,["evaluateInterval"]);if(t!==void 0&&X!=null)u(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],X);let q=l(e,["checkpointInterval"]);if(t!==void 0&&q!=null)u(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],q);let Y=l(e,["maxOutputTokens"]);if(t!==void 0&&Y!=null)u(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],Y);let Z=l(e,["thinkingLevel"]);if(t!==void 0&&Z!=null)u(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],Z);let ne=l(e,["validationDatasetUri"]);if(t!==void 0&&ne!=null)u(t,["reinforcementTuningSpec","validationDatasetUri"],ne);let W=l(e,["encryptionSpec"]);if(t!==void 0&&W!=null)u(t,["encryptionSpec"],W);return o}function kP(e,t){let n={},o=l(e,["baseModel"]);if(o!=null)u(n,["baseModel"],o);let s=l(e,["preTunedModel"]);if(s!=null)u(n,["preTunedModel"],s);let a=l(e,["trainingDataset"]);if(a!=null)$P(a);let c=l(e,["config"]);if(c!=null)NP(c,n);return n}function DP(e,t){let n={},o=l(e,["baseModel"]);if(o!=null)u(n,["baseModel"],o);let s=l(e,["preTunedModel"]);if(s!=null)u(n,["preTunedModel"],s);let a=l(e,["trainingDataset"]);if(a!=null)JP(a,n,t);let c=l(e,["config"]);if(c!=null)xP(c,n,t);return n}function R_(e,t){let n={},o=l(e,["epochCount"]);if(o!=null)u(n,["epochCount"],o);let s=l(e,["learningRateMultiplier"]);if(s!=null)u(n,["learningRateMultiplier"],s);let a=l(e,["adapterSize"]);if(a!=null)u(n,["adapterSize"],a);let c=l(e,["batchSize"]);if(c!=null)u(n,["batchSize"],c);let d=l(e,["learningRate"]);if(d!=null)u(n,["learningRate"],d);let f=l(e,["generationConfig"]);if(f!=null)u(n,["generationConfig"],GP(f));return n}function MP(e,t){let n={},o=l(e,["promptDatasetUri"]);if(o!=null)u(n,["promptDatasetUri"],o);let s=l(e,["validationDatasetUri"]);if(s!=null)u(n,["validationDatasetUri"],s);let a=l(e,["baseTeacherModel"]);if(a!=null)u(n,["baseTeacherModel"],a);let c=l(e,["tunedTeacherModelSource"]);if(c!=null)u(n,["tunedTeacherModelSource"],c);let d=l(e,["hyperparameters"]);if(d!=null)u(n,["hyperparameters"],R_(d));return n}function UP(e,t){let n={},o=l(e,["baseTeacherModel"]);if(o!=null)u(n,["baseTeacherModel"],o);let s=l(e,["hyperParameters"]);if(s!=null)u(n,["hyperParameters"],R_(s));let a=l(e,["pipelineRootDirectory"]);if(a!=null)u(n,["pipelineRootDirectory"],a);let c=l(e,["promptDatasetUri"]);if(c!=null)u(n,["promptDatasetUri"],c);let d=l(e,["studentModel"]);if(d!=null)u(n,["studentModel"],d);let f=l(e,["trainingDatasetUri"]);if(f!=null)u(n,["trainingDatasetUri"],f);let h=l(e,["tunedTeacherModelSource"]);if(h!=null)u(n,["tunedTeacherModelSource"],h);let m=l(e,["tuningMode"]);if(m!=null)u(n,["tuningMode"],m);let g=l(e,["validationDatasetUri"]);if(g!=null)u(n,["validationDatasetUri"],g);return n}function GP(e,t){let n={},o=l(e,["modelConfig"]);if(o!=null)u(n,["modelSelectionConfig"],o);let s=l(e,["responseJsonSchema"]);if(s!=null)u(n,["responseJsonSchema"],Yn(s));let a=l(e,["audioTranscriptionConfig"]);if(a!=null)u(n,["audioTranscriptionConfig"],a);let c=l(e,["audioTimestamp"]);if(c!=null)u(n,["audioTimestamp"],c);let d=l(e,["candidateCount"]);if(d!=null)u(n,["candidateCount"],d);let f=l(e,["enableAffectiveDialog"]);if(f!=null)u(n,["enableAffectiveDialog"],f);let h=l(e,["frequencyPenalty"]);if(h!=null)u(n,["frequencyPenalty"],h);let m=l(e,["logprobs"]);if(m!=null)u(n,["logprobs"],m);let g=l(e,["maxOutputTokens"]);if(g!=null)u(n,["maxOutputTokens"],g);let _=l(e,["mediaResolution"]);if(_!=null)u(n,["mediaResolution"],_);let v=l(e,["presencePenalty"]);if(v!=null)u(n,["presencePenalty"],v);let E=l(e,["responseFormat"]);if(E!=null){let Z=E;if(Array.isArray(Z))Z=Z.map((ne)=>ne);u(n,["responseFormat"],Z)}let T=l(e,["responseLogprobs"]);if(T!=null)u(n,["responseLogprobs"],T);let S=l(e,["responseMimeType"]);if(S!=null)u(n,["responseMimeType"],S);let A=l(e,["responseModalities"]);if(A!=null)u(n,["responseModalities"],A);let w=l(e,["responseSchema"]);if(w!=null)u(n,["responseSchema"],w);let P=l(e,["routingConfig"]);if(P!=null)u(n,["routingConfig"],P);let N=l(e,["seed"]);if(N!=null)u(n,["seed"],N);let D=l(e,["speechConfig"]);if(D!=null)u(n,["speechConfig"],D);let O=l(e,["stopSequences"]);if(O!=null)u(n,["stopSequences"],O);let B=l(e,["temperature"]);if(B!=null)u(n,["temperature"],B);let X=l(e,["thinkingConfig"]);if(X!=null)u(n,["thinkingConfig"],X);let q=l(e,["topK"]);if(q!=null)u(n,["topK"],q);let Y=l(e,["topP"]);if(Y!=null)u(n,["topP"],Y);return n}function bP(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["_url","name"],o);return n}function LP(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["_url","name"],o);return n}function qP(e,t,n){let o={},s=l(e,["pageSize"]);if(t!==void 0&&s!=null)u(t,["_query","pageSize"],s);let a=l(e,["pageToken"]);if(t!==void 0&&a!=null)u(t,["_query","pageToken"],a);let c=l(e,["filter"]);if(t!==void 0&&c!=null)u(t,["_query","filter"],c);return o}function OP(e,t){let n={},o=l(e,["config"]);if(o!=null)qP(o,n);return n}function FP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["nextPageToken"]);if(s!=null)u(n,["nextPageToken"],s);let a=l(e,["tuningJobs"]);if(a!=null){let c=a;if(Array.isArray(c))c=c.map((d)=>Os(d));u(n,["tuningJobs"],c)}return n}function HP(e,t){let n={},o=l(e,["mediaResolution"]);if(o!=null)u(n,["mediaResolution"],o);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let s=l(e,["audioTranscription"]);if(s!=null)u(n,["audioTranscription"],s);let a=l(e,["codeExecutionResult"]);if(a!=null)u(n,["codeExecutionResult"],a);let c=l(e,["executableCode"]);if(c!=null)u(n,["executableCode"],c);let d=l(e,["fileData"]);if(d!=null)u(n,["fileData"],d);let f=l(e,["functionCall"]);if(f!=null)u(n,["functionCall"],f);let h=l(e,["functionResponse"]);if(h!=null)u(n,["functionResponse"],h);let m=l(e,["inlineData"]);if(m!=null)u(n,["inlineData"],m);let g=l(e,["text"]);if(g!=null)u(n,["text"],g);let _=l(e,["thought"]);if(_!=null)u(n,["thought"],_);let v=l(e,["thoughtSignature"]);if(v!=null)u(n,["thoughtSignature"],v);let E=l(e,["videoMetadata"]);if(E!=null)u(n,["videoMetadata"],E);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let T=l(e,["mediaProcessing"]);if(T!=null)u(n,["mediaProcessing"],T);return n}function VP(e,t){let n={},o=l(e,["references"]);if(o!=null)u(n,["references"],o);let s=l(e,["contents"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>qs(d));u(n,["contents"],c)}let a=l(e,["systemInstruction"]);if(a!=null)u(n,["systemInstruction"],qs(a));return n}function BP(e,t){let n={},o=l(e,["name"]);if(o!=null)u(n,["model"],o);let s=l(e,["name"]);if(s!=null)u(n,["endpoint"],s);return n}function $P(e,t){let n={};if(l(e,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["vertexDatasetResource"])!==void 0)throw Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["examples"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((a)=>a);u(n,["examples","examples"],s)}return n}function JP(e,t,n){let o={},s=l(n,["config","method"]);if(s===void 0)s="SUPERVISED_FINE_TUNING";if(s==="SUPERVISED_FINE_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(s==="PREFERENCE_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if(s==="DISTILLATION"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["distillationSpec","promptDatasetUri"],c)}else if(s==="REINFORCEMENT_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["reinforcementTuningSpec","trainingDatasetUri"],c)}let a=l(n,["config","method"]);if(a===void 0)a="SUPERVISED_FINE_TUNING";if(a==="SUPERVISED_FINE_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(a==="PREFERENCE_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if(a==="DISTILLATION"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["distillationSpec","promptDatasetUri"],c)}else if(a==="REINFORCEMENT_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["reinforcementTuningSpec","trainingDatasetUri"],c)}if(l(e,["examples"])!==void 0)throw Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}function XP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["name"]);if(s!=null)u(n,["name"],s);let a=l(e,["state"]);if(a!=null)u(n,["state"],Em(a));let c=l(e,["createTime"]);if(c!=null)u(n,["createTime"],c);let d=l(e,["tuningTask","startTime"]);if(d!=null)u(n,["startTime"],d);let f=l(e,["tuningTask","completeTime"]);if(f!=null)u(n,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(n,["updateTime"],h);let m=l(e,["description"]);if(m!=null)u(n,["description"],m);let g=l(e,["baseModel"]);if(g!=null)u(n,["baseModel"],g);let _=l(e,["_self"]);if(_!=null)u(n,["tunedModel"],BP(_));return n}function Os(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["name"]);if(s!=null)u(n,["name"],s);let a=l(e,["state"]);if(a!=null)u(n,["state"],Em(a));let c=l(e,["createTime"]);if(c!=null)u(n,["createTime"],c);let d=l(e,["startTime"]);if(d!=null)u(n,["startTime"],d);let f=l(e,["endTime"]);if(f!=null)u(n,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(n,["updateTime"],h);let m=l(e,["error"]);if(m!=null)u(n,["error"],m);let g=l(e,["description"]);if(g!=null)u(n,["description"],g);let _=l(e,["baseModel"]);if(_!=null)u(n,["baseModel"],_);let v=l(e,["tunedModel"]);if(v!=null)u(n,["tunedModel"],v);let E=l(e,["preTunedModel"]);if(E!=null)u(n,["preTunedModel"],E);let T=l(e,["supervisedTuningSpec"]);if(T!=null)u(n,["supervisedTuningSpec"],T);let S=l(e,["preferenceOptimizationSpec"]);if(S!=null)u(n,["preferenceOptimizationSpec"],S);let A=l(e,["distillationSamplingSpec"]);if(A!=null)u(n,["distillationSamplingSpec"],MP(A));let w=l(e,["distillationSpec"]);if(w!=null)u(n,["distillationSpec"],UP(w));let P=l(e,["reinforcementTuningSpec"]);if(P!=null)u(n,["reinforcementTuningSpec"],P);let N=l(e,["tuningDataStats"]);if(N!=null)u(n,["tuningDataStats"],N);let D=l(e,["encryptionSpec"]);if(D!=null)u(n,["encryptionSpec"],D);let O=l(e,["partnerModelTuningSpec"]);if(O!=null)u(n,["partnerModelTuningSpec"],O);let B=l(e,["customBaseModel"]);if(B!=null)u(n,["customBaseModel"],B);let X=l(e,["evaluateDatasetRuns"]);if(X!=null){let be=X;if(Array.isArray(be))be=be.map((ze)=>ze);u(n,["evaluateDatasetRuns"],be)}let q=l(e,["experiment"]);if(q!=null)u(n,["experiment"],q);let Y=l(e,["fullFineTuningSpec"]);if(Y!=null)u(n,["fullFineTuningSpec"],Y);let Z=l(e,["labels"]);if(Z!=null)u(n,["labels"],Z);let ne=l(e,["outputUri"]);if(ne!=null)u(n,["outputUri"],ne);let W=l(e,["pipelineJob"]);if(W!=null)u(n,["pipelineJob"],W);let V=l(e,["serviceAccount"]);if(V!=null)u(n,["serviceAccount"],V);let oe=l(e,["tunedModelDisplayName"]);if(oe!=null)u(n,["tunedModelDisplayName"],oe);let se=l(e,["tuningJobMetadata"]);if(se!=null)u(n,["tuningJobMetadata"],se);let xe=l(e,["tuningJobState"]);if(xe!=null)u(n,["tuningJobState"],xe);let Ue=l(e,["veoLoraTuningSpec"]);if(Ue!=null)u(n,["veoLoraTuningSpec"],Ue);let Xe=l(e,["veoTuningSpec"]);if(Xe!=null)u(n,["veoTuningSpec"],Xe);return n}function KP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["name"]);if(s!=null)u(n,["name"],s);let a=l(e,["metadata"]);if(a!=null)u(n,["metadata"],a);let c=l(e,["done"]);if(c!=null)u(n,["done"],c);let d=l(e,["error"]);if(d!=null)u(n,["error"],d);return n}function ki(e,t){let n={},o=l(e,["gcsUri"]);if(o!=null)u(n,["validationDatasetUri"],o);let s=l(e,["vertexDatasetResource"]);if(s!=null)u(n,["validationDatasetUri"],s);return n}function YP(e,t){let n={},o=l(e,["parent"]);if(o!=null)u(n,["_url","parent"],o);let s=l(e,["sampleResponse"]);if(s!=null)u(n,["sampleResponse"],qs(s));let a=l(e,["example"]);if(a!=null)u(n,["example"],VP(a));let c=l(e,["singleRewardConfig"]);if(c!=null)u(n,["singleRewardConfig"],c);let d=l(e,["compositeRewardConfig"]);if(d!=null)u(n,["compositeRewardConfig"],d);return n}function WP(e,t){let n={},o=l(e,["sdkHttpResponse"]);if(o!=null)u(n,["sdkHttpResponse"],o);let s=l(e,["overallReward"]);if(s!=null)u(n,["overallReward"],s);let a=l(e,["error"]);if(a!=null)u(n,["error"],a);let c=l(e,["rewardInfoDetails"]);if(c!=null)u(n,["rewardInfoDetails"],c);return n}class P_ extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_TUNING_JOBS,(n)=>this.listInternal(n),await this.listInternal(t),t),this.get=async(t)=>await this.getInternal(t),this.tune=async(t)=>{var n;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let o={tunedModelName:t.baseModel};if((n=t.config)===null||n===void 0?void 0:n.preTunedModelCheckpointId)o.checkpointId=t.config.preTunedModelCheckpointId;let s=Object.assign(Object.assign({},t),{preTunedModel:o});return s.baseModel=void 0,await this.tuneInternal(s)}else{let o=Object.assign({},t);return await this.tuneInternal(o)}else{let o=Object.assign({},t),s=await this.tuneMldevInternal(o),a="";if(s.metadata!==void 0&&s.metadata.tunedModel!==void 0)a=s.metadata.tunedModel;else if(s.name!==void 0&&s.name.includes("/operations/"))a=s.name.split("/operations/")[0];return{name:a,state:Ts.JOB_STATE_QUEUED}}}}async getInternal(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=LP(e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>Os(h))}else{let f=bP(e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>XP(h))}}async listInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=OP(e);return s=z("tuningJobs",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=FP(d),h=new rm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,n,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let f=wP(e);return c=z("{name}:cancel",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=PP(h),g=new ws;return Object.assign(g,m),g})}else{let f=IP(e);return c=z("{name}:cancel",f._url),d=f._query,delete f._url,delete f._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),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((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),a.then((h)=>{let m=RP(h),g=new ws;return Object.assign(g,m),g})}}async tuneInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=DP(e,e);return s=z("tuningJobs",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>Os(d))}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=kP(e);return s=z("tunedModels",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>KP(d))}}async validateReward(e){var t,n;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=YP(e);return s=z("{parent}/tuningJobs:validateReinforcementTuningReward",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),o.then((d)=>{let f=WP(d),h=new im;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}var N_=8388608,x_=3,k_=1000,D_=2,sn="x-goog-upload-status";async function zP(e,t,n,o){var s;let a=await M_(e,t,n,o),c=await(a===null||a===void 0?void 0:a.json());if(((s=a===null||a===void 0?void 0:a.headers)===null||s===void 0?void 0:s[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return c.file}async function QP(e,t,n,o){var s;let a=await M_(e,t,n,o),c=await(a===null||a===void 0?void 0:a.json());if(((s=a===null||a===void 0?void 0:a.headers)===null||s===void 0?void 0:s[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let d=Hs(c),f=new Hi;return Object.assign(f,d),f}async function M_(e,t,n,o){var s,a,c;let d=t,f=(o===null||o===void 0?void 0:o.baseUrl)||((s=n.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(f){let v=new URL(f),E=new URL(t);E.protocol=v.protocol,E.host=v.host,E.port=v.port,d=E.toString()}let h=0,m=0,g=new yn(new Response),_="upload";h=e.size;while(m<h){let v=Math.min(N_,h-m),E=e.slice(m,m+v);if(m+v>=h)_+=", finalize";let T=0,S=k_;while(T<x_){let A=Object.assign(Object.assign({},(o===null||o===void 0?void 0:o.headers)||{}),{"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":String(m)});if(g=await n.request({path:"",body:E,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:d,headers:A})}),(a=g===null||g===void 0?void 0:g.headers)===null||a===void 0?void 0:a[sn])break;T++,await U_(S),S=S*D_}if(m+=v,((c=g===null||g===void 0?void 0:g.headers)===null||c===void 0?void 0:c[sn])!=="active")break;if(h<=m)throw Error("All content has been uploaded, but the upload status is not finalized.")}return g}async function ZP(e){return{size:e.size,type:e.type}}function U_(e){return new Promise((t)=>setTimeout(t,e))}class G_{async stat(e){let t={size:0,type:void 0};if(typeof e==="string"){let n=await Fi.stat(e);return t.size=n.size,t.type=this.inferMimeType(e),t}else return await ZP(e)}async upload(e,t,n,o){if(typeof e==="string")return await this.uploadFileFromPath(e,t,n,o);else return zP(e,t,n,o)}async uploadToFileSearchStore(e,t,n,o){if(typeof e==="string")return await this.uploadFileToFileSearchStoreFromPath(e,t,n,o);else return QP(e,t,n,o)}inferMimeType(e){let t=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"}[t.toLowerCase()]}async uploadFileFromPath(e,t,n,o){var s;let a=await this.uploadFileFromPathInternal(e,t,n,o),c=await(a===null||a===void 0?void 0:a.json());if(((s=a===null||a===void 0?void 0:a.headers)===null||s===void 0?void 0:s[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return c.file}async uploadFileToFileSearchStoreFromPath(e,t,n,o){var s;let a=await this.uploadFileFromPathInternal(e,t,n,o),c=await(a===null||a===void 0?void 0:a.json());if(((s=a===null||a===void 0?void 0:a.headers)===null||s===void 0?void 0:s[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let d=Hs(c),f=new Hi;return Object.assign(f,d),f}async uploadFileFromPathInternal(e,t,n,o){var s,a,c;let d=t,f=(o===null||o===void 0?void 0:o.baseUrl)||((s=n.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(f){let T=new URL(f),S=new URL(t);S.protocol=T.protocol,S.host=T.host,S.port=T.port,d=S.toString()}let h=0,m=0,g=new yn(new Response),_="upload",v,E=zh.basename(e);try{if(v=await Fi.open(e,"r"),!v)throw Error("Failed to open file");h=(await v.stat()).size;while(m<h){let T=Math.min(N_,h-m);if(m+T>=h)_+=", finalize";let S=new Uint8Array(T),{bytesRead:A}=await v.read(S,0,T,m);if(A!==T)throw Error(`Failed to read ${T} bytes from file at offset ${m}. bytes actually read: ${A}`);let w=new Blob([S]),P=0,N=k_;while(P<x_){let D=Object.assign(Object.assign({},(o===null||o===void 0?void 0:o.headers)||{}),{"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":String(m),"X-Goog-Upload-File-Name":E});if(g=await n.request({path:"",body:w,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:d,headers:D})}),(a=g===null||g===void 0?void 0:g.headers)===null||a===void 0?void 0:a[sn])break;P++,await U_(N),N=N*D_}if(m+=A,((c=g===null||g===void 0?void 0:g.headers)===null||c===void 0?void 0:c[sn])!=="active")break;if(h<=m)throw Error("All content has been uploaded, but the upload status is not finalized.")}return g}finally{if(v)await v.close()}}}class b_ extends a0{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let n=await e.auth.getRequestHeaders(),o=e.config||{},s=o.httpOptions||{},a=Object.assign({},s.headers||{});if(n)if(typeof n[Symbol.iterator]==="function")for(let[c,d]of n)a[c]=d;else for(let[c,d]of Object.entries(n))a[c]=d;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},o),{httpOptions:Object.assign(Object.assign({},s),{headers:a})})})}}var jP="gl-node/";function eN(e){var t;if(e&&(e.enterprise!==void 0||e.vertexai!==void 0)){if(e.enterprise!==void 0&&e.vertexai!==void 0&&e.enterprise!==e.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(t=e.enterprise)!==null&&t!==void 0?t:e.vertexai}let n=an("GOOGLE_GENAI_USE_ENTERPRISE"),o=an("GOOGLE_GENAI_USE_VERTEXAI"),s=Xh(n),a=Xh(o);if(n!==void 0&&o!==void 0&&s!==a)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.");if(n!==void 0)return s;if(o!==void 0)return a;return!1}class Pt{getNextGenClient(){let e=this.httpOptions;if(this._nextGenClient===void 0)this._nextGenClient=Nt(this.apiClient,{timeout_ms:e===null||e===void 0?void 0:e.timeout});if(e===null||e===void 0?void 0:e.extraBody)console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored.");return this._nextGenClient}get interactions(){if(this._interactions!==void 0)return this._interactions;return this._interactions=new __(this.apiClient),this._interactions}get webhooks(){if(this._webhooks!==void 0)return this._webhooks;return this._webhooks=new E_(this.apiClient),this._webhooks}get agents(){if(this._agents!==void 0)return this._agents;return console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new y_(this.apiClient),this._agents}get triggers(){if(this._triggers!==void 0)return this._triggers;return console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new v_(this.apiClient),this._triggers}get environments(){if(this._environments!==void 0)return this._environments;return console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new A_(this.apiClient),this._environments}constructor(e={}){var t,n,o,s;if(this.vertexai=eN(e),(e.project||e.location)&&!this.vertexai)throw Error("Project and location are not supported for Gemini API backend.");let a=tN(),c=an("GOOGLE_CLOUD_PROJECT"),d=an("GOOGLE_CLOUD_LOCATION");if(this.apiKey=(t=e.apiKey)!==null&&t!==void 0?t:a,this.project=(n=e.project)!==null&&n!==void 0?n:c,this.location=(o=e.location)!==null&&o!==void 0?o:d,!this.vertexai&&!this.apiKey)console.warn("API key should be set when using the Gemini API.");if(this.vertexai){if((s=e.googleAuthOptions)===null||s===void 0?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;if(!e.project&&!e.location&&(c||d)&&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;else if((e.project||e.location)&&!e.apiKey&&a)console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0;else if(!e.project&&!e.location&&!e.apiKey&&(c||d)&&a)console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0;if(!this.location&&!this.apiKey)this.location="global"}let f=zT(e.httpOptions,this.vertexai,an("GOOGLE_VERTEX_BASE_URL"),an("GOOGLE_GEMINI_BASE_URL"));if(f)if(e.httpOptions)e.httpOptions.baseUrl=f;else e.httpOptions={baseUrl:f};this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let h=new C_({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new Bm({auth:h,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:jP+process.version,uploader:new G_,downloader:new S_}),this.models=new yt(this.apiClient),this.live=new Ym(this.apiClient,h,new I_),this.batches=new Pm(this.apiClient),this.chats=new km(this.models,this.apiClient),this.caches=new Nm(this.apiClient),this.files=new b_(this.apiClient),this.operations=new zm(this.apiClient),this.authTokens=new Qm(this.apiClient),this.tunings=new P_(this.apiClient),this.fileSearchStores=new jm(this.apiClient)}}function an(e){var t,n,o;return(o=(n=(t=process===null||process===void 0?void 0:process.env)===null||t===void 0?void 0:t[e])===null||n===void 0?void 0:n.trim())!==null&&o!==void 0?o:void 0}function Xh(e){if(e===void 0)return!1;return e.toLowerCase()==="true"}function tN(){let e=an("GOOGLE_API_KEY"),t=an("GEMINI_API_KEY");if(e&&t)console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.");return e||t||void 0}var nN={THINKING_LEVEL_UNSPECIFIED:ln.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ln.MINIMAL,LOW:ln.LOW,MEDIUM:ln.MEDIUM,HIGH:ln.HIGH};function zt(e,t){let n=e.thinkingLevelMap?.[t],o=typeof n==="string"?n.toLowerCase():t;switch(o){case"minimal":case"low":case"medium":case"high":return o;default:throw Error(`Unsupported Google thinking level mapping for ${e.provider}/${e.id}: ${t} -> ${String(n)}`)}}function jt(e){let t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(t)||t==="gemini-flash-latest"||t==="gemini-flash-lite-latest"||/gemma-?4/.test(t)}function Vt(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function Kt(e){return nN[e]}function gr(e){if(!jt(e))return{thinkingBudget:0};let t=G(e,"off");if(t==="off")return{thinkingBudget:0};let n=zt(e,t),o=Vt(n);return{thinkingLevel:Kt(o)}}function yr(e){return e.thought===!0}function kt(e,t){if(typeof t==="string"&&t.length>0)return t;return e}var rN=/^[A-Za-z0-9+/]+={0,2}$/;function iN(e){if(!e)return!1;if(e.length%4!==0)return!1;return rN.test(e)}function ea(e,t){return e&&iN(t)?t:void 0}function ta(e){let t=na(e);return e.startsWith("claude-")||e.startsWith("gpt-oss-")||t!==void 0&&t>=3}function na(e){let t=e.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(!t)return;return Number.parseInt(t[1],10)}function oN(e){let t=na(e);if(t!==void 0)return t>=3;return!0}function br(e,t){let n=$t(Oe(t).messages),o=[],a=ge(n,e,(c)=>{if(!ta(e.id))return c;return c.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)});for(let c of a)if(c.role==="user")if(typeof c.content==="string")o.push({role:"user",parts:[{text:y(c.content)}]});else{let d=c.content.map((f)=>{if(f.type==="text")return{text:y(f.text)};else return{inlineData:{mimeType:f.mimeType,data:f.data}}});if(d.length===0)continue;o.push({role:"user",parts:d})}else if(c.role==="assistant"){let d=[],f=c.provider===e.provider&&c.model===e.id;for(let h of c.content)if(h.type==="text"){let m=ea(f,h.textSignature);if((!h.text||h.text.trim()==="")&&!m)continue;d.push({text:y(h.text),...m&&{thoughtSignature:m}})}else if(h.type==="thinking")if(f){let m=ea(f,h.thinkingSignature);if((!h.thinking||h.thinking.trim()==="")&&!m)continue;d.push({thought:!0,text:y(h.thinking),...m&&{thoughtSignature:m}})}else{if(!h.thinking||h.thinking.trim()==="")continue;d.push({text:y(h.thinking)})}else if(h.type==="toolCall"){let m=ea(f,h.thoughtSignature),g={functionCall:{name:h.name,args:h.arguments??{},...ta(e.id)?{id:h.id}:{}},...m&&{thoughtSignature:m}};d.push(g)}if(d.length===0)continue;o.push({role:"model",parts:d})}else if(c.role==="toolResult"){let f=c.content.filter((w)=>w.type==="text").map((w)=>w.text).join(`
|
|
38
|
-
`),h=e.input.includes("image")?c.content.filter((
|
|
39
|
-
export{
|
|
35
|
+
`];while(!0){let{done:f,value:h}=yield Pe(i.read());if(f){if(s.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let m=o.decode(h,{stream:!0});try{let E=JSON.parse(m);if("error"in E){let y=JSON.parse(JSON.stringify(E.error)),{status:v,code:C}=y,T=`got status: ${v}. ${JSON.stringify(E)}`;if(C>=400&&C<600)throw new Vi({message:T,status:C})}}catch(E){if(E.name==="ApiError")throw E}s+=m;let g=-1,_=0;while(!0){g=-1,_=0;for(let v of d){let C=s.indexOf(v);if(C!==-1&&(g===-1||C<g))g=C,_=v.length}if(g===-1)break;let E=s.substring(0,g);s=s.substring(g+_);let y=E.trim();if(y.startsWith(c)){let v=y.substring(c.length).trim();try{let C=new Response(v,{headers:e===null||e===void 0?void 0:e.headers,status:e===null||e===void 0?void 0:e.status,statusText:e===null||e===void 0?void 0:e.statusText});yield yield Pe(new yn(C))}catch(C){throw Error(`exception parsing stream chunk ${v}. ${C}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,t,n,i,o){var s,c,d,f,h,m;let g=(s=n===null||n===void 0?void 0:n.httpStatusCodes)!==null&&s!==void 0?s:ow,_=async()=>{let C=jI(i,o),T;try{T=await fetch(e,Object.assign(Object.assign({},t),{signal:C.signal}))}catch(I){throw C.dispose(),I}if(!n||T.ok||!g.includes(T.status))return T;try{await _s(T)}finally{C.dispose()}return T};if(!n)return _();let E=Math.max(1,(c=n.attempts)!==null&&c!==void 0?c:ew),y=Math.round(((d=n.initialDelay)!==null&&d!==void 0?d:tw)*1000),v=Math.max(y,Math.round(((f=n.maxDelay)!==null&&f!==void 0?f:nw)*1000));return Kh.default(_,{retries:E-1,factor:(h=n.expBase)!==null&&h!==void 0?h:rw,minTimeout:y,maxTimeout:v,randomize:((m=n.jitter)!==null&&m!==void 0?m:iw)>0,onFailedAttempt:(C)=>{var T;if(o===null||o===void 0?void 0:o.aborted)throw(T=C.error)!==null&&T!==void 0?T:C}})}getDefaultHeaders(){let e={},t=YI+" "+this.clientOptions.userAgentExtra;return e[XI]=t,e[Us]=t,e[$I]="application/json",e}async getHeadersInternal(e,t){let n=new Headers;if(e&&e.headers)for(let[i,o]of Object.entries(e.headers))n.append(i,o);if((e===null||e===void 0?void 0:e.timeout)&&e.timeout>0)n.append(JI,String(Math.ceil(e.timeout/1000)));return await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){var t;let n="";if(typeof e==="string")n=e.replace(/[/\\]+$/,""),n=(t=n.split(/[/\\]/).pop())!==null&&t!==void 0?t:"";return n}async uploadFile(e,t){var n;let i={};if(t!=null)i.mimeType=t.mimeType,i.name=t.name,i.displayName=t.displayName;if(i.name&&!i.name.startsWith("files/"))i.name=`files/${i.name}`;let o=this.clientOptions.uploader,s=await o.stat(e);i.sizeBytes=String(s.size);let c=(n=t===null||t===void 0?void 0:t.mimeType)!==null&&n!==void 0?n:s.type;if(c===void 0||c==="")throw Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=c;let d={file:i},f=this.getFileName(e),h=z("upload/v1beta/files",d._url),m=await this.fetchUploadUrl(h,i.sizeBytes,i.mimeType,f,d,t===null||t===void 0?void 0:t.httpOptions);return o.upload(e,m,this)}async uploadFileToFileSearchStore(e,t,n){var i;let o=this.clientOptions.uploader,s=await o.stat(t),c=String(s.size),d=(i=n===null||n===void 0?void 0:n.mimeType)!==null&&i!==void 0?i:s.type;if(d===void 0||d==="")throw Error("Can not determine mimeType. Please provide mimeType in the config.");let f=`upload/v1beta/${e}:uploadToFileSearchStore`,h=this.getFileName(t),m={};if(n!=null)Vm(n,m);let g=await this.fetchUploadUrl(f,c,d,h,m,n===null||n===void 0?void 0:n.httpOptions);return o.uploadToFileSearchStore(t,g,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,i,o,s){var c;let d={};if(s)d=s;else d={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`},i?{"X-Goog-Upload-File-Name":i}:{})};let f=await this.request({path:e,body:JSON.stringify(o),httpMethod:"POST",httpOptions:d});if(!f||!(f===null||f===void 0?void 0:f.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let h=(c=f===null||f===void 0?void 0:f.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(h===void 0)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return h}}async function _s(e){var t;if(e===void 0)throw Error("response is undefined");if(!e.ok){let n=e.status,i;if((t=e.headers.get("content-type"))===null||t===void 0?void 0:t.includes("application/json"))i=await e.json();else i={error:{message:await e.text(),code:e.status,status:e.statusText}};let o=JSON.stringify(i);if(n>=400&&n<600)throw new Vi({message:o,status:n});throw Error(o)}}function sw(e,t){if(!t||Object.keys(t).length===0)return;if(e.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 e.body==="string"&&e.body.length>0)try{let s=JSON.parse(e.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(s){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function i(s,c){let d=Object.assign({},s);for(let f in c)if(Object.prototype.hasOwnProperty.call(c,f)){let h=c[f],m=d[f];if(h&&typeof h==="object"&&!Array.isArray(h)&&m&&typeof m==="object"&&!Array.isArray(m))d[f]=i(m,h);else{if(m&&h&&typeof m!==typeof h)console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${f}". Original type: ${typeof m}, New type: ${typeof h}. Overwriting.`);d[f]=h}}return d}let o=i(n,t);e.body=JSON.stringify(o)}var aw="mcp_used/unknown",lw=!1;function $m(e){for(let t of e){if(uw(t))return!0;if(typeof t==="object"&&"inputSchema"in t)return!0}return lw}function Jm(e){var t;let n=(t=e[Us])!==null&&t!==void 0?t:"";e[Us]=(n+` ${aw}`).trimStart()}function uw(e){return e!==null&&typeof e==="object"&&e instanceof Ys}function cw(e){return Xn(this,arguments,function*(n,i=100){let o=void 0,s=0;while(s<i){let c=yield Pe(n.listTools({cursor:o}));for(let d of c.tools)yield yield Pe(d),s++;if(!c.nextCursor)break;o=c.nextCursor}})}class Ys{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new Ys(e,t)}async initialize(){var e,t,n,i;if(this.mcpTools.length>0)return;let o={},s=[];for(let h of this.mcpClients)try{for(var c=!0,d=(t=void 0,mr(cw(h))),f;f=await d.next(),e=f.done,!e;c=!0){i=f.value,c=!1;let m=i;s.push(m);let g=m.name;if(o[g])throw Error(`Duplicate function name ${g} found in MCP tools. Please ensure function names are unique.`);o[g]=h}}catch(m){t={error:m}}finally{try{if(!c&&!e&&(n=d.return))await n.call(d)}finally{if(t)throw t.error}}this.mcpTools=s,this.functionNameToMcpClient=o}async tool(){return await this.initialize(),_A(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let n of e)if(n.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[n.name],o=void 0;if(this.config.timeout)o={timeout:this.config.timeout};let s=await i.callTool({name:n.name,arguments:n.args},void 0,o);t.push({functionResponse:{name:n.name,response:s.isError?{error:s}:s}})}return t}}async function dw(e,t,n){let i=new pm,o;if(n.data instanceof Blob)o=JSON.parse(await n.data.text());else o=JSON.parse(n.data);Object.assign(i,o),t(i)}class Xm{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){var t,n;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),o=this.apiClient.getApiVersion(),s=pw(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${i}/ws/google.ai.generativelanguage.${o}.GenerativeService.BidiGenerateMusic?key=${c}`,f=()=>{},h=new Promise((I)=>{f=I}),m=e.callbacks,g=function(){f({})},_=this.apiClient,E={onopen:g,onmessage:(I)=>{dw(_,m.onmessage,I)},onerror:(t=m===null||m===void 0?void 0:m.onerror)!==null&&t!==void 0?t:function(I){},onclose:(n=m===null||m===void 0?void 0:m.onclose)!==null&&n!==void 0?n:function(I){}},y=this.webSocketFactory.create(d,fw(s),E);y.connect(),await h;let T={setup:{model:de(this.apiClient,e.model)}};return y.send(JSON.stringify(T)),new Km(y,this.apiClient)}}class Km{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw Error("Weighted prompts must be set and contain at least one entry.");let t=A0(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){if(!e.musicGenerationConfig)e.musicGenerationConfig={};let t=T0(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Bn.PLAY)}pause(){this.sendPlaybackControl(Bn.PAUSE)}stop(){this.sendPlaybackControl(Bn.STOP)}resetContext(){this.sendPlaybackControl(Bn.RESET_CONTEXT)}close(){this.conn.close()}}function fw(e){let t={};return e.forEach((n,i)=>{t[i]=n}),t}function pw(e){let t=new Headers;for(let[n,i]of Object.entries(e))t.append(n,i);return t}var hw="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function mw(e,t,n){let i=new fm,o;if(n.data instanceof Blob)o=await n.data.text();else if(n.data instanceof ArrayBuffer)o=new TextDecoder().decode(n.data);else o=n.data;let s=JSON.parse(o);if(e.isVertexAI()){let c=I0(s);Object.assign(i,c)}else Object.assign(i,s);t(i)}class Ym{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Xm(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,n,i,o,s,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),f=this.apiClient.getApiVersion(),h,m=this.apiClient.getHeaders();if(e.config&&e.config.tools&&$m(e.config.tools))Jm(m);let g=yw(m);if(this.apiClient.isVertexAI()){let W=this.apiClient.getProject(),H=this.apiClient.getLocation(),oe=this.apiClient.getApiKey(),se=!!W&&!!H||!!oe;if(this.apiClient.getCustomBaseUrl()&&!se)h=d;else h=`${d}/ws/google.cloud.aiplatform.${f}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(g,h)}else{let W=this.apiClient.getApiKey(),H="BidiGenerateContent",oe="key";if(W===null||W===void 0?void 0:W.startsWith("auth_tokens/")){if(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),f!=="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.");H="BidiGenerateContentConstrained",oe="access_token"}h=`${d}/ws/google.ai.generativelanguage.${f}.GenerativeService.${H}?${oe}=${W}`}let _=()=>{},E=new Promise((W)=>{_=W}),y=e.callbacks,v=function(){var W;(W=y===null||y===void 0?void 0:y.onopen)===null||W===void 0||W.call(y),_({})},C=this.apiClient,T=!1,I=[],P=()=>{},N=new Promise((W)=>{P=W}),D={onopen:v,onmessage:(W)=>{mw(C,(H)=>{if(H.setupComplete&&!ne.setupComplete)ne.setupComplete=H.setupComplete,P({});if(T)y.onmessage(H);else I.push(H)},W)},onerror:(t=y===null||y===void 0?void 0:y.onerror)!==null&&t!==void 0?t:function(W){},onclose:(n=y===null||y===void 0?void 0:y.onclose)!==null&&n!==void 0?n:function(W){}},q=this.webSocketFactory.create(h,_w(g),D);q.connect(),await E;let V=de(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&V.startsWith("publishers/")){let W=this.apiClient.getProject(),H=this.apiClient.getLocation();if(W&&H)V=`projects/${W}/locations/${H}/`+V}let J={};if(this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0)if(e.config===void 0)e.config={responseModalities:[Ui.AUDIO]};else e.config.responseModalities=[Ui.AUDIO];if((o=e.config)===null||o===void 0?void 0:o.generationConfig)console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let L=(c=(s=e.config)===null||s===void 0?void 0:s.tools)!==null&&c!==void 0?c:[],Y=[];for(let W of L)if(this.isCallableTool(W)){let H=W;Y.push(await H.tool())}else Y.push(W);if(Y.length>0)e.config.tools=Y;let Z={model:V,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI())J=v0(this.apiClient,Z);else J=E0(this.apiClient,Z);delete J.config;let ne=new Wm(q,this.apiClient);q.send(JSON.stringify(J)),await N,T=!0;for(let W of I)y.onmessage(W);return ne}isCallableTool(e){return"callTool"in e&&typeof e.callTool==="function"}}var gw={turnComplete:!0};class Wm{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let n=[];try{if(n=We(t.turns),!e.isVertexAI())n=n.map((i)=>Sr(i))}catch(i){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(t.functionResponses==null)throw Error("functionResponses is required.");if(!Array.isArray(t.functionResponses))n=[t.functionResponses];else n=t.functionResponses;if(n.length===0)throw Error("functionResponses is required.");for(let o of n){if(typeof o!=="object"||o===null||!("name"in o)||!("response"in o))throw Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw Error(hw)}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},gw),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};if(this.apiClient.isVertexAI())t={realtimeInput:S0(e)};else t={realtimeInput:C0(e)};this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(e.functionResponses==null)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function _w(e){let t={};return e.forEach((n,i)=>{t[i]=n}),t}function yw(e){let t=new Headers;for(let[n,i]of Object.entries(e))t.append(n,i);return t}var wh=10;function Rh(e){var t,n,i;if((t=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||t===void 0?void 0:t.disable)return!0;let o=!1;for(let c of(n=e===null||e===void 0?void 0:e.tools)!==null&&n!==void 0?n:[])if(Kn(c)){o=!0;break}if(!o)return!0;let s=(i=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;if(s&&(s<0||!Number.isInteger(s))||s==0)return 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;return!1}function Kn(e){return"callTool"in e&&typeof e.callTool==="function"}function Ew(e){var t,n,i;return(i=(n=(t=e.config)===null||t===void 0?void 0:t.tools)===null||n===void 0?void 0:n.some((o)=>Kn(o)))!==null&&i!==void 0?i:!1}function Ph(e){var t;let n=[];if(!((t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.tools))return n;return e.config.tools.forEach((i,o)=>{if(Kn(i))return;let s=i;if(s.functionDeclarations&&s.functionDeclarations.length>0)n.push(o)}),n}function Nh(e){var t;return!((t=e===null||e===void 0?void 0:e.automaticFunctionCalling)===null||t===void 0?void 0:t.ignoreCallHistory)}class yt extends xt{constructor(e){super();this.apiClient=e,this.embedContent=async(t)=>{if(!this.apiClient.isVertexAI()){if(t.model.includes("gemini-embedding-2"))t.contents=We(t.contents);return await this.embedContentInternal(t)}if(t.model.includes("gemini")&&t.model!=="gemini-embedding-001"||t.model.includes("maas")){let i=We(t.contents);if(i.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let o=Object.assign(Object.assign({},t),{content:i[0],embeddingApiType:Gi.EMBED_CONTENT});return await this.embedContentInternal(o)}else{let i=Object.assign(Object.assign({},t),{embeddingApiType:Gi.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async(t)=>{var n,i,o,s,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchema(t),!Ew(t)||Rh(t.config))return await this.generateContentInternal(d);let f=Ph(t);if(f.length>0){let y=f.map((v)=>`tools[${v}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${y}.`)}let h,m,g=We(d.contents),_=(o=(i=(n=d.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:wh,E=0;while(E<_){if(h=await this.generateContentInternal(d),!h.functionCalls||h.functionCalls.length===0)break;let y=h.candidates[0].content,v=[];for(let C of(c=(s=t.config)===null||s===void 0?void 0:s.tools)!==null&&c!==void 0?c:[])if(Kn(C)){let I=await C.callTool(h.functionCalls);v.push(...I)}if(E++,m={role:"user",parts:v},d.contents=We(d.contents),d.contents.push(y),d.contents.push(m),Nh(d.config))g.push(y),g.push(m)}if(Nh(d.config))h.automaticFunctionCallingHistory=g;return h},this.generateContentStream=async(t)=>{var n,i,o,s,c;if(this.maybeMoveToResponseJsonSchema(t),Rh(t.config)){let m=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(m)}let d=Ph(t);if(d.length>0){let m=d.map((g)=>`tools[${g}]`).join(", ");throw Error(`Incompatible tools found at ${m}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let f=(o=(i=(n=t===null||t===void 0?void 0:t.config)===null||n===void 0?void 0:n.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||o===void 0?void 0:o.streamFunctionCallArguments,h=(c=(s=t===null||t===void 0?void 0:t.config)===null||s===void 0?void 0:s.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(f&&!h)throw 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(t)},this.generateImages=async(t)=>{if(!yt.loggedGenerateImagesWarning)yt.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images");return await this.generateImagesInternal(t).then((n)=>{var i;let o,s=[];if(n===null||n===void 0?void 0:n.generatedImages)for(let d of n.generatedImages)if(d&&(d===null||d===void 0?void 0:d.safetyAttributes)&&((i=d===null||d===void 0?void 0:d.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt")o=d===null||d===void 0?void 0:d.safetyAttributes;else s.push(d);let c;if(o)c={generatedImages:s,positivePromptSafetyAttributes:o,sdkHttpResponse:n.sdkHttpResponse};else c={generatedImages:s,sdkHttpResponse:n.sdkHttpResponse};return c})},this.list=async(t)=>{var n;let s={config:Object.assign(Object.assign({},{queryBase:!0}),t===null||t===void 0?void 0:t.config)};if(this.apiClient.isVertexAI()){if(!s.config.queryBase)if((n=s.config)===null||n===void 0?void 0:n.filter)throw Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");else s.config.filter="labels.tune-type:*"}return new pn(qt.PAGED_ITEM_MODELS,(c)=>this.listInternal(c),await this.listInternal(s),s)},this.editImage=async(t)=>{if(!yt.loggedEditImageWarning)yt.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image");let n={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};if(t.referenceImages){if(t.referenceImages)n.referenceImages=t.referenceImages.map((i)=>i.toReferenceImageAPI())}return await this.editImageInternal(n)},this.upscaleImage=async(t)=>{let n={numberOfImages:1,mode:"upscale"};if(t.config)n=Object.assign(Object.assign({},n),t.config);let i={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:n};return await this.upscaleImageInternal(i)},this.generateVideos=async(t)=>{var n,i,o,s,c,d;if((t.prompt||t.image||t.video)&&t.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");if(t.prompt||t.image||t.video){if(!yt.loggedGenerateVideosWarning)yt.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead.")}if(!this.apiClient.isVertexAI()){if(((n=t.video)===null||n===void 0?void 0:n.uri)&&((i=t.video)===null||i===void 0?void 0:i.videoBytes))t.video={uri:t.video.uri,mimeType:t.video.mimeType};else if(((s=(o=t.source)===null||o===void 0?void 0:o.video)===null||s===void 0?void 0:s.uri)&&((d=(c=t.source)===null||c===void 0?void 0:c.video)===null||d===void 0?void 0:d.videoBytes))t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType}}return await this.generateVideosInternal(t)}}maybeMoveToResponseJsonSchema(e){if(e.config&&e.config.responseSchema){if(!e.config.responseJsonSchema){if(Object.keys(e.config.responseSchema).includes("$schema"))e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema}}return}async processParamsMaybeAddMcpUsage(e){var t,n,i;let o=(t=e.config)===null||t===void 0?void 0:t.tools;if(!o)return e;let s=await Promise.all(o.map(async(d)=>{if(Kn(d))return await d.tool();return d})),c={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:s})};if(c.config.tools=s,e.config&&e.config.tools&&$m(e.config.tools)){let d=(i=(n=e.config.httpOptions)===null||n===void 0?void 0:n.headers)!==null&&i!==void 0?i:{},f=Object.assign({},d);if(Object.keys(f).length===0)f=this.apiClient.getDefaultHeaders();Jm(f),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:f})}return c}async initAfcToolsMap(e){var t,n,i;let o=new Map;for(let s of(n=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&n!==void 0?n:[])if(Kn(s)){let c=s,d=await c.tool();for(let f of(i=d.functionDeclarations)!==null&&i!==void 0?i:[]){if(!f.name)throw Error("Function declaration name is required.");if(o.has(f.name))throw Error(`Duplicate tool declaration name: ${f.name}`);o.set(f.name,c)}}return o}async processAfcStream(e){var t,n,i;let o=(i=(n=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||n===void 0?void 0:n.maximumRemoteCalls)!==null&&i!==void 0?i:wh,s=!1,c=0,d=await this.initAfcToolsMap(e);return function(f,h,m){return Xn(this,arguments,function*(){var g,_,E,y,v,C;while(c<o){if(s)c++,s=!1;let N=yield Pe(f.processParamsMaybeAddMcpUsage(m)),D=yield Pe(f.generateContentStreamInternal(N)),q=[],V=[];try{for(var T=!0,I=(_=void 0,mr(D)),P;P=yield Pe(I.next()),g=P.done,!g;T=!0){y=P.value,T=!1;let J=y;if(yield yield Pe(J),J.candidates&&((v=J.candidates[0])===null||v===void 0?void 0:v.content)){V.push(J.candidates[0].content);for(let L of(C=J.candidates[0].content.parts)!==null&&C!==void 0?C:[])if(c<o&&L.functionCall){if(!L.functionCall.name)throw Error("Function call name was not returned by the model.");if(!h.has(L.functionCall.name))throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${h.keys()}, missing tool: ${L.functionCall.name}`);else{let Y=yield Pe(h.get(L.functionCall.name).callTool([L.functionCall]));q.push(...Y)}}}}}catch(J){_={error:J}}finally{try{if(!T&&!g&&(E=I.return))yield Pe(E.call(I))}finally{if(_)throw _.error}}if(q.length>0){s=!0;let J=new Hn;J.candidates=[{content:{role:"user",parts:q}}],yield yield Pe(J);let L=[];L.push(...V),L.push({role:"user",parts:q});let Y=We(m.contents).concat(L);m.contents=Y}else break}})}(this,d,e)}async generateContentInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=Ch(this.apiClient,e);return c=z("{model}:generateContent",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=Ih(h),g=new Hn;return Object.assign(g,m),g})}else{let f=Ah(this.apiClient,e);return c=z("{model}:generateContent",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=Sh(h),g=new Hn;return Object.assign(g,m),g})}}async generateContentStreamInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=Ch(this.apiClient,e);return c=z("{model}:streamGenerateContent?alt=sse",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}),s.then(function(m){return Xn(this,arguments,function*(){var g,_,E,y;try{for(var v=!0,C=mr(m),T;T=yield Pe(C.next()),g=T.done,!g;v=!0){y=T.value,v=!1;let I=y,P=Ih(yield Pe(I.json()),e);P.sdkHttpResponse={headers:I.headers};let N=new Hn;Object.assign(N,P),yield yield Pe(N)}}catch(I){_={error:I}}finally{try{if(!v&&!g&&(E=C.return))yield Pe(E.call(C))}finally{if(_)throw _.error}}})})}else{let f=Ah(this.apiClient,e);return c=z("{model}:streamGenerateContent?alt=sse",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),s.then(function(m){return Xn(this,arguments,function*(){var g,_,E,y;try{for(var v=!0,C=mr(m),T;T=yield Pe(C.next()),g=T.done,!g;v=!0){y=T.value,v=!1;let I=y,P=Sh(yield Pe(I.json()),e);P.sdkHttpResponse={headers:I.headers};let N=new Hn;Object.assign(N,P),yield yield Pe(N)}}catch(I){_={error:I}}finally{try{if(!v&&!g&&(E=C.return))yield Pe(E.call(C))}finally{if(_)throw _.error}}})})}}async embedContentInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=cS(this.apiClient,e,e),h=EA(e.model)?"{model}:embedContent":"{model}:predict";return c=z(h,f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((m)=>m.json().then((g)=>{let _=g;return _.sdkHttpResponse={headers:m.headers},_})),s.then((m)=>{let g=fS(m,e),_=new As;return Object.assign(_,g),_})}else{let f=uS(this.apiClient,e);return c=z("{model}:batchEmbedContents",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=dS(h),g=new As;return Object.assign(g,m),g})}}async generateImagesInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=vS(this.apiClient,e);return o=z("{model}:predict",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=TS(d),h=new Qh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=oS(this.apiClient,e);return o=z("{model}:predict",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=sS(d),h=new Zh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=CI(this.apiClient,e);return o=z("{model}:predict",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=SI(d),h=new jh;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=tI(this.apiClient,e);return o=z("{model}:predict",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=nI(d),h=new em;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=uI(this.apiClient,e);return o=z("{model}:predict",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=cI(d),h=new tm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=LS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>Ms(h))}else{let f=bS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>Ds(h))}}async listInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=JS(this.apiClient,e);return c=z("{models_url}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=KS(h),g=new Cs;return Object.assign(g,m),g})}else{let f=$S(this.apiClient,e);return c=z("{models_url}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=XS(h),g=new Cs;return Object.assign(g,m),g})}}async update(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=TI(this.apiClient,e);return c=z("{model}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>Ms(h))}else{let f=vI(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>Ds(h))}}async delete(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=tS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=rS(h),g=new Ss;return Object.assign(g,m),g})}else{let f=eS(this.apiClient,e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=nS(h),g=new Ss;return Object.assign(g,m),g})}}async countTokens(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=Q0(this.apiClient,e);return c=z("{model}:countTokens",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=j0(h),g=new Is;return Object.assign(g,m),g})}else{let f=z0(this.apiClient,e);return c=z("{model}:countTokens",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=Z0(h),g=new Is;return Object.assign(g,m),g})}}async computeTokens(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=V0(this.apiClient,e);return o=z("{model}:computeTokens",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=B0(d),h=new nm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=RS(this.apiClient,e);return c=z("{model}:predictLongRunning",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s.then((h)=>{let m=IS(h),g=new bi;return Object.assign(g,m),g})}else{let f=wS(this.apiClient,e);return c=z("{model}:predictLongRunning",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s.then((h)=>{let m=SS(h),g=new bi;return Object.assign(g,m),g})}}}yt.loggedGenerateImagesWarning=!1;yt.loggedEditImageWarning=!1;yt.loggedGenerateVideosWarning=!1;class zm extends xt{constructor(e){super();this.apiClient=e}async getVideosOperation(e){let{operation:t,config:n}=e;if(t.name===void 0||t.name==="")throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],o=void 0;if(n&&"httpOptions"in n)o=n.httpOptions;let s=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:s,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let{operation:t,config:n}=e;if(t.name===void 0||t.name==="")throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],o=void 0;if(n&&"httpOptions"in n)o=n.httpOptions;let s=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:s,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=sA(e);return c=z("{operationName}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json()),s}else{let f=oA(e);return c=z("{operationName}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json()),s}}async fetchPredictVideosOperationInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=ZT(e);return o=z("{resourceName}:fetchPredictOperation",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}function vw(e){let t={},n=l(e,["apiKey"]);if(n!=null)u(t,["apiKey"],n);if(l(e,["apiKeyConfig"])!==void 0)throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["authType"])!==void 0)throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["googleServiceAccountConfig"])!==void 0)throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["httpBasicAuthConfig"])!==void 0)throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oauthConfig"])!==void 0)throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["oidcConfig"])!==void 0)throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Tw(e){let t={},n=l(e,["data"]);if(n!=null)u(t,["data"],n);if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function Aw(e){let t={},n=l(e,["parts"]);if(n!=null){let o=n;if(Array.isArray(o))o=o.map((s)=>kw(s));u(t,["parts"],o)}let i=l(e,["role"]);if(i!=null)u(t,["role"],i);return t}function Cw(e,t,n){let i={},o=l(t,["expireTime"]);if(n!==void 0&&o!=null)u(n,["expireTime"],o);let s=l(t,["newSessionExpireTime"]);if(n!==void 0&&s!=null)u(n,["newSessionExpireTime"],s);let c=l(t,["uses"]);if(n!==void 0&&c!=null)u(n,["uses"],c);let d=l(t,["liveConnectConstraints"]);if(n!==void 0&&d!=null)u(n,["bidiGenerateContentSetup"],xw(e,d));let f=l(t,["lockAdditionalFields"]);if(n!==void 0&&f!=null)u(n,["fieldMask"],f);return i}function Sw(e,t){let n={},i=l(t,["config"]);if(i!=null)u(n,["config"],Cw(e,i,n));return n}function Iw(e){let t={};if(l(e,["displayName"])!==void 0)throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["fileUri"]);if(n!=null)u(t,["fileUri"],n);let i=l(e,["mimeType"]);if(i!=null)u(t,["mimeType"],i);return t}function ww(e){let t={},n=l(e,["args"]);if(n!=null)u(t,["args"],n);let i=l(e,["id"]);if(i!=null)u(t,["id"],i);let o=l(e,["name"]);if(o!=null)u(t,["name"],o);if(l(e,["partialArgs"])!==void 0)throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["willContinue"])!==void 0)throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Rw(e){let t={},n=l(e,["authConfig"]);if(n!=null)u(t,["authConfig"],vw(n));let i=l(e,["enableWidget"]);if(i!=null)u(t,["enableWidget"],i);if(l(e,["groundingTypes"])!==void 0)throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Pw(e){let t={};if(l(e,["blockingConfidence"])!==void 0)throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["excludeDomains"])!==void 0)throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["searchTypes"]);if(n!=null)u(t,["searchTypes"],n);let i=l(e,["timeRangeFilter"]);if(i!=null)u(t,["timeRangeFilter"],i);return t}function Nw(e,t){let n={},i=l(e,["generationConfig"]);if(t!==void 0&&i!=null)u(t,["setup","generationConfig"],i);let o=l(e,["responseModalities"]);if(t!==void 0&&o!=null)u(t,["setup","generationConfig","responseModalities"],o);let s=l(e,["temperature"]);if(t!==void 0&&s!=null)u(t,["setup","generationConfig","temperature"],s);let c=l(e,["topP"]);if(t!==void 0&&c!=null)u(t,["setup","generationConfig","topP"],c);let d=l(e,["topK"]);if(t!==void 0&&d!=null)u(t,["setup","generationConfig","topK"],d);let f=l(e,["maxOutputTokens"]);if(t!==void 0&&f!=null)u(t,["setup","generationConfig","maxOutputTokens"],f);let h=l(e,["mediaResolution"]);if(t!==void 0&&h!=null)u(t,["setup","generationConfig","mediaResolution"],h);let m=l(e,["seed"]);if(t!==void 0&&m!=null)u(t,["setup","generationConfig","seed"],m);let g=l(e,["speechConfig"]);if(t!==void 0&&g!=null)u(t,["setup","generationConfig","speechConfig"],Xs(g));let _=l(e,["thinkingConfig"]);if(t!==void 0&&_!=null)u(t,["setup","generationConfig","thinkingConfig"],_);let E=l(e,["enableAffectiveDialog"]);if(t!==void 0&&E!=null)u(t,["setup","generationConfig","enableAffectiveDialog"],E);let y=l(e,["systemInstruction"]);if(t!==void 0&&y!=null)u(t,["setup","systemInstruction"],Aw(qe(y)));let v=l(e,["tools"]);if(t!==void 0&&v!=null){let L=zn(v);if(Array.isArray(L))L=L.map((Y)=>Uw(Wn(Y)));u(t,["setup","tools"],L)}let C=l(e,["sessionResumption"]);if(t!==void 0&&C!=null)u(t,["setup","sessionResumption"],Mw(C));let T=l(e,["inputAudioTranscription"]);if(t!==void 0&&T!=null)u(t,["setup","inputAudioTranscription"],T);let I=l(e,["outputAudioTranscription"]);if(t!==void 0&&I!=null)u(t,["setup","outputAudioTranscription"],I);let P=l(e,["realtimeInputConfig"]);if(t!==void 0&&P!=null)u(t,["setup","realtimeInputConfig"],P);let N=l(e,["contextWindowCompression"]);if(t!==void 0&&N!=null)u(t,["setup","contextWindowCompression"],N);let D=l(e,["proactivity"]);if(t!==void 0&&D!=null)u(t,["setup","proactivity"],D);if(l(e,["explicitVadSignal"])!==void 0)throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let q=l(e,["avatarConfig"]);if(t!==void 0&&q!=null)u(t,["setup","avatarConfig"],q);let V=l(e,["safetySettings"]);if(t!==void 0&&V!=null){let L=V;if(Array.isArray(L))L=L.map((Y)=>Dw(Y));u(t,["setup","safetySettings"],L)}let J=l(e,["translationConfig"]);if(t!==void 0&&J!=null)u(t,["setup","generationConfig","translationConfig"],J);return n}function xw(e,t){let n={},i=l(t,["model"]);if(i!=null)u(n,["setup","model"],de(e,i));let o=l(t,["config"]);if(o!=null)u(n,["config"],Nw(o,n));return n}function kw(e){let t={},n=l(e,["mediaResolution"]);if(n!=null)u(t,["mediaResolution"],n);let i=l(e,["toolCall"]);if(i!=null)u(t,["toolCall"],i);let o=l(e,["toolResponse"]);if(o!=null)u(t,["toolResponse"],o);let s=l(e,["audioTranscription"]);if(s!=null)u(t,["audioTranscription"],s);let c=l(e,["codeExecutionResult"]);if(c!=null)u(t,["codeExecutionResult"],c);let d=l(e,["executableCode"]);if(d!=null)u(t,["executableCode"],d);let f=l(e,["fileData"]);if(f!=null)u(t,["fileData"],Iw(f));let h=l(e,["functionCall"]);if(h!=null)u(t,["functionCall"],ww(h));let m=l(e,["functionResponse"]);if(m!=null)u(t,["functionResponse"],m);let g=l(e,["inlineData"]);if(g!=null)u(t,["inlineData"],Tw(g));let _=l(e,["text"]);if(_!=null)u(t,["text"],_);let E=l(e,["thought"]);if(E!=null)u(t,["thought"],E);let y=l(e,["thoughtSignature"]);if(y!=null)u(t,["thoughtSignature"],y);let v=l(e,["videoMetadata"]);if(v!=null)u(t,["videoMetadata"],v);let C=l(e,["partMetadata"]);if(C!=null)u(t,["partMetadata"],C);let T=l(e,["mediaProcessing"]);if(T!=null)u(t,["mediaProcessing"],T);return t}function Dw(e){let t={},n=l(e,["category"]);if(n!=null)u(t,["category"],n);if(l(e,["method"])!==void 0)throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["threshold"]);if(i!=null)u(t,["threshold"],i);return t}function Mw(e){let t={},n=l(e,["handle"]);if(n!=null)u(t,["handle"],n);if(l(e,["transparent"])!==void 0)throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Uw(e){let t={};if(l(e,["retrieval"])!==void 0)throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=l(e,["googleMaps"]);if(n!=null)u(t,["googleMaps"],Rw(n));let i=l(e,["mcpServers"]);if(i!=null){let g=i;if(Array.isArray(g))g=g.map((_)=>_);u(t,["mcpServers"],g)}let o=l(e,["codeExecution"]);if(o!=null)u(t,["codeExecution"],o);let s=l(e,["computerUse"]);if(s!=null)u(t,["computerUse"],s);if(l(e,["enterpriseWebSearch"])!==void 0)throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["exaAiSearch"])!==void 0)throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=l(e,["functionDeclarations"]);if(c!=null){let g=c;if(Array.isArray(g))g=g.map((_)=>_);u(t,["functionDeclarations"],g)}let d=l(e,["googleSearch"]);if(d!=null)u(t,["googleSearch"],Pw(d));let f=l(e,["googleSearchRetrieval"]);if(f!=null)u(t,["googleSearchRetrieval"],f);if(l(e,["parallelAiSearch"])!==void 0)throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=l(e,["urlContext"]);if(h!=null)u(t,["urlContext"],h);let m=l(e,["fileSearch"]);if(m!=null)u(t,["fileSearch"],m);return t}function Gw(e){let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let i=e[n];if(typeof i==="object"&&i!=null&&Object.keys(i).length>0){let o=Object.keys(i).map((s)=>`${n}.${s}`);t.push(...o)}else t.push(n)}return t.join(",")}function bw(e,t){let n=null,i=e.bidiGenerateContentSetup;if(typeof i==="object"&&i!==null&&"setup"in i){let s=i.setup;if(typeof s==="object"&&s!==null)e.bidiGenerateContentSetup=s,n=s;else delete e.bidiGenerateContentSetup}else if(i!==void 0)delete e.bidiGenerateContentSetup;let o=e.fieldMask;if(n){let s=Gw(n);if(Array.isArray(t===null||t===void 0?void 0:t.lockAdditionalFields)&&(t===null||t===void 0?void 0:t.lockAdditionalFields.length)===0)if(s)e.fieldMask=s;else delete e.fieldMask;else if((t===null||t===void 0?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){let c=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],d=[];if(o.length>0)d=o.map((h)=>{if(c.includes(h))return`generationConfig.${h}`;return h});let f=[];if(s)f.push(s);if(d.length>0)f.push(...d);if(f.length>0)e.fieldMask=f.join(",");else delete e.fieldMask}else delete e.fieldMask}else if(o!==null&&Array.isArray(o)&&o.length>0)e.fieldMask=o.join(",");else delete e.fieldMask;return e}class Qm extends xt{constructor(e){super();this.apiClient=e}async create(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");else{let c=Sw(this.apiClient,e);o=z("auth_tokens",c._url),s=c._query,delete c.config,delete c._url,delete c._query;let d=bw(c,e.config);return i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((f)=>f.json()),i.then((f)=>f)}}}function Lw(e,t){let n={},i=l(e,["force"]);if(t!==void 0&&i!=null)u(t,["_query","force"],i);return n}function qw(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);let i=l(e,["config"]);if(i!=null)Lw(i,t);return t}function Ow(e){let t={},n=l(e,["name"]);if(n!=null)u(t,["_url","name"],n);return t}function Fw(e,t){let n={},i=l(e,["pageSize"]);if(t!==void 0&&i!=null)u(t,["_query","pageSize"],i);let o=l(e,["pageToken"]);if(t!==void 0&&o!=null)u(t,["_query","pageToken"],o);return n}function Hw(e){let t={},n=l(e,["parent"]);if(n!=null)u(t,["_url","parent"],n);let i=l(e,["config"]);if(i!=null)Fw(i,t);return t}function Vw(e){let t={},n=l(e,["sdkHttpResponse"]);if(n!=null)u(t,["sdkHttpResponse"],n);let i=l(e,["nextPageToken"]);if(i!=null)u(t,["nextPageToken"],i);let o=l(e,["documents"]);if(o!=null){let s=o;if(Array.isArray(s))s=s.map((c)=>c);u(t,["documents"],s)}return t}class Zm extends xt{constructor(e){super();this.apiClient=e,this.list=async(t)=>new pn(qt.PAGED_ITEM_DOCUMENTS,(n)=>this.listInternal({parent:t.parent,config:n.config}),await this.listInternal(t),t)}async get(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=Ow(e);return o=z("{name}",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>d)}}async delete(e){var t,n;let i="",o={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let s=qw(e);i=z("{name}",s._url),o=s._query,delete s._url,delete s._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}}async listInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=Hw(e);return o=z("{parent}/documents",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=Vw(d),h=new om;return Object.assign(h,f),h})}}}class jm extends xt{constructor(e,t=new Zm(e)){super();this.apiClient=e,this.documents=t,this.list=async(n={})=>new pn(qt.PAGED_ITEM_FILE_SEARCH_STORES,(i)=>this.listInternal(i),await this.listInternal(n),n)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw 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,t){if(this.apiClient.isVertexAI())throw Error("This method is only supported in the Gemini Developer client.");let n=new URL(e,"http://dummy.com"),i=n.pathname;if(i.startsWith("/"))i=i.slice(1);if(!i.includes("/media/"))throw Error(`Invalid uri format: ${e}. Expected to contain /media/`);let o={};n.searchParams.forEach((d,f)=>{o[f]=d}),o.alt="media";let s=Object.assign({},t===null||t===void 0?void 0:t.httpOptions),c=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:o,httpOptions:s});if(c instanceof yn){let d=await c.responseInternal.arrayBuffer();return new Uint8Array(d)}else throw Error("Unexpected response type from downloadMedia")}async create(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=kI(this.apiClient,e);return o=z("fileSearchStores",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>d)}}async get(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=UI(e);return o=z("{name}",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>d)}}async delete(e){var t,n;let i="",o={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let s=MI(e);i=z("{name}",s._url),o=s._query,delete s._url,delete s._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal})}}async listInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=FI(e);return o=z("fileSearchStores",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=HI(d),h=new sm;return Object.assign(h,f),h})}}async uploadToFileSearchStoreInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=VI(e);return o=z("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=BI(d),h=new am;return Object.assign(h,f),h})}}async importFile(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=LI(e);return o=z("{file_search_store_name}:importFile",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json()),i.then((d)=>{let f=bI(d),h=new Vs;return Object.assign(h,f),h})}}}function Bw(){if("Deno"in globalThis)return!0;return!1}var Pi=void 0;function gr(){var e,t,n,i,o,s;if(Pi)return Pi;let c=globalThis,d={};if(Bw())d=(i=(n=(t=(e=c.Deno)===null||e===void 0?void 0:e.env)===null||t===void 0?void 0:t.toObject)===null||n===void 0?void 0:n.call(t))!==null&&i!==void 0?i:{};else d=(s=(o=c.process)===null||o===void 0?void 0:o.env)!==null&&s!==void 0?s:{};return Pi=d,Pi}function $w(e){var t,n;let i=Object.assign({},e),o=gr();if(typeof o.GOOGLE_GENAI_API_VERSION<"u")(t=i.api_version)!==null&&t!==void 0||(i.api_version=o.GOOGLE_GENAI_API_VERSION);if(typeof o.GOOGLE_GENAI_USER_PROJECT<"u")(n=i.user_project)!==null&&n!==void 0||(i.user_project=o.GOOGLE_GENAI_USER_PROJECT);return i}class eg{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return Yw(await this.options.getAuthHeaders(e))}}class tg{beforeCreateRequest(e,t){return Object.assign(Object.assign({},t),{url:Jw(t.url)})}async beforeRequest(e,t){if(kh(t.headers,Kw(e.security_source)),Ww(e,t.headers),Qw(t.headers))return t;let n=await Xw(e.security_source,t.url);return kh(t.headers,n===null||n===void 0?void 0:n.default_headers),zw(t.headers,n),t}}function Jw(e){let[,t,...n]=e.pathname.split("/");if(!t)return e;let i=decodeURIComponent(t);if(!i.includes("/"))return e;let o=new URL(e);return o.pathname=`/${i}/${n.join("/")}`,o}async function Xw(e,t){if(rg(e))return e.resolveGoogleGenAISecurity(t);let n=typeof e==="function"?await e():e;if(ng(n))return xh(n);return xh(void 0)}function Kw(e){var t,n;if(rg(e))return(n=(t=e.getDefaultHeaders)===null||t===void 0?void 0:t.call(e))!==null&&n!==void 0?n:e.defaultHeaders;if(ng(e))return e.default_headers;return}function xh(e){var t,n;let i=gr(),o=Object.assign(Object.assign({},e),{api_key:(t=e===null||e===void 0?void 0:e.api_key)!==null&&t!==void 0?t:i.GOOGLE_GENAI_API_KEY,access_token:(n=e===null||e===void 0?void 0:e.access_token)!==null&&n!==void 0?n:i.GOOGLE_GENAI_ACCESS_TOKEN});return ig(o)?o:void 0}function Yw(e){var t,n;let i={};for(let[s,c]of e){let d=s.toLowerCase();if(d!=="authorization"&&d!=="x-goog-api-key")i[s]=c}let o={access_token:(t=e.get("authorization"))!==null&&t!==void 0?t:void 0,api_key:(n=e.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(i).length?i:void 0};return ig(o)?o:void 0}function kh(e,t){if(!t)return;for(let[n,i]of new Headers(t))if(e.get(n)===null)e.set(n,i)}function Ww(e,t){if(e.options.user_project!==void 0&&t.get("x-goog-user-project")===null)t.set("x-goog-user-project",e.options.user_project)}function zw(e,t){if(!t)return;if(t.api_key){e.set("x-goog-api-key",t.api_key);return}if(t.access_token)e.set("Authorization",Zw(t.access_token))}function Qw(e){return e.get("authorization")!==null||e.get("x-goog-api-key")!==null}function Zw(e){return e.slice(0,7).toLowerCase()==="bearer "?e:`Bearer ${e}`}function ng(e){return typeof e==="object"&&e!==null}function rg(e){return typeof e==="object"&&e!==null&&"resolveGoogleGenAISecurity"in e&&typeof e.resolveGoogleGenAISecurity==="function"}function ig(e){return e.api_key!==void 0||e.access_token!==void 0||e.default_headers!==void 0}class vn extends Error{constructor(e,t){let n=e;if(t===null||t===void 0?void 0:t.cause)n+=`: ${t.cause}`;super(n,t);if(this.name="HTTPClientError",typeof this.cause>"u")this.cause=t===null||t===void 0?void 0:t.cause}}class Gs extends vn{constructor(){super(...arguments);this.name="UnexpectedClientError"}}class hr extends vn{constructor(){super(...arguments);this.name="InvalidRequestError"}}class Ws extends vn{constructor(){super(...arguments);this.name="RequestAbortedError"}}class zs extends vn{constructor(){super(...arguments);this.name="RequestTimeoutError"}}class Qs extends vn{constructor(){super(...arguments);this.name="ConnectionError"}}class vt extends Error{constructor(e,t){var n,i,o,s;super(e);this.statusCode=(n=t===null||t===void 0?void 0:t.response)===null||n===void 0?void 0:n.status,this.body=(i=t===null||t===void 0?void 0:t.body)!==null&&i!==void 0?i:"",this.headers=(o=t===null||t===void 0?void 0:t.response)===null||o===void 0?void 0:o.headers,this.contentType=((s=t===null||t===void 0?void 0:t.response)===null||s===void 0?void 0:s.headers.get("content-type"))||"",this.rawResponse=t===null||t===void 0?void 0:t.response,this.name="GoogleGenAiError"}}class og extends Error{}class Je extends og{constructor(e,t,n,i){super(Je.makeMessage(e,t,n));this.status=e,this.headers=i,this.error=t,this.statusCode=e,this.body=Mh(t),this.contentType=(i===null||i===void 0?void 0:i.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,t,n){var i;let o=t&&nR(t)&&typeof t.message==="string"?t.message:void 0,s=Mh(t),c=(i=o!==null&&o!==void 0?o:n)!==null&&i!==void 0?i:s||"An error occurred";return`${e?`${e} `:""}${c}`}static generate(e,t,n,i){if(!e||!i)return new yr({message:n,cause:t instanceof Error?t:void 0});if(e===400)return new lg(e,t,n,i);if(e===401)return new ug(e,t,n,i);if(e===403)return new cg(e,t,n,i);if(e===404)return new dg(e,t,n,i);if(e===409)return new fg(e,t,n,i);if(e===422)return new pg(e,t,n,i);if(e===429)return new hg(e,t,n,i);if(e>=500)return new mg(e,t,n,i);return new Je(e,t,n,i)}}class sg extends Je{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class yr extends Je{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);this.cause=t}}class ag extends yr{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."})}}class lg extends Je{}class ug extends Je{}class cg extends Je{}class dg extends Je{}class fg extends Je{}class pg extends Je{}class hg extends Je{}class mg extends Je{}function $n(e){if(rR(e))return e;if(e instanceof vt)return jw(e);if(e instanceof vn)return eR(e);return e}function jw(e){let t=tR(e),n=Je.generate(e.statusCode,t,e.message,e.headers);return fr(n,"body",e.body),fr(n,"contentType",e.contentType),fr(n,"rawResponse",e.rawResponse),fr(n,"statusCode",e.statusCode),fr(n,"cause",e),n}function eR(e){if(e instanceof zs)return new ag({message:e.message});if(e instanceof Ws)return new sg({message:e.message});if(e instanceof Qs)return new yr({message:e.message,cause:e});return new yr({message:e.message,cause:e})}function tR(e){let t=Dh(e,"data$");if(t&&typeof t==="object")return t;try{let i=JSON.parse(e.body);if(i&&typeof i==="object")return i}catch(i){}let n=Dh(e,"error");return n&&typeof n==="object"?n:void 0}function Dh(e,t){return e&&typeof e==="object"?e[t]:void 0}function Mh(e){if(!e)return"";try{return JSON.stringify(e)}catch(t){return String(e)}}function nR(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function rR(e){return typeof e==="object"&&e!==null?Je.prototype.isPrototypeOf(e):!1}function fr(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!1})}function iR(e){let t=new tg;e.registerBeforeCreateRequestHook(t),e.registerBeforeRequestHook(t)}class bs{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let t of e){if("sdkInit"in t)this.registerSDKInitHook(t);if("beforeCreateRequest"in t)this.registerBeforeCreateRequestHook(t);if("beforeRequest"in t)this.registerBeforeRequestHook(t);if("afterSuccess"in t)this.registerAfterSuccessHook(t);if("afterError"in t)this.registerAfterErrorHook(t)}iR(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((t,n)=>n.sdkInit(t),e)}beforeCreateRequest(e,t){let n=t;for(let i of this.beforeCreateRequestHooks)n=i.beforeCreateRequest(e,n);return n}async beforeRequest(e,t){let n=t;for(let i of this.beforeRequestHooks)n=await i.beforeRequest(e,n);return n}async afterSuccess(e,t){let n=t;for(let i of this.afterSuccessHooks)n=await i.afterSuccess(e,n);return n}async afterError(e,t,n){let i=t,o=n;for(let s of this.afterErrorHooks){let c=await s.afterError(e,i,o);i=c.response,o=c.error}return{response:i,error:o}}}function Uh(e){return{ok:!0,value:e}}function Lt(e){return{ok:!1,error:e}}function Zs(e){return btoa(String.fromCodePoint(...e))}function oR(e){return new TextEncoder().encode(e)}function sR(e){return Zs(oR(e))}var aR=Object.prototype.hasOwnProperty;function ye(e,t){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(o={}){return e.replace(n,function(s,c){if(!aR.call(o,c))throw Error(`Parameter '${c}' is required`);let d=o[c];if(typeof d!=="string"&&typeof d!=="number")throw Error(`Parameter '${c}' must be a string or number`);return`${d}`}).replace(/^\/+/,"")}}var Gh=["https://generativelanguage.googleapis.com"];function lR(e){var t;let n=e.server_url,i={};if(!n){let s=(t=e.server_idx)!==null&&t!==void 0?t:0;if(s<0||s>=Gh.length)throw Error(`Invalid server index ${s}`);n=Gh[s]||""}let o=ye(n)(i);return new URL(o)}var uR={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function cR(...e){let t=[];for(let n of e)if(n)t.push(n);switch(t.length){case 0:case 1:return t[0]||null;default:if("any"in AbortSignal&&typeof AbortSignal.any==="function")return AbortSignal.any(t);return dR(t)}}function dR(e){let t=new AbortController,n=t.signal;if(!e.length)return t.signal;if(e.length===1)return e[0]||t.signal;for(let c of e)if(c.aborted)return c;function i(){t.abort(this.reason),s()}let o=[];function s(){for(let c of o){let d=c.deref();if(d)d.removeEventListener("abort",i)}}for(let c of e)o.push(new WeakRef(c)),c.addEventListener("abort",i);return n}function ve(e){let t={};for(let[n,i]of Object.entries(e))if(typeof i<"u")t[n]=i;return t}function cn(e){if(e===null||typeof e!=="object")return!1;if(Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;try{return Object.getPrototypeOf(t)===null}catch(n){return!1}}function fR(e){return(t,n,i)=>{let o="",s=(i===null||i===void 0?void 0:i.explode)?_g(t,n):[[t,n]];if(s.every(([h,m])=>m==null))return;let c=(h)=>(i===null||i===void 0?void 0:i.charEncoding)==="percent"?encodeURIComponent(h):h,d=(h)=>c(yg(h)),f=c(e);return s.forEach(([h,m])=>{var g,_;let E="",y=null;if(m==null)return;else if(Array.isArray(m))y=(g=vg(m,(v)=>`${d(v)}`))===null||g===void 0?void 0:g.join(f);else if(cn(m))y=(_=Tg(Object.entries(m),([v,C])=>`${c(v)}${f}${d(C)}`))===null||_===void 0?void 0:_.join(f);else y=`${d(m)}`;if(y==null)return;if(E=`${c(h)}=${y}`,!E||E==="=")return;o+=`&${E}`}),o.slice(1)}}var gg=fR(",");function Ft(e,t,n){if(typeof t>"u")return;let i=(s)=>(n===null||n===void 0?void 0:n.charEncoding)==="percent"?encodeURIComponent(s):s,o=i(JSON.stringify(t,Eg));return(n===null||n===void 0?void 0:n.explode)?o:`${i(e)}=${o}`}var re=(e,t,n)=>{let i="",o=(n===null||n===void 0?void 0:n.explode)?_g(e,t):[[e,t]];if(o.every(([d,f])=>f==null))return;let s=(d)=>(n===null||n===void 0?void 0:n.charEncoding)==="percent"?encodeURIComponent(d):d,c=(d)=>s(yg(d));return o.forEach(([d,f])=>{var h;let m="";if(f==null)return;else if(Array.isArray(f))m=(h=vg(f,(g)=>`${c(g)}`))===null||h===void 0?void 0:h.join(",");else if(cn(f)){let g=Tg(Object.entries(f),([_,E])=>`,${s(_)},${c(E)}`);m=g===null||g===void 0?void 0:g.join("").slice(1)}else m=`${(n===null||n===void 0?void 0:n.explode)&&cn(t)?`${d}=`:""}${c(f)}`;i+=m?`,${m}`:""}),i.slice(1)};function _g(e,t){if(Array.isArray(t))return t.map((n)=>[e,n]);else if(cn(t))return Object.entries(t!==null&&t!==void 0?t:{}).map(([i,o])=>[i,o]);else return[[e,t]]}function yg(e){if(e==null)return"";else if(e instanceof Date)return e.toISOString();else if(e instanceof Uint8Array)return Zs(e);else if(typeof e==="object")return JSON.stringify(e,Eg);return`${e}`}function Eg(e,t){if(t instanceof Uint8Array)return Zs(t);else return t}function vg(e,t){let n=e.reduce((i,o)=>{if(o==null)return i;let s=t(o);if(s==null)return i;return i.push(s),i},[]);return n.length?n:null}function Tg(e,t){let n=[];for(let[i,o]of e){if(o==null)continue;let s=t([i,o]);if(s==null)continue;n.push(s)}return n.length?n:null}function pR(...e){return e.filter(Boolean).join("&")}function hR(e){return function(n,i){var o,s,c;let d=Object.assign(Object.assign({},i),{explode:(o=i===null||i===void 0?void 0:i.explode)!==null&&o!==void 0?o:!0,charEncoding:(s=i===null||i===void 0?void 0:i.charEncoding)!==null&&s!==void 0?s:"percent"}),f=new Set((c=i===null||i===void 0?void 0:i.allowEmptyValue)!==null&&c!==void 0?c:[]),h=Object.entries(n).map(([m,g])=>{if(f.has(m)){if(g===void 0||g===null||g===""||Array.isArray(g)&&g.length===0)return`${encodeURIComponent(m)}=`}return e(m,g,d)});return pR(...h)}}var hn=hR(gg),mR=(e,t)=>{if(t==null)return fetch(e);else return fetch(e,t)};class js{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||mR}async request(e){let t=e;for(let n of this.requestHooks){let i=await n(t);if(i)t=i}try{let n=await this.fetcher(t);for(let i of this.responseHooks)await i(n,t);return n}catch(n){for(let i of this.requestErrorHooks)await i(n,t);throw n}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let t;if(e[0]==="beforeRequest")t=this.requestHooks;else if(e[0]==="requestError")t=this.requestErrorHooks;else if(e[0]==="response")t=this.responseHooks;else throw Error(`Invalid hook type: ${e[0]}`);let n=t.findIndex((i)=>i===e[1]);if(n>=0)t.splice(n,1);return this}clone(){let e=new js(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}}var bh=/\s*;\s*/g;function Vn(e,t){var n;if(t==="*")return!0;let i=((n=e.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";i=i.toLowerCase();let o=t.toLowerCase().trim().split(bh),[s="",...c]=o;if(s.split("/").length!==2)return!1;let d=i.split(bh),[f="",...h]=d,[m="",g=""]=f.split("/");if(!m||!g)return!1;if(s!=="*/*"&&f!==s&&`${m}/*`!==s&&`*/${g}`!==s)return!1;if(h.length<c.length)return!1;let _=new Set(h);for(let E of c)if(!_.has(E))return!1;return!0}var gR=new RegExp("^[0-9]xx$","i");function me(e,t){let n=`${e.status}`,i=Array.isArray(t)?t:[t];if(!i.length)return!1;return i.some((o)=>{let s=`${o}`;if(s==="default")return!0;if(!gR.test(`${s}`))return s===n;let c=s.charAt(0);if(!c)throw Error("Invalid status code range");let d=n.charAt(0);if(!d)throw Error(`Invalid response status code: ${n}`);return d===c})}function _R(e,t,n){return me(e,t)&&Vn(e,n)}function Ag(e){if(typeof e!=="object"||e==null)return!1;let t=e instanceof TypeError&&e.message.toLowerCase().startsWith("failed to fetch"),n=e instanceof TypeError&&e.message.toLowerCase().startsWith("fetch failed"),i="name"in e&&e.name==="ConnectionError",o="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnreset";return t||n||o||i}function Cg(e){if(typeof e!=="object"||e==null)return!1;let t="name"in e&&e.name==="TimeoutError",n="code"in e&&e.code===23,i="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnaborted";return t||n||i}function yR(e){if(typeof e!=="object"||e==null)return!1;let t="name"in e&&e.name==="AbortError",n="code"in e&&e.code===20,i="code"in e&&typeof e.code==="string"&&e.code.toLowerCase()==="econnaborted";return t||n||i}var Lh={initialInterval:500,maxInterval:60000,exponent:1.5,maxElapsedTime:3600000};class Ir extends Error{constructor(e,t){let n=e;if(t===null||t===void 0?void 0:t.cause)n+=`: ${t.cause}`;super(n,t);if(this.name="PermanentError",typeof this.cause>"u")this.cause=t===null||t===void 0?void 0:t.cause;Object.setPrototypeOf(this,Ir.prototype)}}class dn extends Error{constructor(e,t){super(e);this.response=t,this.name="TemporaryError",Object.setPrototypeOf(this,dn.prototype)}}async function ER(e,t){var n;switch(t.config.strategy){case"backoff":return AR(qh(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),(n=t.config.backoff)!==null&&n!==void 0?n:Lh);case"attempt-count-backoff":return CR(qh(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),Object.assign(Object.assign({},Lh),t.config.backoff),t.config);default:return await e(0)}}function qh(e,t){return async(n)=>{try{let i=await e(n);if(TR(i,t.statusCodes))throw new dn("Response failed with retryable status code",i);return i}catch(i){if(i instanceof dn)throw i;if(t.retryConnectionErrors&&(Cg(i)||Ag(i)))throw i;throw new Ir("Permanent error",{cause:i})}}}var vR=new RegExp("^[0-9]xx$","i");function TR(e,t){let n=`${e.status}`;return t.some((i)=>{if(!vR.test(i))return i===n;let o=i.charAt(0);if(!o)throw Error("Invalid status code range");let s=n.charAt(0);if(!s)throw Error(`Invalid response status code: ${n}`);return s===o})}async function AR(e,t){let{maxElapsedTime:n,initialInterval:i,exponent:o,maxInterval:s}=t,c=Date.now(),d=0;while(!0)try{return await e(d)}catch(f){if(f instanceof Ir)throw f.cause;if(Date.now()-c>n){if(f instanceof dn)return f.response;throw f}let m=0;if(f instanceof dn)m=Sg(f.response);if(m<=0)m=i*Math.pow(d,o)+Math.random()*1000;let g=Math.min(m,s);await Ig(g),d++}}async function CR(e,t,n){let i=0;while(!0)try{return await e(i)}catch(o){if(o instanceof Ir)throw o.cause;if(i>=n.maxRetries){if(o instanceof dn)return o.response;throw o}let s=0;if(o instanceof dn)s=Sg(o.response);if(s<=0)s=t.initialInterval*Math.pow(t.exponent,i)*(1-Math.random()*0.25);let c=Math.min(s,t.maxInterval);await Ig(c),i++}}function Sg(e){let t=e.headers.get("retry-after-ms");if(t){let s=Number(t);if(Number.isFinite(s)&&s>=0)return s}let n=e.headers.get("retry-after")||"";if(!n)return 0;let i=Number(n);if(Number.isInteger(i))return i*1000;let o=Date.parse(n);if(Number.isInteger(o)){let s=o-Date.now();return s>0?Math.ceil(s):0}return 0}async function Ig(e){return new Promise((t)=>setTimeout(t,e))}var Ni=typeof globalThis>"u"?null:globalThis,SR=typeof Ni==="object"&&Ni!=null&&"importScripts"in Ni&&typeof Ni.importScripts==="function",IR=SR||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window==="object"&&typeof window.document<"u";class mn{constructor(e={}){let t=e;if(typeof t==="object"&&t!=null&&"hooks"in t&&t.hooks instanceof bs)this._hooks=t.hooks;else this._hooks=new bs;let n=new js;e.http_client=e.http_client||n,e=this._hooks.sdkInit(e);let i=lR(e);if(i)i.pathname=i.pathname.replace(/\/+$/,"")+"/";if(this._baseURL=i,this._httpClient=e.http_client||n,this._options=Object.assign(Object.assign({},$w(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&gr().GOOGLE_GENAI_DEBUG)this._logger=console}_createRequest(e,t,n){var i,o,s,c,d;let{method:f,path:h,query:m,headers:g,security:_}=t,E=(i=t.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!E)return Lt(new hr("No base URL provided for operation"));let y=new URL(E),v;if(h){if(y.pathname=y.pathname.replace(/\/+$/,"")+"/",v=new URL(h,y),!v.search&&y.search)v.search=y.search}else v=y;v.hash="";let C=(W,H)=>{if(!H)return W;let oe=new Set(H.split("&").filter((Ne)=>Ne!=="").map((Ne)=>{var Me;return(Me=Ne.split("=")[0])!==null&&Me!==void 0?Me:""}));return[...W.split("&").filter((Ne)=>{var Me;return Ne!==""&&!oe.has((Me=Ne.split("=")[0])!==null&&Me!==void 0?Me:"")}),H].join("&")},T=(W)=>Object.entries(W).map(([H,oe])=>{if(oe==null)return;let se=cn(oe)?JSON.stringify(oe):oe;return gg(H,se,{explode:Array.isArray(se),charEncoding:"percent"})}).filter((H)=>typeof H<"u").join("&"),I=[m||"",T((n===null||n===void 0?void 0:n.extra_query)||{}),T((_===null||_===void 0?void 0:_.queryParams)||{})].reduce(C,v.search.slice(1));if(I)v.search=`?${I}`;let P=new Headers(g),N=_===null||_===void 0?void 0:_.basic.username,D=_===null||_===void 0?void 0:_.basic.password;if(N!=null||D!=null){let W=sR([N||"",D||""].join(":"));P.set("Authorization",`Basic ${W}`)}let q=new Headers((_===null||_===void 0?void 0:_.headers)||{});for(let[W,H]of q)P.set(W,H);let V=P.get("cookie")||"";for(let[W,H]of Object.entries((_===null||_===void 0?void 0:_.cookies)||{}))V+=`; ${W}=${H}`;V=V.startsWith("; ")?V.slice(2):V,P.set("cookie",V);let J=new Headers((o=n===null||n===void 0?void 0:n.headers)!==null&&o!==void 0?o:(s=n===null||n===void 0?void 0:n.fetch_options)===null||s===void 0?void 0:s.headers);for(let[W,H]of J)P.set(W,H);if(!IR)P.set((c=t.uaHeader)!==null&&c!==void 0?c:"user-agent",(d=t.userAgent)!==null&&d!==void 0?d:uR.userAgent);let L=t.body,Y=Object.fromEntries(Object.entries((n===null||n===void 0?void 0:n.extra_body)||{}).filter(([,W])=>typeof W<"u"));if(Object.keys(Y).length>0){let W=new Headers(g).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(W)||typeof L!=="string"&&L!=null)return Lt(new hr("extra_body can only be merged into JSON object request bodies"));let oe;try{oe=L?JSON.parse(L):{}}catch(se){return Lt(new hr("extra_body can only be merged into JSON object request bodies",{cause:se}))}if(!cn(oe))return Lt(new hr("extra_body can only be merged into JSON object request bodies"));L=JSON.stringify(Object.assign(Object.assign({},oe),Y)),P.delete("content-length")}let Z=Object.assign(Object.assign({},n===null||n===void 0?void 0:n.fetch_options),n);if(!(Z===null||Z===void 0?void 0:Z.signal)&&t.timeout_ms!=null&&t.timeout_ms>0)e.timeout_ms=t.timeout_ms;if(t.body instanceof ReadableStream)Object.assign(Z,{duplex:"half"});let ne;try{ne=this._hooks.beforeCreateRequest(e,{url:v,options:Object.assign(Object.assign({},Z),{body:L!==null&&L!==void 0?L:null,headers:P,method:f})})}catch(W){return Lt(new Gs("Create request hook failed to execute",{cause:W}))}return Uh(new Request(ne.url,ne.options))}async _do(e,t){let{context:n,isErrorStatusCode:i}=t,o=n.timeout_ms;return ER(async()=>{var s;let c=e.clone(),d=c;if(o!=null&&o>0){let m=AbortSignal.timeout(o),g=(s=cR(c.signal,m))!==null&&s!==void 0?s:m;d=new Request(c,{signal:g})}let f=await this._hooks.beforeRequest(n,d);await wR(this._logger,f).catch((m)=>{var g;return(g=this._logger)===null||g===void 0?void 0:g.log("Failed to log request:",m)});let h=await this._httpClient.request(f);try{if(i(h.status)){let m=await this._hooks.afterError(n,h,null);if(m.error)throw m.error;h=m.response||h}else h=await this._hooks.afterSuccess(n,h)}finally{await RR(this._logger,h,f).catch((m)=>{var g;return(g=this._logger)===null||g===void 0?void 0:g.log("Failed to log response:",m)})}return h},{config:t.retryConfig,statusCodes:t.retryCodes}).then((s)=>Uh(s),(s)=>{switch(!0){case yR(s):return Lt(new Ws("Request aborted by client",{cause:s}));case Cg(s):return Lt(new zs("Request timed out",{cause:s}));case Ag(s):return Lt(new Qs("Unable to make request",{cause:s}));default:return Lt(new Gs("Unexpected HTTP client error",{cause:s}))}})}}var wg=/^(application|text)\/([^+]+\+)*json.*/,Oh=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function wR(e,t){if(!e)return;let n=t.headers.get("content-type"),i=(n===null||n===void 0?void 0:n.split(";")[0])||"";e.group(`> Request: ${t.method} ${t.url}`),e.group("Headers:");for(let[o,s]of t.headers.entries())e.log(`${o}: ${s}`);switch(e.groupEnd(),e.group("Body:"),!0){case wg.test(i):e.log(await t.clone().json());break;case i.startsWith("text/"):e.log(await t.clone().text());break;case i==="multipart/form-data":{let o=await t.clone().formData();for(let[s,c]of o){let d=c instanceof Blob?"<Blob>":c;e.log(`${s}: ${d}`)}break}default:e.log(`<${n}>`);break}e.groupEnd(),e.groupEnd()}async function RR(e,t,n){if(!e)return;let i=t.headers.get("content-type"),o=(i===null||i===void 0?void 0:i.split(";")[0])||"";e.group(`< Response: ${n.method} ${n.url}`),e.log("Status Code:",t.status,t.statusText),e.group("Headers:");for(let[s,c]of t.headers.entries())e.log(`${s}: ${c}`);switch(e.groupEnd(),e.group("Body:"),!0){case(Vn(t,"application/json")||wg.test(o)&&!Oh.test(o)):e.log(await t.clone().json());break;case(Vn(t,"application/jsonl")||Oh.test(o)):case Vn(t,"text/event-stream"):e.log(`<${i}>`);break;case Vn(t,"text/*"):e.log(await t.clone().text());break;case Vn(t,"multipart/form-data"):{let s=await t.clone().formData();for(let[c,d]of s){let f=d instanceof Blob?"<Blob>":d;e.log(`${c}: ${f}`)}break}default:e.log(`<${i}>`);break}e.groupEnd(),e.groupEnd()}class Ls extends vt{constructor(e,t){if(e)e+=": ";e+=`Status ${t.response.status}`;let n=t.response.headers.get("content-type")||'""';if(n!=="application/json")e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`;let i=t.body||'""';e+=i.length>100?`
|
|
36
|
+
`:". ";let o=i;if(i.length>1e4){let s=i.substring(0,1e4),c=i.length-1e4;o=`${s}...and ${c} more chars`}e+=`Body: ${o}`,e=e.trim();super(e,t);this.name="GoogleGenAiDefaultError"}}function Fh(e){try{return JSON.parse(e)}catch(t){return e}}function PR(e,t={}){var n,i;let o=t.flattened===!0,s=(n=t.sentinel)!==null&&n!==void 0?n:"";return new Rg(e,(c)=>{if(s!==""&&c.data===s)return{done:!0,value:void 0};if(o)return{done:!1,value:c.data==null?void 0:Fh(c.data)};return{done:!1,value:Object.assign(Object.assign({},c),{data:c.data==null?c.data:Fh(c.data)})}},{dataRequired:(i=t.dataRequired)!==null&&i!==void 0?i:!0})}class Rg extends ReadableStream{constructor(e,t,n){var i;let o=e.getReader(),s=new Uint8Array(4096),c=0,d=0,f={eventId:void 0},h=(i=n===null||n===void 0?void 0:n.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(m){try{while(!0){let g=xR(s,c,d);if(!g){d=Math.max(0,c-NR+1);let y=await o.read();if(y.done)return m.close();if(c+y.value.length>s.length){let v=new Uint8Array(Math.max(s.length*2,c+y.value.length));v.set(s.subarray(0,c)),s=v}s.set(y.value,c),c+=y.value.length;continue}let _=s.slice(0,g.index);if(s.copyWithin(0,g.index+g.length,c),c-=g.index+g.length,s.length>4096&&c<=s.length>>2){let y=new Uint8Array(Math.max(4096,c*2));y.set(s.subarray(0,c)),s=y}d=0;let E=kR(_,t,f,h);if(E&&!E.done)return m.enqueue(E.value);if(E===null||E===void 0?void 0:E.done)return await o.cancel("done"),m.close()}}catch(g){m.error(g),await o.cancel(g)}},cancel:(m)=>o.cancel(m)})}[Symbol.asyncIterator](e){let t=ReadableStream.prototype[Symbol.asyncIterator];if(typeof t==="function")return t.call(this,e);let n=this.getReader(),i={next:async()=>{let s=await n.read();if(s.done)return n.releaseLock(),{done:!0,value:void 0};return{done:!1,value:s.value}},throw:async(s)=>(await n.cancel(s),n.releaseLock(),{done:!0,value:void 0}),return:async()=>(await n.cancel("done"),n.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},o=Symbol.asyncDispose;if(o)i[o]=async()=>{var s;await((s=i.return)===null||s===void 0?void 0:s.call(i))};return i}values(e){return this[Symbol.asyncIterator](e)}}var ft=13,pt=10,Pg=[[ft,pt,ft,pt],[ft,pt,ft],[ft,pt,pt],[ft,ft,pt],[pt,ft,pt],[ft,ft],[pt,ft],[pt,pt]],NR=Pg.reduce((e,t)=>Math.max(e,t.length),0);function xR(e,t,n){for(let i=n;i<t;i++){if(e[i]!==ft&&e[i]!==pt)continue;for(let o of Pg){if(i+o.length>t)continue;let s=!0;for(let c=0;c<o.length;c++)if(e[i+c]!==o[c]){s=!1;break}if(s)return{index:i,length:o.length}}}return null}function kR(e,t,n,i){let s=new TextDecoder().decode(e).split(/\r\n|\r|\n/),c=[],d={},f=!0;for(let h of s){if(!h||h.startsWith(":"))continue;f=!1;let m=h.indexOf(":"),g=h,_="";if(m>0)g=h.slice(0,m),_=h[m+1]===" "?h.slice(m+2):h.slice(m+1);if(g==="data")c.push(_);else if(g==="event")d.event=_;else if(g==="id"&&!_.includes("\x00"))n.eventId=_;else if(g==="retry"&&/^\d+$/.test(_))d.retry=Number(_)}if(f)return;if(d.id=n.eventId,c.length)d.data=c.join(`
|
|
37
|
+
`);else if(i)return;return t(d)}var DR={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function fn(e,t,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:e,errorClass:t})}function Re(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function Ng(e,t,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:e}),t?{sse:t}:{})}function MR(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function ie(e){return{enc:"fail",codes:e}}function Te(...e){return async function(n,i,o){let s,c;for(let _ of e){let{codes:E}=_,y="ctype"in _?_.ctype:DR[_.enc];if(y&&_R(n,E,y)){c=_;break}else if(!y&&me(n,E)){c=_;break}}if(!c)return[{ok:!1,error:new Ls("Unexpected Status or Content-Type",{response:n,request:i,body:await n.text().catch(()=>"")})},s];let d=c.enc,f="";switch(d){case"json":f=await n.text();try{s=JSON.parse(f)}catch(_){if(!("err"in c))throw _;s=f}break;case"jsonl":s=n.body;break;case"bytes":s=new Uint8Array(await n.arrayBuffer());break;case"stream":s=n.body;break;case"text":f=await n.text(),s=f;break;case"sse":if(n.body){let _="sse"in c&&c.sse||{};s=PR(n.body,_)}else s=null;break;case"nil":f=await n.text(),s=void 0;break;case"fail":f=await n.text(),s=f;break;default:throw Error(`Unsupported response type: ${d}`)}if(c.enc==="fail")return[{ok:!1,error:new Ls("API error occurred",{request:i,response:n,body:f})},s];let h=c.key||(o===null||o===void 0?void 0:o.resultKey),m,g=c.hdrs?{headers:GR(n.headers)}:null;if("err"in c)m=Object.assign(Object.assign(Object.assign({},o===null||o===void 0?void 0:o.extraFields),g),cn(s)?s:null);else if(h)m=Object.assign(Object.assign(Object.assign({},o===null||o===void 0?void 0:o.extraFields),g),{[h]:s});else if(c.hdrs)m=Object.assign(Object.assign(Object.assign({},o===null||o===void 0?void 0:o.extraFields),g),cn(s)?s:null);else m=s;if("err"in c)return[{ok:!1,error:c.errorClass?new c.errorClass(m,{request:i,response:n,body:f}):m},s];return[{ok:!0,value:m},s]}}var UR=/, */;function GR(e){let t={};for(let[n,i]of e.entries())t[n]=i.split(UR);return t}var Hh={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"};class qi extends Error{constructor(e,t){super(t);this.code=e,this.name="SecurityError"}static incomplete(){return new qi(Hh.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new qi(Hh.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}}function bR(...e){let t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=e.find((i)=>i.every((o)=>{if(o.value==null)return!1;else if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;else if(o.type==="http:custom")return null;else if(o.type==="oauth2:password")return typeof o.value==="string"&&!!o.value;else if(o.type==="oauth2:client_credentials"){if(typeof o.value=="string")return!!o.value;return o.value.client_id!=null||o.value.client_secret!=null}else if(typeof o.value==="string")return!!o.value;else throw Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));if(n==null)return null;return n.forEach((i)=>{if(i.value==null)return;let{type:o}=i;switch(o){case"apiKey:header":t.headers[i.fieldName]=i.value;break;case"apiKey:query":t.queryParams[i.fieldName]=i.value;break;case"apiKey:cookie":t.cookies[i.fieldName]=i.value;break;case"http:basic":LR(t,i);break;case"http:custom":break;case"http:bearer":xi(t,i);break;case"oauth2":xi(t,i);break;case"oauth2:password":xi(t,i);break;case"oauth2:client_credentials":break;case"openIdConnect":xi(t,i);break;default:throw qi.unrecognizedType(o)}}),t}function LR(e,t){if(t.value==null)return;e.basic=t.value}function xi(e,t){if(typeof t.value!=="string"||!t.value)return;let n=t.value;if(n.slice(0,7).toLowerCase()!=="bearer ")n=`Bearer ${n}`;if(t.fieldName!==void 0)e.headers[t.fieldName]=n}function Ae(e,t){var n,i;let o=[[{fieldName:"accessToken",type:"http:custom",value:(n=e===null||e===void 0?void 0:e.access_token)!==null&&n!==void 0?n:gr().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(i=e===null||e===void 0?void 0:e.api_key)!==null&&i!==void 0?i:gr().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:e===null||e===void 0?void 0:e.default_headers}]];return bR(...o)}async function Ce(e){if(e==null)return;return typeof e==="function"?e():e}var xg;class pe{constructor(e,t){this[xg]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=t!==null&&t!==void 0?t:null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([t])=>t)}then(e,t){return this._promise.then(e?([n])=>e(n):void 0,t)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,n])=>n)).then((n)=>{if(!n.response)throw Error("APIPromise.asResponse: response unavailable");return n.response})}async withResponse(){let[[e],t]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:t}}_thenUnwrap(e){var t;let n=this._promise.then(([i,o])=>[e(i),o]);return n.catch(()=>{}),new pe(n,(t=this._callSource)!==null&&t!==void 0?t:void 0)}}xg=Symbol.toStringTag;function Ee(e){let t=e.$inspect(),n=t.then(([o,s])=>{if(!o.ok)throw o.error;return[o.value,s]}),i=t.then(([o,s])=>{var c;if(!o.ok&&!((c=s.response)===null||c===void 0?void 0:c.ok))throw o.error;return s});return n.catch(()=>{}),i.catch(()=>{}),new pe(n,i)}function kg(e,t,n,i){return new pe(qR(e,t,n,i))}async function qR(e,t,n,i){var o,s,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/agents")(m),_=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function Dg(e,t,n,i){return new pe(OR(e,t,n,i))}async function OR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/agents/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"DELETE",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function Mg(e,t,n,i){return new pe(FR(e,t,n,i))}async function FR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/agents/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"GET",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function Ug(e,t,n,i,o,s){return new pe(HR(e,t,n,i,o,s))}async function HR(e,t,n,i,o,s){var c,d,f;let m={api_version:t,page_size:n,page_token:i,parent:o},g=null,_={api_version:re("api_version",(c=m===null||m===void 0?void 0:m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"})},E=ye("/{api_version}/agents")(_),y=hn({page_size:m===null||m===void 0?void 0:m.page_size,page_token:m===null||m===void 0?void 0:m.page_token,parent:m===null||m===void 0?void 0:m.parent}),v=new Headers(ve({Accept:"application/json"})),C=await Ce(e._options.security),T=Ae(C),I={options:e._options,base_url:(f=(d=s===null||s===void 0?void 0:s.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(I,{security:T,method:"GET",baseURL:s===null||s===void 0?void 0:s.server_url,path:E,headers:v,query:y,body:null,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:I,isErrorStatusCode:(J)=>me({status:J},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let q=D.value,[V]=await Te(ie("4XX"),ie("5XX"),Re("default"))(q,N);if(!V.ok)return[V,{status:"complete",request:N,response:q}];return[V,{status:"complete",request:N,response:q}]}class Gg extends mn{list(e,t){return Ee(Ug(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,e===null||e===void 0?void 0:e.parent,t))}create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return Ee(kg(this,i,n,t))}delete(e,t,n){return Ee(Dg(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Ee(Mg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function bg(e,t,n,i){return new pe(VR(e,t,n,i))}async function VR(e,t,n,i){var o,s,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/environments")(m),_=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function Lg(e,t,n,i){return new pe(BR(e,t,n,i))}async function BR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/environments/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"DELETE",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function qg(e,t,n,i){return new pe($R(e,t,n,i))}async function $R(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/environments/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"GET",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function Og(e,t,n,i,o){return new pe(JR(e,t,n,i,o))}async function JR(e,t,n,i,o){var s,c,d;let h={api_version:t,page_size:n,page_token:i},m=null,g={api_version:re("api_version",(s=h===null||h===void 0?void 0:h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/environments")(g),E=hn({page_size:h===null||h===void 0?void 0:h.page_size,page_token:h===null||h===void 0?void 0:h.page_token}),y=new Headers(ve({Accept:"application/json"})),v=await Ce(e._options.security),C=Ae(v),T={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:C,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},I=e._createRequest(T,{security:C,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:y,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!I.ok)return[I,{status:"invalid"}];let P=I.value,N=await e._do(P,{context:T,isErrorStatusCode:(V)=>me({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!N.ok)return[N,{status:"request-error",request:P}];let D=N.value,[q]=await Te(ie("4XX"),ie("5XX"),Re("default"))(D,P);if(!q.ok)return[q,{status:"complete",request:P,response:D}];return[q,{status:"complete",request:P,response:D}]}function Fg(e,t,n,i,o,s,c,d){return new pe(XR(e,t,n,i,o,s,c,d))}async function XR(e,t,n,i,o,s,c,d){var f,h,m;let _={environment:t,path:n,api_version:i,page_size:o,page_token:s,recursive:c},E=null,y={api_version:re("api_version",(f=_.api_version)!==null&&f!==void 0?f:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:re("environment",_.environment,{explode:!1,charEncoding:"percent"}),path:re("path",_.path,{explode:!1,charEncoding:"percent"})},v=ye("/{api_version}/environments/{environment}/files/{path}")(y),C=hn({page_size:_.page_size,page_token:_.page_token,recursive:_.recursive}),T=new Headers(ve({Accept:"application/json"})),I=await Ce(e._options.security),P=Ae(I),N={options:e._options,base_url:(m=(h=d===null||d===void 0?void 0:d.server_url)!==null&&h!==void 0?h:e._baseURL)!==null&&m!==void 0?m:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:P,security_source:e._options.security,retry_config:(d===null||d===void 0?void 0:d.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(d===null||d===void 0?void 0:d.retry_codes)||["408","409","429","5XX"]},D=e._createRequest(N,{security:P,method:"GET",baseURL:d===null||d===void 0?void 0:d.server_url,path:v,headers:T,query:C,body:null,userAgent:e._options.user_agent,timeout_ms:(d===null||d===void 0?void 0:d.timeout_ms)||e._options.timeout_ms||-1},d);if(!D.ok)return[D,{status:"invalid"}];let q=D.value,V=await e._do(q,{context:N,isErrorStatusCode:(Y)=>me({status:Y},["4XX","5XX"]),retryConfig:N.retry_config,retryCodes:N.retry_codes});if(!V.ok)return[V,{status:"request-error",request:q}];let J=V.value,[L]=await Te(Re(200),ie("4XX"),ie("5XX"))(J,q);if(!L.ok)return[L,{status:"complete",request:q,response:J}];return[L,{status:"complete",request:q,response:J}]}class Hg extends mn{list(e,t,n,i){return Ee(Fg(this,e,t,n===null||n===void 0?void 0:n.api_version,n===null||n===void 0?void 0:n.page_size,n===null||n===void 0?void 0:n.page_token,n===null||n===void 0?void 0:n.recursive,i))}}class Vg extends mn{get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new Hg(this._options)}listEnvironments(e,t){return Ee(Og(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}createEnvironment(e,t,n){return Ee(bg(this,e,t,n))}deleteEnvironment(e,t,n){return Ee(Lg(this,e,t===null||t===void 0?void 0:t.api_version,n))}getEnvironment(e,t,n){return Ee(qg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}class Bg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}}class $g extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}}class Jg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}}class Xg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}}class Kg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}}class Yg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}}class Wg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}}class zg extends vt{constructor(e,t){var n;let i=((n=e.error)===null||n===void 0?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,t);this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}}function Qg(e,t,n,i){return new pe(KR(e,t,n,i))}async function KR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/interactions/{id}/cancel")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(q)=>me({status:q},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,N={httpMeta:{response:P,request:T}},[D]=await Te(Re(200),fn("4XX",$g),fn("5XX",Bg))(P,T,{extraFields:N});if(!D.ok)return[D,{status:"complete",request:T,response:P}];return[D,{status:"complete",request:T,response:P}]}function Zg(e,t,n,i){return new pe(YR(e,t,n,i))}async function YR(e,t,n,i){var o,s,c,d;let f={body:t,api_version:n},h=f,m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(o=h.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/interactions")(g),E=new Headers(ve({"Content-Type":"application/json",Accept:((s=f===null||f===void 0?void 0:f.body)===null||s===void 0?void 0:s.stream)?"text/event-stream":"application/json"})),y=await Ce(e._options.security),v=Ae(y),C={options:e._options,base_url:(d=(c=i===null||i===void 0?void 0:i.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(C,{security:v,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:_,headers:E,body:m,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let I=T.value,P=await e._do(I,{context:C,isErrorStatusCode:(V)=>me({status:V},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let N=P.value,D={httpMeta:{response:N,request:I}},[q]=await Te(Re(200),Ng(200,{sentinel:"[DONE]",flattened:!0}),fn("4XX",Xg),fn("5XX",Jg))(N,I,{extraFields:D});if(!q.ok)return[q,{status:"complete",request:I,response:N}];return[q,{status:"complete",request:I,response:N}]}function WR(e,t,n,i){return new pe(zR(e,t,n,i))}async function zR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/interactions/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"DELETE",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(q)=>me({status:q},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,N={httpMeta:{response:P,request:T}},[D]=await Te(MR(200),fn("4XX",Yg),fn("5XX",Kg))(P,T,{extraFields:N});if(!D.ok)return[D,{status:"complete",request:T,response:P}];return[D,{status:"complete",request:T,response:P}]}function jg(e,t,n,i,o,s,c){return new pe(QR(e,t,n,i,o,s,c))}async function QR(e,t,n,i,o,s,c){var d,f,h;let m={id:t,api_version:n,include_input:i,last_event_id:o,stream:s},g=m,_=null,E={api_version:re("api_version",(d=g.api_version)!==null&&d!==void 0?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",g.id,{explode:!1,charEncoding:"percent"})},y=ye("/{api_version}/interactions/{id}")(E),v=hn({include_input:g.include_input,last_event_id:g.last_event_id,stream:g.stream}),C=new Headers(ve({Accept:(m===null||m===void 0?void 0:m.stream)?"text/event-stream":"application/json"})),T=await Ce(e._options.security),I=Ae(T),P={options:e._options,base_url:(h=(f=c===null||c===void 0?void 0:c.server_url)!==null&&f!==void 0?f:e._baseURL)!==null&&h!==void 0?h:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:I,security_source:e._options.security,retry_config:(c===null||c===void 0?void 0:c.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(c===null||c===void 0?void 0:c.retry_codes)||["408","409","429","5XX"]},N=e._createRequest(P,{security:I,method:"GET",baseURL:c===null||c===void 0?void 0:c.server_url,path:y,headers:C,query:v,body:null,userAgent:e._options.user_agent,timeout_ms:(c===null||c===void 0?void 0:c.timeout_ms)||e._options.timeout_ms||-1},c);if(!N.ok)return[N,{status:"invalid"}];let D=N.value,q=await e._do(D,{context:P,isErrorStatusCode:(Y)=>me({status:Y},["4XX","5XX"]),retryConfig:P.retry_config,retryCodes:P.retry_codes});if(!q.ok)return[q,{status:"request-error",request:D}];let V=q.value,J={httpMeta:{response:V,request:D}},[L]=await Te(Re(200),Ng(200,{sentinel:"[DONE]",flattened:!0}),fn("4XX",zg),fn("5XX",Wg))(V,D,{extraFields:J});if(!L.ok)return[L,{status:"complete",request:D,response:V}];return[L,{status:"complete",request:D,response:V}]}class e_ extends mn{create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return Ee(Zg(this,i,n,t))}delete(e,t,n){return Ee(WR(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Ee(jg(this,e,t===null||t===void 0?void 0:t.api_version,t===null||t===void 0?void 0:t.include_input,t===null||t===void 0?void 0:t.last_event_id,t===null||t===void 0?void 0:t.stream,n))}cancel(e,t,n){return Ee(Qg(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function t_(e,t,n,i){return new pe(ZR(e,t,n,i))}async function ZR(e,t,n,i){var o,s,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/triggers")(m),_=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(Re(200),ie("4XX"),ie("5XX"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function n_(e,t,n,i){return new pe(jR(e,t,n,i))}async function jR(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/triggers/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"DELETE",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(Re(200),ie("4XX"),ie("5XX"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function r_(e,t,n,i){return new pe(eP(e,t,n,i))}async function eP(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/triggers/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"GET",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(Re(200),ie("4XX"),ie("5XX"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function i_(e,t,n,i,o,s){return new pe(tP(e,t,n,i,o,s))}async function tP(e,t,n,i,o,s){var c,d,f;let m={trigger_id:t,api_version:n,page_size:i,page_token:o},g=null,_={api_version:re("api_version",(c=m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:re("trigger_id",m.trigger_id,{explode:!1,charEncoding:"percent"})},E=ye("/{api_version}/triggers/{trigger_id}/executions")(_),y=hn({page_size:m.page_size,page_token:m.page_token}),v=new Headers(ve({Accept:"application/json"})),C=await Ce(e._options.security),T=Ae(C),I={options:e._options,base_url:(f=(d=s===null||s===void 0?void 0:s.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(I,{security:T,method:"GET",baseURL:s===null||s===void 0?void 0:s.server_url,path:E,headers:v,query:y,body:null,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:I,isErrorStatusCode:(J)=>me({status:J},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let q=D.value,[V]=await Te(Re(200),ie("4XX"),ie("5XX"))(q,N);if(!V.ok)return[V,{status:"complete",request:N,response:q}];return[V,{status:"complete",request:N,response:q}]}function o_(e,t,n,i,o,s){return new pe(nP(e,t,n,i,o,s))}async function nP(e,t,n,i,o,s){var c,d,f;let m={api_version:t,filter:n,page_size:i,page_token:o},g=null,_={api_version:re("api_version",(c=m===null||m===void 0?void 0:m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"})},E=ye("/{api_version}/triggers")(_),y=hn({filter:m===null||m===void 0?void 0:m.filter,page_size:m===null||m===void 0?void 0:m.page_size,page_token:m===null||m===void 0?void 0:m.page_token}),v=new Headers(ve({Accept:"application/json"})),C=await Ce(e._options.security),T=Ae(C),I={options:e._options,base_url:(f=(d=s===null||s===void 0?void 0:s.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(I,{security:T,method:"GET",baseURL:s===null||s===void 0?void 0:s.server_url,path:E,headers:v,query:y,body:null,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:I,isErrorStatusCode:(J)=>me({status:J},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let q=D.value,[V]=await Te(Re(200),ie("4XX"),ie("5XX"))(q,N);if(!V.ok)return[V,{status:"complete",request:N,response:q}];return[V,{status:"complete",request:N,response:q}]}function s_(e,t,n,i){return new pe(rP(e,t,n,i))}async function rP(e,t,n,i){var o,s,c;let f={trigger_id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:re("trigger_id",f.trigger_id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/triggers/{trigger_id}/executions")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(Re(200),ie("4XX"),ie("5XX"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function a_(e,t,n,i,o){return new pe(iP(e,t,n,i,o))}async function iP(e,t,n,i,o){var s,c,d;let h={id:t,body:n,api_version:i},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(s=h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/triggers/{id}")(g),E=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),y=await Ce(e._options.security),v=Ae(y),C={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(C,{security:v,method:"PATCH",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:E,body:m,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!T.ok)return[T,{status:"invalid"}];let I=T.value,P=await e._do(I,{context:C,isErrorStatusCode:(q)=>me({status:q},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let N=P.value,[D]=await Te(Re(200),ie("4XX"),ie("5XX"))(N,I);if(!D.ok)return[D,{status:"complete",request:I,response:N}];return[D,{status:"complete",request:I,response:N}]}class l_ extends mn{list(e,t){return Ee(o_(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.filter,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return Ee(t_(this,i,n,t))}delete(e,t,n){return Ee(n_(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Ee(r_(this,e,t===null||t===void 0?void 0:t.api_version,n))}update(e,t,n){let{api_version:i}=t,o=Ve(t,["api_version"]);return Ee(a_(this,e,o,i,n))}listExecutions(e,t,n){return Ee(i_(this,e,t===null||t===void 0?void 0:t.api_version,t===null||t===void 0?void 0:t.page_size,t===null||t===void 0?void 0:t.page_token,n))}run(e,t,n){return Ee(s_(this,e,t===null||t===void 0?void 0:t.api_version,n))}}function u_(e,t,n,i){return new pe(oP(e,t,n,i))}async function oP(e,t,n,i){var o,s,c;let f={body:t,api_version:n},h=Ft("body",f.body,{explode:!0}),m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/webhooks")(m),_=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"POST",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:h,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function c_(e,t,n,i){return new pe(sP(e,t,n,i))}async function sP(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/webhooks/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"DELETE",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function d_(e,t,n,i){return new pe(aP(e,t,n,i))}async function aP(e,t,n,i){var o,s,c;let f={id:t,api_version:n},h=null,m={api_version:re("api_version",(o=f.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",f.id,{explode:!1,charEncoding:"percent"})},g=ye("/{api_version}/webhooks/{id}")(m),_=new Headers(ve({Accept:"application/json"})),E=await Ce(e._options.security),y=Ae(E),v={options:e._options,base_url:(c=(s=i===null||i===void 0?void 0:i.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(i===null||i===void 0?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(i===null||i===void 0?void 0:i.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(v,{security:y,method:"GET",baseURL:i===null||i===void 0?void 0:i.server_url,path:g,headers:_,body:null,userAgent:e._options.user_agent,timeout_ms:(i===null||i===void 0?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let T=C.value,I=await e._do(T,{context:v,isErrorStatusCode:(D)=>me({status:D},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!I.ok)return[I,{status:"request-error",request:T}];let P=I.value,[N]=await Te(ie("4XX"),ie("5XX"),Re("default"))(P,T);if(!N.ok)return[N,{status:"complete",request:T,response:P}];return[N,{status:"complete",request:T,response:P}]}function f_(e,t,n,i,o){return new pe(lP(e,t,n,i,o))}async function lP(e,t,n,i,o){var s,c,d;let h={api_version:t,page_size:n,page_token:i},m=null,g={api_version:re("api_version",(s=h===null||h===void 0?void 0:h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/webhooks")(g),E=hn({page_size:h===null||h===void 0?void 0:h.page_size,page_token:h===null||h===void 0?void 0:h.page_token}),y=new Headers(ve({Accept:"application/json"})),v=await Ce(e._options.security),C=Ae(v),T={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:C,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},I=e._createRequest(T,{security:C,method:"GET",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:y,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!I.ok)return[I,{status:"invalid"}];let P=I.value,N=await e._do(P,{context:T,isErrorStatusCode:(V)=>me({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!N.ok)return[N,{status:"request-error",request:P}];let D=N.value,[q]=await Te(ie("4XX"),ie("5XX"),Re("default"))(D,P);if(!q.ok)return[q,{status:"complete",request:P,response:D}];return[q,{status:"complete",request:P,response:D}]}function p_(e,t,n,i,o){return new pe(uP(e,t,n,i,o))}async function uP(e,t,n,i,o){var s,c,d;let h={id:t,api_version:n,body:i},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(s=h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/webhooks/{id}:ping")(g),E=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),y=await Ce(e._options.security),v=Ae(y),C={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(C,{security:v,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:E,body:m,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!T.ok)return[T,{status:"invalid"}];let I=T.value,P=await e._do(I,{context:C,isErrorStatusCode:(q)=>me({status:q},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let N=P.value,[D]=await Te(ie("4XX"),ie("5XX"),Re("default"))(N,I);if(!D.ok)return[D,{status:"complete",request:I,response:N}];return[D,{status:"complete",request:I,response:N}]}function h_(e,t,n,i,o){return new pe(cP(e,t,n,i,o))}async function cP(e,t,n,i,o){var s,c,d;let h={id:t,api_version:n,body:i},m=Ft("body",h.body,{explode:!0}),g={api_version:re("api_version",(s=h.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",h.id,{explode:!1,charEncoding:"percent"})},_=ye("/{api_version}/webhooks/{id}:rotateSigningSecret")(g),E=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),y=await Ce(e._options.security),v=Ae(y),C={options:e._options,base_url:(d=(c=o===null||o===void 0?void 0:o.server_url)!==null&&c!==void 0?c:e._baseURL)!==null&&d!==void 0?d:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(o===null||o===void 0?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(o===null||o===void 0?void 0:o.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(C,{security:v,method:"POST",baseURL:o===null||o===void 0?void 0:o.server_url,path:_,headers:E,body:m,userAgent:e._options.user_agent,timeout_ms:(o===null||o===void 0?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!T.ok)return[T,{status:"invalid"}];let I=T.value,P=await e._do(I,{context:C,isErrorStatusCode:(q)=>me({status:q},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let N=P.value,[D]=await Te(ie("4XX"),ie("5XX"),Re("default"))(N,I);if(!D.ok)return[D,{status:"complete",request:I,response:N}];return[D,{status:"complete",request:I,response:N}]}function m_(e,t,n,i,o,s){return new pe(dP(e,t,n,i,o,s))}async function dP(e,t,n,i,o,s){var c,d,f;let m={id:t,api_version:n,update_mask:i,body:o},g=Ft("body",m.body,{explode:!0}),_={api_version:re("api_version",(c=m.api_version)!==null&&c!==void 0?c:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:re("id",m.id,{explode:!1,charEncoding:"percent"})},E=ye("/{api_version}/webhooks/{id}")(_),y=hn({update_mask:m.update_mask}),v=new Headers(ve({"Content-Type":"application/json",Accept:"application/json"})),C=await Ce(e._options.security),T=Ae(C),I={options:e._options,base_url:(f=(d=s===null||s===void 0?void 0:s.server_url)!==null&&d!==void 0?d:e._baseURL)!==null&&f!==void 0?f:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:(s===null||s===void 0?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8000,exponent:2,maxElapsedTime:30000},retryConnectionErrors:!0,maxRetries:4},retry_codes:(s===null||s===void 0?void 0:s.retry_codes)||["408","409","429","5XX"]},P=e._createRequest(I,{security:T,method:"PATCH",baseURL:s===null||s===void 0?void 0:s.server_url,path:E,headers:v,query:y,body:g,userAgent:e._options.user_agent,timeout_ms:(s===null||s===void 0?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!P.ok)return[P,{status:"invalid"}];let N=P.value,D=await e._do(N,{context:I,isErrorStatusCode:(J)=>me({status:J},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!D.ok)return[D,{status:"request-error",request:N}];let q=D.value,[V]=await Te(ie("4XX"),ie("5XX"),Re("default"))(q,N);if(!V.ok)return[V,{status:"complete",request:N,response:q}];return[V,{status:"complete",request:N,response:q}]}class g_ extends mn{list(e,t){return Ee(f_(this,e===null||e===void 0?void 0:e.api_version,e===null||e===void 0?void 0:e.page_size,e===null||e===void 0?void 0:e.page_token,t))}create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return Ee(u_(this,i,n,t))}delete(e,t,n){return Ee(c_(this,e,t===null||t===void 0?void 0:t.api_version,n))}get(e,t,n){return Ee(d_(this,e,t===null||t===void 0?void 0:t.api_version,n))}update(e,t,n){let i=t!==null&&t!==void 0?t:{},{api_version:o,update_mask:s}=i,c=Ve(i,["api_version","update_mask"]),d=t===void 0||Object.keys(c).length===0?void 0:c;return Ee(m_(this,e,o,s,d,n))}ping(e,t,n,i){return Ee(p_(this,e,t,n,i))}rotateSigningSecret(e,t,n,i){return Ee(h_(this,e,t,n,i))}}var fP=class extends mn{get agents(){var t;return(t=this._agents)!==null&&t!==void 0?t:this._agents=new Gg(this._options)}get environments(){var t;return(t=this._environments)!==null&&t!==void 0?t:this._environments=new Vg(this._options)}get interactions(){var t;return(t=this._interactions)!==null&&t!==void 0?t:this._interactions=new e_(this._options)}get triggers(){var t;return(t=this._triggers)!==null&&t!==void 0?t:this._triggers=new l_(this._options)}get webhooks(){var t;return(t=this._webhooks)!==null&&t!==void 0?t:this._webhooks=new g_(this._options)}},pP=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function hP(e){let t=e.getBaseUrl();if(!t)throw Error("Base URL must be set.");return t.replace(/\/+$/,"")}function mP(e){let t=gP(e.getApiVersion()),n=e.getProject(),i=e.getLocation();if(e.isVertexAI()&&t&&n&&i)return`${t}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(i)}`;return t}function Nt(e,t={}){var n,i,o,s,c;return new fP(Object.assign(Object.assign({},t),{api_version:(n=t.api_version)!==null&&n!==void 0?n:mP(e),security:(i=t.security)!==null&&i!==void 0?i:new eg({defaultHeaders:Object.assign(Object.assign({},(o=e.getDefaultHeaders)===null||o===void 0?void 0:o.call(e)),(s=e.getHeaders)===null||s===void 0?void 0:s.call(e)),getAuthHeaders:(f)=>e.getAuthHeaders(f)}),server_url:(c=t.server_url)!==null&&c!==void 0?c:hP(e)}))}class __{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);if(i.stream===!0){let s=await ys(()=>this.getClient(n).interactions.create(Object.assign(Object.assign({},i),{stream:!0,api_version:n}),he(t,!0)));return Bh(s)}let o=await we(Zg(this.getClient(n),i,n,he(t)));return Es(o)}async get(e,t={},n){let{api_version:i,stream:o=!1,last_event_id:s,include_input:c}=t!==null&&t!==void 0?t:{};if(o===!0){let f=await ys(()=>this.getClient(i).interactions.get(e,{stream:o,last_event_id:s,include_input:c,api_version:i},he(n,!0)));return Bh(f)}let d=await we(jg(this.getClient(i),e,i,c,s,o,he(n)));return Es(d)}async delete(e,t={},n){return ys(()=>this.getClient(t===null||t===void 0?void 0:t.api_version).interactions.delete(e,{api_version:t===null||t===void 0?void 0:t.api_version},he(n)))}async cancel(e,t={},n){return Es(await we(Qg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n))))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class y_{constructor(e){this.parentClient=e}async create(e={},t){let n=e!==null&&e!==void 0?e:{},{api_version:i}=n,o=Ve(n,["api_version"]);return we(kg(this.getClient(i),o,i,he(t)))}async list(e={},t){let{api_version:n,pageSize:i,pageToken:o,parent:s}=e!==null&&e!==void 0?e:{};return we(Ug(this.getClient(n),n,i,o,s,he(t)))}async get(e,t={},n){return we(Mg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async delete(e,t={},n){return we(Dg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class E_{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return we(u_(this.getClient(),i,n,he(t)))}async list(e={},t){let{api_version:n,page_size:i,page_token:o}=e!==null&&e!==void 0?e:{};return we(f_(this.getClient(),n,i,o,he(t)))}async get(e,t={},n){return we(d_(this.getClient(),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async update(e,t={},n){let i=t!==null&&t!==void 0?t:{},{api_version:o,update_mask:s}=i,c=Ve(i,["api_version","update_mask"]);return we(m_(this.getClient(),e,o,s,c,he(n)))}async delete(e,t={},n){return we(c_(this.getClient(),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async rotateSigningSecret(e,t={},n){let i=t!==null&&t!==void 0?t:{},{api_version:o}=i,s=Ve(i,["api_version"]);return we(h_(this.getClient(),e,o,s,he(n)))}async ping(e,t=void 0,n){let{api_version:i,body:o}=t!==null&&t!==void 0?t:{};return we(p_(this.getClient(),e,i,o,he(n)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}class v_{constructor(e){this.parentClient=e}async create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return we(t_(this.getClient(n),i,n,he(t)))}async list(e={},t){let{api_version:n,filter:i,pageSize:o,pageToken:s}=e!==null&&e!==void 0?e:{};return we(o_(this.getClient(n),n,i,o,s,he(t)))}async get(e,t={},n){return we(r_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async update(e,t,n){let{api_version:i}=t,o=Ve(t,["api_version"]);return we(a_(this.getClient(i),e,o,i,he(n)))}async delete(e,t={},n){return we(n_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async run(e,t={},n){return we(s_(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async listExecutions(e,t={},n){let{api_version:i,pageSize:o,pageToken:s}=t!==null&&t!==void 0?t:{};return we(i_(this.getClient(i),e,i,o,s,he(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}function gP(e){return e.replace(/^\/+|\/+$/g,"")}function he(e,t=!1){var n,i,o,s;if(!e&&!t)return;let c=e!==null&&e!==void 0?e:{},{timeout:d,maxRetries:f,defaultBaseURL:h,query:m,body:g,fetchOptions:_}=c,E=Ve(c,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),y=Object.assign({},E);if(Oi(m))y.extra_query=m;else Vh("query",m);if(Oi(g))y.extra_body=g;else Vh("body",g);let v=(n=E.fetch_options)!==null&&n!==void 0?n:_;if(v)y.fetch_options=v;let C=(i=E.server_url)!==null&&i!==void 0?i:h;if(C)y.server_url=C;let T=(o=E.timeout_ms)!==null&&o!==void 0?o:d;if(T!==void 0)y.timeout_ms=T;if(f!==void 0)y.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:f};if(t){let I=new Headers((s=y.headers)!==null&&s!==void 0?s:v===null||v===void 0?void 0:v.headers);I.set("Accept","text/event-stream"),y.headers=I}return y}function Vh(e,t){if(t!==void 0&&t!==null)console.warn(`GoogleGenAI.interactions: request option ${e} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function we(e){let[t,n]=await e.$inspect();if(!t.ok)throw $n(t.error);return _P(t.value,n)}async function ys(e){try{return await e()}catch(t){throw $n(t)}}function Bh(e){let t=e;return new Proxy(e,{get(n,i){if(i!==Symbol.asyncIterator){let o=Reflect.get(n,i,n);return typeof o==="function"?o.bind(n):o}return function(){let s=t[Symbol.asyncIterator]();return{async next(...c){try{return await s.next(...c)}catch(d){throw $n(d)}},async return(c){if(!s.return)return{done:!0,value:c};try{return await s.return(c)}catch(d){throw $n(d)}},async throw(c){if(!s.throw)throw $n(c);try{return await s.throw(c)}catch(d){throw $n(d)}},[Symbol.asyncIterator](){return this}}}}})}function _P(e,t){if(!Oi(e)||t.status!=="complete")return e;return Object.assign(Object.assign({},e),{sdkHttpResponse:yP(t.response,e)})}function yP(e,t){let n={};for(let[i,o]of e.headers.entries())n[i]=o;return{headers:n,responseInternal:e,json:async()=>t}}function Es(e){let t=EP(e);if(!t)return e;return TP(t)}function EP(e){if(!Oi(e))return;if(Array.isArray(e.steps))return e;if(vP(e)){let t=e.outputs;if(Array.isArray(t)){let{outputs:n}=e,i=Ve(e,["outputs"]);return Object.assign(Object.assign({},i),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}function vP(e){let t=e.model;return typeof t==="string"&&pP.has(t)}function Oi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function TP(e){var t,n;let i=AP(e),o=(t=i.steps)!==null&&t!==void 0?t:[],s=[],c=!1;e:for(let g=o.length-1;g>=0;g--){let _=o[g];if(_.type==="user_input")break;if(_.type!=="model_output"||!_.content){if(c)break;continue}let E=_.content;for(let y=E.length-1;y>=0;y--){let v=E[y];if(v.type==="text")c=!0,s.push((n=v.text)!==null&&n!==void 0?n:"");else if(c)break e}}let d,f,h;for(let g=o.length-1;g>=0;g--){let _=o[g];if(_.type==="user_input")break;if(_.type==="model_output"&&_.content)for(let E=_.content.length-1;E>=0;E--){let y=_.content[E];if(y.type==="image"&&!d)d=y;if(y.type==="audio"&&!f)f=y;if(y.type==="video"&&!h)h=y}}let m=s.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),m&&{output_text:m}),d?{output_image:d}:{}),f?{output_audio:f}:{}),h?{output_video:h}:{})}function AP(e){return Object.assign(Object.assign({},e),{created:$h(e.created),updated:$h(e.updated)})}function $h(e){return e instanceof Date?e.toISOString():e}class T_{constructor(e){this.resolveClient=e}async list(e,t){let{environment:n,path:i,page_size:o,page_token:s,recursive:c,api_version:d}=e;return we(Fg(this.resolveClient(d),n,i,d,o,s,c,he(t)))}}class A_{constructor(e){this.parentClient=e,this.files=new T_((t)=>this.getClient(t))}async create(e,t){let{api_version:n}=e,i=Ve(e,["api_version"]);return we(bg(this.getClient(n),i,n,he(t)))}async list(e={},t){let{api_version:n,page_size:i,page_token:o}=e!==null&&e!==void 0?e:{};return we(Og(this.getClient(n),n,i,o,he(t)))}async get(e,t={},n){return we(qg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}async delete(e,t={},n){return we(Lg(this.getClient(t===null||t===void 0?void 0:t.api_version),e,t===null||t===void 0?void 0:t.api_version,he(n)))}getClient(e){var t;if(e)return Nt(this.parentClient,{api_version:e});return(t=this.sdk)!==null&&t!==void 0||(this.sdk=Nt(this.parentClient)),this.sdk}}var Jh="x-goog-api-key",pr="https://www.googleapis.com/auth/cloud-platform";class C_{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let t=CP(e.googleAuthOptions);this.googleAuth=new Yh.GoogleAuth(t)}async addAuthHeaders(e,t){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(e.get(Jh)!==null)return;if(this.apiKey===void 0)throw Error("Trying to set API key header but apiKey is not set");e.append(Jh,this.apiKey)}async addGoogleAuthHeaders(e,t){if(this.googleAuth===void 0)throw Error("Trying to set google-auth headers but googleAuth is unset");let n=await this.googleAuth.getRequestHeaders(t);for(let[i,o]of n){if(e.get(i)!==null)continue;e.append(i,o)}}}function CP(e){let t;if(!e)return t={scopes:[pr]},t;else{if(t=e,!t.scopes)return t.scopes=[pr],t;else if(typeof t.scopes==="string"&&t.scopes!==pr||Array.isArray(t.scopes)&&t.scopes.indexOf(pr)<0)throw Error(`Invalid auth scopes. Scopes must include: ${pr}`);return t}}class S_{async download(e,t){if(e.downloadPath){let n=await SP(e,t);if(n instanceof yn){let i=BT(e.downloadPath);JT.fromWeb(n.responseInternal.body).pipe(i),await XT(i)}else try{await $T(e.downloadPath,n,{encoding:"base64"})}catch(i){throw Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}}async function SP(e,t){var n,i,o;let s=Ks(e.file);if(s!==void 0)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},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 if(vm(e.file)){let c=(o=e.file.video)===null||o===void 0?void 0:o.videoBytes;if(typeof c==="string")return c;else throw Error("Failed to download generated video, Uri or videoBytes not found.")}else if(Tm(e.file)){let c=e.file.videoBytes;if(typeof c==="string")return c;else throw Error("Failed to download video, Uri or videoBytes not found.")}else throw Error("Unsupported file type")}class I_{create(e,t,n){return new w_(e,t,n)}}class w_{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}connect(){this.ws=new Wh.WebSocket(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 Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw Error("WebSocket is not connected");this.ws.close()}}function IP(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["_url","name"],i);return n}function wP(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["_url","name"],i);return n}function RP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);return n}function PP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);return n}function qs(e,t){let n={},i=l(e,["parts"]);if(i!=null){let s=i;if(Array.isArray(s))s=s.map((c)=>HP(c));u(n,["parts"],s)}let o=l(e,["role"]);if(o!=null)u(n,["role"],o);return n}function NP(e,t,n){let i={};if(l(e,["validationDataset"])!==void 0)throw Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=l(e,["tunedModelDisplayName"]);if(t!==void 0&&o!=null)u(t,["displayName"],o);if(l(e,["description"])!==void 0)throw Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=l(e,["epochCount"]);if(t!==void 0&&s!=null)u(t,["tuningTask","hyperparameters","epochCount"],s);let c=l(e,["learningRateMultiplier"]);if(c!=null)u(i,["tuningTask","hyperparameters","learningRateMultiplier"],c);if(l(e,["exportLastCheckpointOnly"])!==void 0)throw Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["preTunedModelCheckpointId"])!==void 0)throw Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["adapterSize"])!==void 0)throw Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tuningMode"])!==void 0)throw Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["customBaseModel"])!==void 0)throw Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=l(e,["batchSize"]);if(t!==void 0&&d!=null)u(t,["tuningTask","hyperparameters","batchSize"],d);let f=l(e,["learningRate"]);if(t!==void 0&&f!=null)u(t,["tuningTask","hyperparameters","learningRate"],f);if(l(e,["labels"])!==void 0)throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["beta"])!==void 0)throw Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["baseTeacherModel"])!==void 0)throw Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["tunedTeacherModelSource"])!==void 0)throw Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["sftLossWeightMultiplier"])!==void 0)throw Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["outputUri"])!==void 0)throw Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["rewardConfig"])!==void 0)throw Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["compositeRewardConfig"])!==void 0)throw Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["samplesPerPrompt"])!==void 0)throw Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["evaluateInterval"])!==void 0)throw Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["checkpointInterval"])!==void 0)throw Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["maxOutputTokens"])!==void 0)throw Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["thinkingLevel"])!==void 0)throw Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["validationDatasetUri"])!==void 0)throw Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["encryptionSpec"])!==void 0)throw Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function xP(e,t,n){let i={},o=l(n,["config","method"]);if(o===void 0)o="SUPERVISED_FINE_TUNING";if(o==="SUPERVISED_FINE_TUNING"){let H=l(e,["validationDataset"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec"],ki(H))}else if(o==="PREFERENCE_TUNING"){let H=l(e,["validationDataset"]);if(t!==void 0&&H!=null)u(t,["preferenceOptimizationSpec"],ki(H))}else if(o==="DISTILLATION"){let H=l(e,["validationDataset"]);if(t!==void 0&&H!=null)u(t,["distillationSpec"],ki(H))}else if(o==="REINFORCEMENT_TUNING"){let H=l(e,["validationDataset"]);if(t!==void 0&&H!=null)u(t,["reinforcementTuningSpec"],ki(H))}let s=l(e,["tunedModelDisplayName"]);if(t!==void 0&&s!=null)u(t,["tunedModelDisplayName"],s);let c=l(e,["description"]);if(t!==void 0&&c!=null)u(t,["description"],c);let d=l(n,["config","method"]);if(d===void 0)d="SUPERVISED_FINE_TUNING";if(d==="SUPERVISED_FINE_TUNING"){let H=l(e,["epochCount"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","hyperParameters","epochCount"],H)}else if(d==="PREFERENCE_TUNING"){let H=l(e,["epochCount"]);if(t!==void 0&&H!=null)u(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],H)}else if(d==="DISTILLATION"){let H=l(e,["epochCount"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","hyperParameters","epochCount"],H)}else if(d==="REINFORCEMENT_TUNING"){let H=l(e,["epochCount"]);if(t!==void 0&&H!=null)u(t,["reinforcementTuningSpec","hyperParameters","epochCount"],H)}let f=l(n,["config","method"]);if(f===void 0)f="SUPERVISED_FINE_TUNING";if(f==="SUPERVISED_FINE_TUNING"){let H=l(e,["learningRateMultiplier"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],H)}else if(f==="PREFERENCE_TUNING"){let H=l(e,["learningRateMultiplier"]);if(t!==void 0&&H!=null)u(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],H)}else if(f==="DISTILLATION"){let H=l(e,["learningRateMultiplier"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","hyperParameters","learningRateMultiplier"],H)}else if(f==="REINFORCEMENT_TUNING"){let H=l(e,["learningRateMultiplier"]);if(t!==void 0&&H!=null)u(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],H)}let h=l(n,["config","method"]);if(h===void 0)h="SUPERVISED_FINE_TUNING";if(h==="SUPERVISED_FINE_TUNING"){let H=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","exportLastCheckpointOnly"],H)}else if(h==="PREFERENCE_TUNING"){let H=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&H!=null)u(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],H)}else if(h==="DISTILLATION"){let H=l(e,["exportLastCheckpointOnly"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","exportLastCheckpointOnly"],H)}let m=l(n,["config","method"]);if(m===void 0)m="SUPERVISED_FINE_TUNING";if(m==="SUPERVISED_FINE_TUNING"){let H=l(e,["adapterSize"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","hyperParameters","adapterSize"],H)}else if(m==="PREFERENCE_TUNING"){let H=l(e,["adapterSize"]);if(t!==void 0&&H!=null)u(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],H)}else if(m==="DISTILLATION"){let H=l(e,["adapterSize"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","hyperParameters","adapterSize"],H)}else if(m==="REINFORCEMENT_TUNING"){let H=l(e,["adapterSize"]);if(t!==void 0&&H!=null)u(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],H)}let g=l(n,["config","method"]);if(g===void 0)g="SUPERVISED_FINE_TUNING";if(g==="SUPERVISED_FINE_TUNING"){let H=l(e,["tuningMode"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","tuningMode"],H)}else if(g==="DISTILLATION"){let H=l(e,["tuningMode"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","tuningMode"],H)}let _=l(e,["customBaseModel"]);if(t!==void 0&&_!=null)u(t,["customBaseModel"],_);let E=l(n,["config","method"]);if(E===void 0)E="SUPERVISED_FINE_TUNING";if(E==="SUPERVISED_FINE_TUNING"){let H=l(e,["batchSize"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","hyperParameters","batchSize"],H)}else if(E==="DISTILLATION"){let H=l(e,["batchSize"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","hyperParameters","batchSize"],H)}else if(E==="REINFORCEMENT_TUNING"){let H=l(e,["batchSize"]);if(t!==void 0&&H!=null)u(t,["reinforcementTuningSpec","hyperParameters","batchSize"],H)}let y=l(n,["config","method"]);if(y===void 0)y="SUPERVISED_FINE_TUNING";if(y==="SUPERVISED_FINE_TUNING"){let H=l(e,["learningRate"]);if(t!==void 0&&H!=null)u(t,["supervisedTuningSpec","hyperParameters","learningRate"],H)}else if(y==="DISTILLATION"){let H=l(e,["learningRate"]);if(t!==void 0&&H!=null)u(t,["distillationSpec","hyperParameters","learningRate"],H)}let v=l(e,["labels"]);if(t!==void 0&&v!=null)u(t,["labels"],v);let C=l(e,["beta"]);if(t!==void 0&&C!=null)u(t,["preferenceOptimizationSpec","hyperParameters","beta"],C);let T=l(e,["baseTeacherModel"]);if(t!==void 0&&T!=null)u(t,["distillationSpec","baseTeacherModel"],T);let I=l(e,["tunedTeacherModelSource"]);if(t!==void 0&&I!=null)u(t,["distillationSpec","tunedTeacherModelSource"],I);let P=l(e,["sftLossWeightMultiplier"]);if(t!==void 0&&P!=null)u(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],P);let N=l(e,["outputUri"]);if(t!==void 0&&N!=null)u(t,["outputUri"],N);let D=l(e,["rewardConfig"]);if(t!==void 0&&D!=null)u(t,["reinforcementTuningSpec","singleRewardConfig"],D);let q=l(e,["compositeRewardConfig"]);if(t!==void 0&&q!=null)u(t,["reinforcementTuningSpec","compositeRewardConfig"],q);let V=l(e,["samplesPerPrompt"]);if(t!==void 0&&V!=null)u(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],V);let J=l(e,["evaluateInterval"]);if(t!==void 0&&J!=null)u(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],J);let L=l(e,["checkpointInterval"]);if(t!==void 0&&L!=null)u(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],L);let Y=l(e,["maxOutputTokens"]);if(t!==void 0&&Y!=null)u(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],Y);let Z=l(e,["thinkingLevel"]);if(t!==void 0&&Z!=null)u(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],Z);let ne=l(e,["validationDatasetUri"]);if(t!==void 0&&ne!=null)u(t,["reinforcementTuningSpec","validationDatasetUri"],ne);let W=l(e,["encryptionSpec"]);if(t!==void 0&&W!=null)u(t,["encryptionSpec"],W);return i}function kP(e,t){let n={},i=l(e,["baseModel"]);if(i!=null)u(n,["baseModel"],i);let o=l(e,["preTunedModel"]);if(o!=null)u(n,["preTunedModel"],o);let s=l(e,["trainingDataset"]);if(s!=null)$P(s);let c=l(e,["config"]);if(c!=null)NP(c,n);return n}function DP(e,t){let n={},i=l(e,["baseModel"]);if(i!=null)u(n,["baseModel"],i);let o=l(e,["preTunedModel"]);if(o!=null)u(n,["preTunedModel"],o);let s=l(e,["trainingDataset"]);if(s!=null)JP(s,n,t);let c=l(e,["config"]);if(c!=null)xP(c,n,t);return n}function R_(e,t){let n={},i=l(e,["epochCount"]);if(i!=null)u(n,["epochCount"],i);let o=l(e,["learningRateMultiplier"]);if(o!=null)u(n,["learningRateMultiplier"],o);let s=l(e,["adapterSize"]);if(s!=null)u(n,["adapterSize"],s);let c=l(e,["batchSize"]);if(c!=null)u(n,["batchSize"],c);let d=l(e,["learningRate"]);if(d!=null)u(n,["learningRate"],d);let f=l(e,["generationConfig"]);if(f!=null)u(n,["generationConfig"],GP(f));return n}function MP(e,t){let n={},i=l(e,["promptDatasetUri"]);if(i!=null)u(n,["promptDatasetUri"],i);let o=l(e,["validationDatasetUri"]);if(o!=null)u(n,["validationDatasetUri"],o);let s=l(e,["baseTeacherModel"]);if(s!=null)u(n,["baseTeacherModel"],s);let c=l(e,["tunedTeacherModelSource"]);if(c!=null)u(n,["tunedTeacherModelSource"],c);let d=l(e,["hyperparameters"]);if(d!=null)u(n,["hyperparameters"],R_(d));return n}function UP(e,t){let n={},i=l(e,["baseTeacherModel"]);if(i!=null)u(n,["baseTeacherModel"],i);let o=l(e,["hyperParameters"]);if(o!=null)u(n,["hyperParameters"],R_(o));let s=l(e,["pipelineRootDirectory"]);if(s!=null)u(n,["pipelineRootDirectory"],s);let c=l(e,["promptDatasetUri"]);if(c!=null)u(n,["promptDatasetUri"],c);let d=l(e,["studentModel"]);if(d!=null)u(n,["studentModel"],d);let f=l(e,["trainingDatasetUri"]);if(f!=null)u(n,["trainingDatasetUri"],f);let h=l(e,["tunedTeacherModelSource"]);if(h!=null)u(n,["tunedTeacherModelSource"],h);let m=l(e,["tuningMode"]);if(m!=null)u(n,["tuningMode"],m);let g=l(e,["validationDatasetUri"]);if(g!=null)u(n,["validationDatasetUri"],g);return n}function GP(e,t){let n={},i=l(e,["modelConfig"]);if(i!=null)u(n,["modelSelectionConfig"],i);let o=l(e,["responseJsonSchema"]);if(o!=null)u(n,["responseJsonSchema"],Yn(o));let s=l(e,["audioTranscriptionConfig"]);if(s!=null)u(n,["audioTranscriptionConfig"],s);let c=l(e,["audioTimestamp"]);if(c!=null)u(n,["audioTimestamp"],c);let d=l(e,["candidateCount"]);if(d!=null)u(n,["candidateCount"],d);let f=l(e,["enableAffectiveDialog"]);if(f!=null)u(n,["enableAffectiveDialog"],f);let h=l(e,["frequencyPenalty"]);if(h!=null)u(n,["frequencyPenalty"],h);let m=l(e,["logprobs"]);if(m!=null)u(n,["logprobs"],m);let g=l(e,["maxOutputTokens"]);if(g!=null)u(n,["maxOutputTokens"],g);let _=l(e,["mediaResolution"]);if(_!=null)u(n,["mediaResolution"],_);let E=l(e,["presencePenalty"]);if(E!=null)u(n,["presencePenalty"],E);let y=l(e,["responseFormat"]);if(y!=null){let Z=y;if(Array.isArray(Z))Z=Z.map((ne)=>ne);u(n,["responseFormat"],Z)}let v=l(e,["responseLogprobs"]);if(v!=null)u(n,["responseLogprobs"],v);let C=l(e,["responseMimeType"]);if(C!=null)u(n,["responseMimeType"],C);let T=l(e,["responseModalities"]);if(T!=null)u(n,["responseModalities"],T);let I=l(e,["responseSchema"]);if(I!=null)u(n,["responseSchema"],I);let P=l(e,["routingConfig"]);if(P!=null)u(n,["routingConfig"],P);let N=l(e,["seed"]);if(N!=null)u(n,["seed"],N);let D=l(e,["speechConfig"]);if(D!=null)u(n,["speechConfig"],D);let q=l(e,["stopSequences"]);if(q!=null)u(n,["stopSequences"],q);let V=l(e,["temperature"]);if(V!=null)u(n,["temperature"],V);let J=l(e,["thinkingConfig"]);if(J!=null)u(n,["thinkingConfig"],J);let L=l(e,["topK"]);if(L!=null)u(n,["topK"],L);let Y=l(e,["topP"]);if(Y!=null)u(n,["topP"],Y);return n}function bP(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["_url","name"],i);return n}function LP(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["_url","name"],i);return n}function qP(e,t,n){let i={},o=l(e,["pageSize"]);if(t!==void 0&&o!=null)u(t,["_query","pageSize"],o);let s=l(e,["pageToken"]);if(t!==void 0&&s!=null)u(t,["_query","pageToken"],s);let c=l(e,["filter"]);if(t!==void 0&&c!=null)u(t,["_query","filter"],c);return i}function OP(e,t){let n={},i=l(e,["config"]);if(i!=null)qP(i,n);return n}function FP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["nextPageToken"]);if(o!=null)u(n,["nextPageToken"],o);let s=l(e,["tuningJobs"]);if(s!=null){let c=s;if(Array.isArray(c))c=c.map((d)=>Os(d));u(n,["tuningJobs"],c)}return n}function HP(e,t){let n={},i=l(e,["mediaResolution"]);if(i!=null)u(n,["mediaResolution"],i);if(l(e,["toolCall"])!==void 0)throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(e,["toolResponse"])!==void 0)throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=l(e,["audioTranscription"]);if(o!=null)u(n,["audioTranscription"],o);let s=l(e,["codeExecutionResult"]);if(s!=null)u(n,["codeExecutionResult"],s);let c=l(e,["executableCode"]);if(c!=null)u(n,["executableCode"],c);let d=l(e,["fileData"]);if(d!=null)u(n,["fileData"],d);let f=l(e,["functionCall"]);if(f!=null)u(n,["functionCall"],f);let h=l(e,["functionResponse"]);if(h!=null)u(n,["functionResponse"],h);let m=l(e,["inlineData"]);if(m!=null)u(n,["inlineData"],m);let g=l(e,["text"]);if(g!=null)u(n,["text"],g);let _=l(e,["thought"]);if(_!=null)u(n,["thought"],_);let E=l(e,["thoughtSignature"]);if(E!=null)u(n,["thoughtSignature"],E);let y=l(e,["videoMetadata"]);if(y!=null)u(n,["videoMetadata"],y);if(l(e,["partMetadata"])!==void 0)throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let v=l(e,["mediaProcessing"]);if(v!=null)u(n,["mediaProcessing"],v);return n}function VP(e,t){let n={},i=l(e,["references"]);if(i!=null)u(n,["references"],i);let o=l(e,["contents"]);if(o!=null){let c=o;if(Array.isArray(c))c=c.map((d)=>qs(d));u(n,["contents"],c)}let s=l(e,["systemInstruction"]);if(s!=null)u(n,["systemInstruction"],qs(s));return n}function BP(e,t){let n={},i=l(e,["name"]);if(i!=null)u(n,["model"],i);let o=l(e,["name"]);if(o!=null)u(n,["endpoint"],o);return n}function $P(e,t){let n={};if(l(e,["gcsUri"])!==void 0)throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["vertexDatasetResource"])!==void 0)throw Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=l(e,["examples"]);if(i!=null){let o=i;if(Array.isArray(o))o=o.map((s)=>s);u(n,["examples","examples"],o)}return n}function JP(e,t,n){let i={},o=l(n,["config","method"]);if(o===void 0)o="SUPERVISED_FINE_TUNING";if(o==="SUPERVISED_FINE_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(o==="PREFERENCE_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if(o==="DISTILLATION"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["distillationSpec","promptDatasetUri"],c)}else if(o==="REINFORCEMENT_TUNING"){let c=l(e,["gcsUri"]);if(t!==void 0&&c!=null)u(t,["reinforcementTuningSpec","trainingDatasetUri"],c)}let s=l(n,["config","method"]);if(s===void 0)s="SUPERVISED_FINE_TUNING";if(s==="SUPERVISED_FINE_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(s==="PREFERENCE_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if(s==="DISTILLATION"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["distillationSpec","promptDatasetUri"],c)}else if(s==="REINFORCEMENT_TUNING"){let c=l(e,["vertexDatasetResource"]);if(t!==void 0&&c!=null)u(t,["reinforcementTuningSpec","trainingDatasetUri"],c)}if(l(e,["examples"])!==void 0)throw Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return i}function XP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["state"]);if(s!=null)u(n,["state"],Em(s));let c=l(e,["createTime"]);if(c!=null)u(n,["createTime"],c);let d=l(e,["tuningTask","startTime"]);if(d!=null)u(n,["startTime"],d);let f=l(e,["tuningTask","completeTime"]);if(f!=null)u(n,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(n,["updateTime"],h);let m=l(e,["description"]);if(m!=null)u(n,["description"],m);let g=l(e,["baseModel"]);if(g!=null)u(n,["baseModel"],g);let _=l(e,["_self"]);if(_!=null)u(n,["tunedModel"],BP(_));return n}function Os(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["state"]);if(s!=null)u(n,["state"],Em(s));let c=l(e,["createTime"]);if(c!=null)u(n,["createTime"],c);let d=l(e,["startTime"]);if(d!=null)u(n,["startTime"],d);let f=l(e,["endTime"]);if(f!=null)u(n,["endTime"],f);let h=l(e,["updateTime"]);if(h!=null)u(n,["updateTime"],h);let m=l(e,["error"]);if(m!=null)u(n,["error"],m);let g=l(e,["description"]);if(g!=null)u(n,["description"],g);let _=l(e,["baseModel"]);if(_!=null)u(n,["baseModel"],_);let E=l(e,["tunedModel"]);if(E!=null)u(n,["tunedModel"],E);let y=l(e,["preTunedModel"]);if(y!=null)u(n,["preTunedModel"],y);let v=l(e,["supervisedTuningSpec"]);if(v!=null)u(n,["supervisedTuningSpec"],v);let C=l(e,["preferenceOptimizationSpec"]);if(C!=null)u(n,["preferenceOptimizationSpec"],C);let T=l(e,["distillationSamplingSpec"]);if(T!=null)u(n,["distillationSamplingSpec"],MP(T));let I=l(e,["distillationSpec"]);if(I!=null)u(n,["distillationSpec"],UP(I));let P=l(e,["reinforcementTuningSpec"]);if(P!=null)u(n,["reinforcementTuningSpec"],P);let N=l(e,["tuningDataStats"]);if(N!=null)u(n,["tuningDataStats"],N);let D=l(e,["encryptionSpec"]);if(D!=null)u(n,["encryptionSpec"],D);let q=l(e,["partnerModelTuningSpec"]);if(q!=null)u(n,["partnerModelTuningSpec"],q);let V=l(e,["customBaseModel"]);if(V!=null)u(n,["customBaseModel"],V);let J=l(e,["evaluateDatasetRuns"]);if(J!=null){let Le=J;if(Array.isArray(Le))Le=Le.map((ze)=>ze);u(n,["evaluateDatasetRuns"],Le)}let L=l(e,["experiment"]);if(L!=null)u(n,["experiment"],L);let Y=l(e,["fullFineTuningSpec"]);if(Y!=null)u(n,["fullFineTuningSpec"],Y);let Z=l(e,["labels"]);if(Z!=null)u(n,["labels"],Z);let ne=l(e,["outputUri"]);if(ne!=null)u(n,["outputUri"],ne);let W=l(e,["pipelineJob"]);if(W!=null)u(n,["pipelineJob"],W);let H=l(e,["serviceAccount"]);if(H!=null)u(n,["serviceAccount"],H);let oe=l(e,["tunedModelDisplayName"]);if(oe!=null)u(n,["tunedModelDisplayName"],oe);let se=l(e,["tuningJobMetadata"]);if(se!=null)u(n,["tuningJobMetadata"],se);let Ne=l(e,["tuningJobState"]);if(Ne!=null)u(n,["tuningJobState"],Ne);let Me=l(e,["veoLoraTuningSpec"]);if(Me!=null)u(n,["veoLoraTuningSpec"],Me);let Xe=l(e,["veoTuningSpec"]);if(Xe!=null)u(n,["veoTuningSpec"],Xe);return n}function KP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["name"]);if(o!=null)u(n,["name"],o);let s=l(e,["metadata"]);if(s!=null)u(n,["metadata"],s);let c=l(e,["done"]);if(c!=null)u(n,["done"],c);let d=l(e,["error"]);if(d!=null)u(n,["error"],d);return n}function ki(e,t){let n={},i=l(e,["gcsUri"]);if(i!=null)u(n,["validationDatasetUri"],i);let o=l(e,["vertexDatasetResource"]);if(o!=null)u(n,["validationDatasetUri"],o);return n}function YP(e,t){let n={},i=l(e,["parent"]);if(i!=null)u(n,["_url","parent"],i);let o=l(e,["sampleResponse"]);if(o!=null)u(n,["sampleResponse"],qs(o));let s=l(e,["example"]);if(s!=null)u(n,["example"],VP(s));let c=l(e,["singleRewardConfig"]);if(c!=null)u(n,["singleRewardConfig"],c);let d=l(e,["compositeRewardConfig"]);if(d!=null)u(n,["compositeRewardConfig"],d);return n}function WP(e,t){let n={},i=l(e,["sdkHttpResponse"]);if(i!=null)u(n,["sdkHttpResponse"],i);let o=l(e,["overallReward"]);if(o!=null)u(n,["overallReward"],o);let s=l(e,["error"]);if(s!=null)u(n,["error"],s);let c=l(e,["rewardInfoDetails"]);if(c!=null)u(n,["rewardInfoDetails"],c);return n}class P_ extends xt{constructor(e){super();this.apiClient=e,this.list=async(t={})=>new pn(qt.PAGED_ITEM_TUNING_JOBS,(n)=>this.listInternal(n),await this.listInternal(t),t),this.get=async(t)=>await this.getInternal(t),this.tune=async(t)=>{var n;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let i={tunedModelName:t.baseModel};if((n=t.config)===null||n===void 0?void 0:n.preTunedModelCheckpointId)i.checkpointId=t.config.preTunedModelCheckpointId;let o=Object.assign(Object.assign({},t),{preTunedModel:i});return o.baseModel=void 0,await this.tuneInternal(o)}else{let i=Object.assign({},t);return await this.tuneInternal(i)}else{let i=Object.assign({},t),o=await this.tuneMldevInternal(i),s="";if(o.metadata!==void 0&&o.metadata.tunedModel!==void 0)s=o.metadata.tunedModel;else if(o.name!==void 0&&o.name.includes("/operations/"))s=o.name.split("/operations/")[0];return{name:s,state:Ts.JOB_STATE_QUEUED}}}}async getInternal(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=LP(e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>Os(h))}else{let f=bP(e);return c=z("{name}",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>XP(h))}}async listInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=OP(e);return o=z("tuningJobs",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=FP(d),h=new rm;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,n,i,o;let s,c="",d={};if(this.apiClient.isVertexAI()){let f=wP(e);return c=z("{name}:cancel",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=PP(h),g=new ws;return Object.assign(g,m),g})}else{let f=IP(e);return c=z("{name}:cancel",f._url),d=f._query,delete f._url,delete f._query,s=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(f),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then((h)=>h.json().then((m)=>{let g=m;return g.sdkHttpResponse={headers:h.headers},g})),s.then((h)=>{let m=RP(h),g=new ws;return Object.assign(g,m),g})}}async tuneInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=DP(e,e);return o=z("tuningJobs",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>Os(d))}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");else{let c=kP(e);return o=z("tunedModels",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>KP(d))}}async validateReward(e){var t,n;let i,o="",s={};if(this.apiClient.isVertexAI()){let c=YP(e);return o=z("{parent}/tuningJobs:validateReinforcementTuningReward",c._url),s=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(n=e.config)===null||n===void 0?void 0:n.abortSignal}).then((d)=>d.json().then((f)=>{let h=f;return h.sdkHttpResponse={headers:d.headers},h})),i.then((d)=>{let f=WP(d),h=new im;return Object.assign(h,f),h})}else throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}var N_=8388608,x_=3,k_=1000,D_=2,sn="x-goog-upload-status";async function zP(e,t,n,i){var o;let s=await M_(e,t,n,i),c=await(s===null||s===void 0?void 0:s.json());if(((o=s===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return c.file}async function QP(e,t,n,i){var o;let s=await M_(e,t,n,i),c=await(s===null||s===void 0?void 0:s.json());if(((o=s===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let d=Hs(c),f=new Hi;return Object.assign(f,d),f}async function M_(e,t,n,i){var o,s,c;let d=t,f=(i===null||i===void 0?void 0:i.baseUrl)||((o=n.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(f){let E=new URL(f),y=new URL(t);y.protocol=E.protocol,y.host=E.host,y.port=E.port,d=y.toString()}let h=0,m=0,g=new yn(new Response),_="upload";h=e.size;while(m<h){let E=Math.min(N_,h-m),y=e.slice(m,m+E);if(m+E>=h)_+=", finalize";let v=0,C=k_;while(v<x_){let T=Object.assign(Object.assign({},(i===null||i===void 0?void 0:i.headers)||{}),{"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":String(m)});if(g=await n.request({path:"",body:y,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:d,headers:T})}),(s=g===null||g===void 0?void 0:g.headers)===null||s===void 0?void 0:s[sn])break;v++,await U_(C),C=C*D_}if(m+=E,((c=g===null||g===void 0?void 0:g.headers)===null||c===void 0?void 0:c[sn])!=="active")break;if(h<=m)throw Error("All content has been uploaded, but the upload status is not finalized.")}return g}async function ZP(e){return{size:e.size,type:e.type}}function U_(e){return new Promise((t)=>setTimeout(t,e))}class G_{async stat(e){let t={size:0,type:void 0};if(typeof e==="string"){let n=await Fi.stat(e);return t.size=n.size,t.type=this.inferMimeType(e),t}else return await ZP(e)}async upload(e,t,n,i){if(typeof e==="string")return await this.uploadFileFromPath(e,t,n,i);else return zP(e,t,n,i)}async uploadToFileSearchStore(e,t,n,i){if(typeof e==="string")return await this.uploadFileToFileSearchStoreFromPath(e,t,n,i);else return QP(e,t,n,i)}inferMimeType(e){let t=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"}[t.toLowerCase()]}async uploadFileFromPath(e,t,n,i){var o;let s=await this.uploadFileFromPathInternal(e,t,n,i),c=await(s===null||s===void 0?void 0:s.json());if(((o=s===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return c.file}async uploadFileToFileSearchStoreFromPath(e,t,n,i){var o;let s=await this.uploadFileFromPathInternal(e,t,n,i),c=await(s===null||s===void 0?void 0:s.json());if(((o=s===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o[sn])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let d=Hs(c),f=new Hi;return Object.assign(f,d),f}async uploadFileFromPathInternal(e,t,n,i){var o,s,c;let d=t,f=(i===null||i===void 0?void 0:i.baseUrl)||((o=n.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(f){let v=new URL(f),C=new URL(t);C.protocol=v.protocol,C.host=v.host,C.port=v.port,d=C.toString()}let h=0,m=0,g=new yn(new Response),_="upload",E,y=zh.basename(e);try{if(E=await Fi.open(e,"r"),!E)throw Error("Failed to open file");h=(await E.stat()).size;while(m<h){let v=Math.min(N_,h-m);if(m+v>=h)_+=", finalize";let C=new Uint8Array(v),{bytesRead:T}=await E.read(C,0,v,m);if(T!==v)throw Error(`Failed to read ${v} bytes from file at offset ${m}. bytes actually read: ${T}`);let I=new Blob([C]),P=0,N=k_;while(P<x_){let D=Object.assign(Object.assign({},(i===null||i===void 0?void 0:i.headers)||{}),{"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":String(m),"X-Goog-Upload-File-Name":y});if(g=await n.request({path:"",body:I,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:d,headers:D})}),(s=g===null||g===void 0?void 0:g.headers)===null||s===void 0?void 0:s[sn])break;P++,await U_(N),N=N*D_}if(m+=T,((c=g===null||g===void 0?void 0:g.headers)===null||c===void 0?void 0:c[sn])!=="active")break;if(h<=m)throw Error("All content has been uploaded, but the upload status is not finalized.")}return g}finally{if(E)await E.close()}}}class b_ extends a0{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let n=await e.auth.getRequestHeaders(),i=e.config||{},o=i.httpOptions||{},s=Object.assign({},o.headers||{});if(n)if(typeof n[Symbol.iterator]==="function")for(let[c,d]of n)s[c]=d;else for(let[c,d]of Object.entries(n))s[c]=d;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},o),{headers:s})})})}}var jP="gl-node/";function eN(e){var t;if(e&&(e.enterprise!==void 0||e.vertexai!==void 0)){if(e.enterprise!==void 0&&e.vertexai!==void 0&&e.enterprise!==e.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(t=e.enterprise)!==null&&t!==void 0?t:e.vertexai}let n=an("GOOGLE_GENAI_USE_ENTERPRISE"),i=an("GOOGLE_GENAI_USE_VERTEXAI"),o=Xh(n),s=Xh(i);if(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.");if(n!==void 0)return o;if(i!==void 0)return s;return!1}class It{getNextGenClient(){let e=this.httpOptions;if(this._nextGenClient===void 0)this._nextGenClient=Nt(this.apiClient,{timeout_ms:e===null||e===void 0?void 0:e.timeout});if(e===null||e===void 0?void 0:e.extraBody)console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored.");return this._nextGenClient}get interactions(){if(this._interactions!==void 0)return this._interactions;return this._interactions=new __(this.apiClient),this._interactions}get webhooks(){if(this._webhooks!==void 0)return this._webhooks;return this._webhooks=new E_(this.apiClient),this._webhooks}get agents(){if(this._agents!==void 0)return this._agents;return console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new y_(this.apiClient),this._agents}get triggers(){if(this._triggers!==void 0)return this._triggers;return console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new v_(this.apiClient),this._triggers}get environments(){if(this._environments!==void 0)return this._environments;return console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new A_(this.apiClient),this._environments}constructor(e={}){var t,n,i,o;if(this.vertexai=eN(e),(e.project||e.location)&&!this.vertexai)throw Error("Project and location are not supported for Gemini API backend.");let s=tN(),c=an("GOOGLE_CLOUD_PROJECT"),d=an("GOOGLE_CLOUD_LOCATION");if(this.apiKey=(t=e.apiKey)!==null&&t!==void 0?t:s,this.project=(n=e.project)!==null&&n!==void 0?n:c,this.location=(i=e.location)!==null&&i!==void 0?i:d,!this.vertexai&&!this.apiKey)console.warn("API key should be set when using the Gemini API.");if(this.vertexai){if((o=e.googleAuthOptions)===null||o===void 0?void 0:o.credentials)console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0;if(!e.project&&!e.location&&(c||d)&&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;else if((e.project||e.location)&&!e.apiKey&&s)console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0;else if(!e.project&&!e.location&&!e.apiKey&&(c||d)&&s)console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0;if(!this.location&&!this.apiKey)this.location="global"}let f=zT(e.httpOptions,this.vertexai,an("GOOGLE_VERTEX_BASE_URL"),an("GOOGLE_GEMINI_BASE_URL"));if(f)if(e.httpOptions)e.httpOptions.baseUrl=f;else e.httpOptions={baseUrl:f};this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let h=new C_({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new Bm({auth:h,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:jP+process.version,uploader:new G_,downloader:new S_}),this.models=new yt(this.apiClient),this.live=new Ym(this.apiClient,h,new I_),this.batches=new Pm(this.apiClient),this.chats=new km(this.models,this.apiClient),this.caches=new Nm(this.apiClient),this.files=new b_(this.apiClient),this.operations=new zm(this.apiClient),this.authTokens=new Qm(this.apiClient),this.tunings=new P_(this.apiClient),this.fileSearchStores=new jm(this.apiClient)}}function an(e){var t,n,i;return(i=(n=(t=process===null||process===void 0?void 0:process.env)===null||t===void 0?void 0:t[e])===null||n===void 0?void 0:n.trim())!==null&&i!==void 0?i:void 0}function Xh(e){if(e===void 0)return!1;return e.toLowerCase()==="true"}function tN(){let e=an("GOOGLE_API_KEY"),t=an("GEMINI_API_KEY");if(e&&t)console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.");return e||t||void 0}var nN={THINKING_LEVEL_UNSPECIFIED:ln.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ln.MINIMAL,LOW:ln.LOW,MEDIUM:ln.MEDIUM,HIGH:ln.HIGH};function Xt(e,t){let n=e.thinkingLevelMap?.[t],i=typeof n==="string"?n.toLowerCase():t;switch(i){case"minimal":case"low":case"medium":case"high":return i;default:throw Error(`Unsupported Google thinking level mapping for ${e.provider}/${e.id}: ${t} -> ${String(n)}`)}}function Jt(e){let t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(t)||t==="gemini-flash-latest"||t==="gemini-flash-lite-latest"||/gemma-?4/.test(t)}function Yt(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function Zt(e){return nN[e]}function _r(e){if(!Jt(e))return{thinkingBudget:0};let t=K(e,"off");if(t==="off")return{thinkingBudget:0};let n=Xt(e,t),i=Yt(n);return{thinkingLevel:Zt(i)}}function Ar(e){return e.thought===!0}function Mt(e,t){if(typeof t==="string"&&t.length>0)return t;return e}var rN=/^[A-Za-z0-9+/]+={0,2}$/;function iN(e){if(!e)return!1;if(e.length%4!==0)return!1;return rN.test(e)}function ea(e,t){return e&&iN(t)?t:void 0}function ta(e){let t=na(e);return e.startsWith("claude-")||e.startsWith("gpt-oss-")||t!==void 0&&t>=3}function na(e){let t=e.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(!t)return;return Number.parseInt(t[1],10)}function oN(e){let t=na(e);if(t!==void 0)return t>=3;return!0}function Er(e,t){let n=zt(Ue(t).messages),i=[],s=Se(n,e,(c)=>{if(!ta(e.id))return c;return c.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)});for(let c of s)if(c.role==="user")if(typeof c.content==="string")i.push({role:"user",parts:[{text:w(c.content)}]});else{let d=c.content.map((f)=>{if(f.type==="text")return{text:w(f.text)};else return{inlineData:{mimeType:f.mimeType,data:f.data}}});if(d.length===0)continue;i.push({role:"user",parts:d})}else if(c.role==="assistant"){let d=[],f=c.provider===e.provider&&c.model===e.id;for(let h of c.content)if(h.type==="text"){let m=ea(f,h.textSignature);if((!h.text||h.text.trim()==="")&&!m)continue;d.push({text:w(h.text),...m&&{thoughtSignature:m}})}else if(h.type==="thinking")if(f){let m=ea(f,h.thinkingSignature);if((!h.thinking||h.thinking.trim()==="")&&!m)continue;d.push({thought:!0,text:w(h.thinking),...m&&{thoughtSignature:m}})}else{if(!h.thinking||h.thinking.trim()==="")continue;d.push({text:w(h.thinking)})}else if(h.type==="toolCall"){let m=ea(f,h.thoughtSignature),g={functionCall:{name:h.name,args:h.arguments??{},...ta(e.id)?{id:h.id}:{}},...m&&{thoughtSignature:m}};d.push(g)}if(d.length===0)continue;i.push({role:"model",parts:d})}else if(c.role==="toolResult"){let f=c.content.filter((I)=>I.type==="text").map((I)=>I.text).join(`
|
|
38
|
+
`),h=e.input.includes("image")?c.content.filter((I)=>I.type==="image"):[],m=f.length>0,g=h.length>0,_=oN(e.id),E=m?w(f):g?"(see attached image)":"",y=h.map((I)=>({inlineData:{mimeType:I.mimeType,data:I.data}})),v=ta(e.id),C={functionResponse:{name:c.toolName,response:c.isError?{error:E}:{output:E},...g&&_&&{parts:y},...v?{id:c.toolCallId}:{}}},T=i[i.length-1];if(T?.role==="user"&&T.parts?.some((I)=>I.functionResponse))T.parts.push(C);else i.push({role:"user",parts:[C]});if(g&&!_)i.push({role:"user",parts:[{text:"Tool result image:"},...y]})}return i}var sN=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function q_(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={};for(let[n,i]of Object.entries(e)){if(sN.has(n))continue;t[n]=q_(i)}return t}function Tr(e,t=!1,n=!0){if(e.length===0)return;return[{functionDeclarations:e.map((i)=>{let o=fe(i,n),s=be(i,o);return{name:i.name,description:i.description,...t?{parameters:q_(s)}:{parametersJsonSchema:s}}})}]}function Pr(e){let t=na(e);return t!==void 0&&t>=3}function L_(e){switch(e){case"auto":return un.AUTO;case"none":return un.NONE;case"any":return un.ANY;default:return un.AUTO}}function kr(e,t,n){let i=e.some((o)=>fe(o,n)===!0);if(t==="none"||t==="any")return L_(t);if(i)return un.VALIDATED;return t?L_(t):void 0}function Rr(e){switch(e){case De.STOP:return"stop";case De.MAX_TOKENS:return"length";case De.BLOCKLIST:case De.PROHIBITED_CONTENT:case De.SPII:case De.SAFETY:case De.IMAGE_SAFETY:case De.IMAGE_PROHIBITED_CONTENT:case De.IMAGE_RECITATION:case De.IMAGE_OTHER:case De.RECITATION:case De.FINISH_REASON_UNSPECIFIED:case De.OTHER:case De.LANGUAGE:case De.MALFORMED_FUNCTION_CALL:case De.UNEXPECTED_TOOL_CALL:case De.TOO_MANY_TOOL_CALLS:case De.NO_IMAGE:return"error";default:throw Error(`Unhandled stop reason: ${e}`)}}function Cr(e,t){return ue(async()=>{try{return await e()}catch(n){if(n instanceof Error&&"status"in n&&!("headers"in n))n.headers=void 0;throw n}},{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal})}
|
|
39
|
+
export{vr,It,Xt,Jt,Yt,Zt,_r,Ar,Mt,Er,Tr,Pr,kr,Rr,Cr};
|