noskills 4.5.1 → 5.0.0
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 +497 -18
- package/noskills.js +145 -1
- package/package.json +14 -1
- package/{chunks/ajan-bridge-T5M4DPDT.js → ts/chunks/ajan-bridge-6UUIUFAV.js} +1 -1
- package/ts/chunks/anthropic-ICVQ5GK6.js +1 -0
- package/ts/chunks/approve-R7MCYHCS.js +1 -0
- package/ts/chunks/ask-GBLFPNFX.js +2 -0
- package/ts/chunks/block-YEKLMXHR.js +1 -0
- package/ts/chunks/cancel-7NS4WM2N.js +1 -0
- package/ts/chunks/chunk-2CLD527I.js +1 -0
- package/ts/chunks/chunk-34AWV7DB.js +1 -0
- package/ts/chunks/chunk-3M26Y3NG.js +27 -0
- package/{chunks/chunk-KM64FL2X.js → ts/chunks/chunk-3QVRJO3V.js} +1 -1
- package/ts/chunks/chunk-5ALJRBMW.js +22 -0
- package/ts/chunks/chunk-5NMDE2VZ.js +4 -0
- package/ts/chunks/chunk-6BKTY7SA.js +4 -0
- package/ts/chunks/chunk-6M7PCVUR.js +1 -0
- package/ts/chunks/chunk-6O2RXYTM.js +3 -0
- package/ts/chunks/chunk-7DIQYKPL.js +3 -0
- package/ts/chunks/chunk-7J6R2D2K.js +2 -0
- package/ts/chunks/chunk-ATNTR7M5.js +1 -0
- package/ts/chunks/chunk-AW3XJGEP.js +1 -0
- package/ts/chunks/chunk-BRC46A3N.js +39 -0
- package/ts/chunks/chunk-C5LYQDQH.js +368 -0
- package/ts/chunks/chunk-CCYWFSXR.js +3 -0
- package/{chunks/chunk-OAWYVETM.js → ts/chunks/chunk-CL55MNGD.js} +1 -1
- package/ts/chunks/chunk-CSP2GUD4.js +29 -0
- package/{chunks/chunk-EROZRDGT.js → ts/chunks/chunk-D2UKX2VW.js} +1 -1
- package/ts/chunks/chunk-DGYDUGTM.js +1 -0
- package/ts/chunks/chunk-FB3Z7XYQ.js +1 -0
- package/ts/chunks/chunk-FLLYK5FU.js +1 -0
- package/{chunks/chunk-EJYSOUEA.js → ts/chunks/chunk-GCPGG4YB.js} +1 -1
- package/{chunks/chunk-LN4NDYT6.js → ts/chunks/chunk-HLDPASM6.js} +1 -1
- package/ts/chunks/chunk-HNQA5O2S.js +2 -0
- package/ts/chunks/chunk-HUP7XWW6.js +1 -0
- package/ts/chunks/chunk-J3XNDEMU.js +4 -0
- package/ts/chunks/chunk-K6FVY52W.js +5 -0
- package/ts/chunks/chunk-KQJGXVWX.js +91 -0
- package/ts/chunks/chunk-M4U4Y3XQ.js +7 -0
- package/ts/chunks/chunk-M6CAJL36.js +1 -0
- package/ts/chunks/chunk-MPHTBN7E.js +1 -0
- package/ts/chunks/chunk-NYIFCLEG.js +1 -0
- package/ts/chunks/chunk-RRDWQKZY.js +1 -0
- package/ts/chunks/chunk-RVNSKPFL.js +1 -0
- package/ts/chunks/chunk-S5F2DAAG.js +5 -0
- package/ts/chunks/chunk-SCYP2G2T.js +3 -0
- package/ts/chunks/chunk-SWP6BJR6.js +147 -0
- package/{chunks/chunk-XDRX4ZBJ.js → ts/chunks/chunk-SWRVSRYY.js} +1 -1
- package/ts/chunks/chunk-T2X4E35X.js +1 -0
- package/ts/chunks/chunk-TDLTCTV4.js +1 -0
- package/ts/chunks/chunk-TKBGNLNV.js +1 -0
- package/ts/chunks/chunk-UY4YFVSW.js +3 -0
- package/ts/chunks/chunk-V5ZXCJPI.js +2 -0
- package/ts/chunks/chunk-W46BJM2F.js +1 -0
- package/ts/chunks/chunk-W7KQFMHV.js +1 -0
- package/ts/chunks/chunk-XGRZPTAD.js +24 -0
- package/ts/chunks/chunk-XTQFSF6C.js +1 -0
- package/ts/chunks/chunk-YN3SHWBR.js +1 -0
- package/ts/chunks/chunk-ZAY6LSJD.js +2 -0
- package/ts/chunks/chunk-ZGVXR3EC.js +8 -0
- package/ts/chunks/chunk-ZW5C5IGT.js +32 -0
- package/ts/chunks/claude-code-J2V5WSGZ.js +1 -0
- package/ts/chunks/concern-EDWQHU4H.js +1 -0
- package/ts/chunks/config-E7BDBHPK.js +1 -0
- package/ts/chunks/decision-ledger-5QXKZSV2.js +1 -0
- package/ts/chunks/delegate-LVQQ3GCV.js +1 -0
- package/ts/chunks/diagrams-2F5ZYXA7.js +1 -0
- package/ts/chunks/diagrams-H62JGTIS.js +1 -0
- package/ts/chunks/done-U3TOSZIX.js +1 -0
- package/ts/chunks/followup-J2HJU3ZT.js +1 -0
- package/ts/chunks/free-73WMLMCT.js +1 -0
- package/ts/chunks/gemini-GA6P4M7D.js +1 -0
- package/ts/chunks/init-6CVDGRY2.js +1 -0
- package/ts/chunks/invoke-hook-2TMKWL7I.js +15 -0
- package/ts/chunks/kiro-BJSKSAUC.js +1 -0
- package/ts/chunks/learn-7Q2VWZMI.js +7 -0
- package/ts/chunks/ledger-XR4AHZRX.js +2 -0
- package/ts/chunks/list-CUQCPXZH.js +1 -0
- package/ts/chunks/manager-WTLJ5C2I.js +3 -0
- package/ts/chunks/mod-BZA5TFW7.js +1 -0
- package/ts/chunks/mod-RWA5ZPYH.js +1 -0
- package/ts/chunks/mod-X372UNSQ.js +1 -0
- package/ts/chunks/mod-XVE4ZWPY.js +1 -0
- package/ts/chunks/next-CEYZSYGB.js +20 -0
- package/ts/chunks/node-33JV5VS3.js +15 -0
- package/ts/chunks/node-XYP2DQHR.js +74 -0
- package/ts/chunks/node-ZSGIX7K3.js +1 -0
- package/ts/chunks/ollama-X6OGN5BW.js +1 -0
- package/ts/chunks/openai-TV7KLQ2C.js +1 -0
- package/ts/chunks/openai-YPM2E7QS.js +30 -0
- package/ts/chunks/opencode-AK6WWZRF.js +1 -0
- package/ts/chunks/pack-EOUSZGJT.js +5 -0
- package/ts/chunks/plan-export-ZBINRAAS.js +3 -0
- package/ts/chunks/purge-GPMC5A6Y.js +5 -0
- package/ts/chunks/reopen-LPVNZN5I.js +1 -0
- package/ts/chunks/reset-RNLPXGWQ.js +1 -0
- package/ts/chunks/review-ZGAY5XCN.js +1 -0
- package/ts/chunks/rule-SNBQ4VZD.js +6 -0
- package/ts/chunks/run-4TDP4C7Z.js +3 -0
- package/ts/chunks/sdk-MEVPL5WT.js +1 -0
- package/ts/chunks/session-J7TSLNEH.js +1 -0
- package/ts/chunks/spec-3NSPFDIC.js +1 -0
- package/ts/chunks/status-DIEA2OGR.js +1 -0
- package/ts/chunks/sync-HZNKILSP.js +1 -0
- package/ts/chunks/validate-MWHDOF2F.js +1 -0
- package/ts/chunks/vertexai-ARXI4AMJ.js +1 -0
- package/ts/chunks/watch-P6HABMAS.js +7 -0
- package/ts/chunks/web-BMIC3VJQ.js +1 -0
- package/ts/chunks/wontfix-6UKEYTVB.js +1 -0
- package/ts/noskills.js +2 -0
- package/chunks/anthropic-TS7EMQML.js +0 -1
- package/chunks/approve-HEW3VFYH.js +0 -1
- package/chunks/ask-AXHTCVD6.js +0 -2
- package/chunks/block-VN76CXZW.js +0 -1
- package/chunks/browser-BGFD24RX.js +0 -1
- package/chunks/bun-WZ7BVR7Y.js +0 -1
- package/chunks/cancel-7WRAST62.js +0 -1
- package/chunks/chunk-3ZJ3UGQL.js +0 -48
- package/chunks/chunk-4PF2MT7S.js +0 -29
- package/chunks/chunk-575Y3OEG.js +0 -1
- package/chunks/chunk-5DZHAHXW.js +0 -110
- package/chunks/chunk-5PBNUBBY.js +0 -3
- package/chunks/chunk-5RLCKUIF.js +0 -2
- package/chunks/chunk-6YSS6PEL.js +0 -3
- package/chunks/chunk-7GC46XEU.js +0 -1
- package/chunks/chunk-7PPUGTKL.js +0 -4
- package/chunks/chunk-AUZWXMWA.js +0 -27
- package/chunks/chunk-CH6A3LES.js +0 -91
- package/chunks/chunk-CML74SNT.js +0 -3
- package/chunks/chunk-CTTMQSHF.js +0 -1
- package/chunks/chunk-DBKXMYLF.js +0 -4
- package/chunks/chunk-DEHRWREM.js +0 -1
- package/chunks/chunk-EIGFDYGQ.js +0 -1
- package/chunks/chunk-EIMBEXUJ.js +0 -1
- package/chunks/chunk-ENP4P2YH.js +0 -0
- package/chunks/chunk-FE4MKOI4.js +0 -1
- package/chunks/chunk-GQTHILPL.js +0 -5
- package/chunks/chunk-IFE5SYGK.js +0 -1
- package/chunks/chunk-IGDFEGCH.js +0 -2
- package/chunks/chunk-JL3MAFYQ.js +0 -1
- package/chunks/chunk-JYVB6UAV.js +0 -1
- package/chunks/chunk-KJLEPI7T.js +0 -1
- package/chunks/chunk-KMLNG3EC.js +0 -1
- package/chunks/chunk-KRKOWSYW.js +0 -148
- package/chunks/chunk-KRRPOVQG.js +0 -1
- package/chunks/chunk-LJEWPIEI.js +0 -1
- package/chunks/chunk-NGCBWJML.js +0 -2
- package/chunks/chunk-O4KKKYCH.js +0 -1
- package/chunks/chunk-PKEQKXZW.js +0 -23
- package/chunks/chunk-PRQ5CRIG.js +0 -1
- package/chunks/chunk-PSX63TYP.js +0 -2
- package/chunks/chunk-Q4TI7EYT.js +0 -5
- package/chunks/chunk-QKWJ72HI.js +0 -3
- package/chunks/chunk-RAQY37P6.js +0 -1
- package/chunks/chunk-S4MUTKHT.js +0 -4
- package/chunks/chunk-SLO22P65.js +0 -1
- package/chunks/chunk-UE56BMAW.js +0 -21
- package/chunks/chunk-VJRCTYGL.js +0 -1
- package/chunks/chunk-VXU6XZ66.js +0 -39
- package/chunks/chunk-W4TQLLUK.js +0 -7
- package/chunks/chunk-Y5E7ZCCX.js +0 -1
- package/chunks/chunk-Z7OYXH3J.js +0 -1
- package/chunks/claude-code-DIWRQKZA.js +0 -1
- package/chunks/cmd-46ZIHXLB.js +0 -1
- package/chunks/concern-QSENGU6C.js +0 -1
- package/chunks/config-S3UXTJN2.js +0 -1
- package/chunks/decision-ledger-GY2W6VWL.js +0 -1
- package/chunks/delegate-WKXIER7E.js +0 -1
- package/chunks/deno-YM5PW6ZM.js +0 -1
- package/chunks/diagrams-A7W2EBYV.js +0 -1
- package/chunks/diagrams-CBCUA47B.js +0 -1
- package/chunks/done-WR3UFYJT.js +0 -1
- package/chunks/followup-5EGZEF5Q.js +0 -1
- package/chunks/free-KJQHRYZA.js +0 -1
- package/chunks/gemini-IWP24T63.js +0 -1
- package/chunks/init-437SU6XH.js +0 -1
- package/chunks/invoke-hook-LMCWNF65.js +0 -13
- package/chunks/kiro-THWCXS5L.js +0 -1
- package/chunks/learn-ZTYKBZER.js +0 -7
- package/chunks/ledger-FOOPJ2UO.js +0 -1
- package/chunks/list-HNGIOVBK.js +0 -1
- package/chunks/loader-command-3A5FK2RF.js +0 -1
- package/chunks/loader-reactor-YZM7HO4G.js +0 -1
- package/chunks/manager-2MOLEJ4Q.js +0 -3
- package/chunks/mod-6EZYRKWV.js +0 -1
- package/chunks/mod-7VTKN6Q5.js +0 -1
- package/chunks/mod-7X5TKHKC.js +0 -1
- package/chunks/mod-AJIRKRAH.js +0 -1
- package/chunks/mod-SFSUQWSB.js +0 -8
- package/chunks/mod-TGOMO3CJ.js +0 -1
- package/chunks/next-Y6FOPM4Z.js +0 -15
- package/chunks/node-AZK2C657.js +0 -12
- package/chunks/node-GQQ42DT2.js +0 -68
- package/chunks/node-J4GTOSL2.js +0 -1
- package/chunks/ollama-2KAMCXVL.js +0 -1
- package/chunks/openai-HHE35TAX.js +0 -31
- package/chunks/openai-YES2XJDU.js +0 -1
- package/chunks/opencode-S4M7WJTO.js +0 -1
- package/chunks/pack-KUT53Z24.js +0 -5
- package/chunks/plan-export-PG2BVRQZ.js +0 -3
- package/chunks/purge-JGNJNEET.js +0 -4
- package/chunks/reopen-RPDXN3CF.js +0 -1
- package/chunks/reset-RBCQO2RF.js +0 -1
- package/chunks/review-VMS5MYOV.js +0 -1
- package/chunks/rule-IB4VKSBC.js +0 -6
- package/chunks/run-62PWXVII.js +0 -3
- package/chunks/sdk-FR7Z4YSC.js +0 -1
- package/chunks/session-Q43KMFL2.js +0 -1
- package/chunks/spec-4RKLPOEM.js +0 -1
- package/chunks/status-OGLFEFF7.js +0 -1
- package/chunks/sync-H35O5DN5.js +0 -1
- package/chunks/unstable_chmod-44MCKF3B.js +0 -1
- package/chunks/validate-JX7UTAK5.js +0 -1
- package/chunks/vertexai-WF5CKMYI.js +0 -1
- package/chunks/watch-SOZDHLSC.js +0 -8
- package/chunks/web-3VGRM3W4.js +0 -1
- package/chunks/wontfix-RBOGLLWJ.js +0 -1
- package/chunks/workerd-I7MLRCLJ.js +0 -1
- /package/{chunks → ts/chunks}/chunk-HISXAZ4Y.js +0 -0
- /package/{chunks → ts/chunks}/chunk-I4Z2RF7L.js +0 -0
- /package/{chunks → ts/chunks}/dist-3MH5UCQU.js +0 -0
- /package/{chunks → ts/chunks}/multipart-parser-DKDFOZKD.js +0 -0
- /package/{chunks → ts/chunks}/src-HXQVVTGQ.js +0 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import{a as K,c as V,e as Ct}from"./chunk-HISXAZ4Y.js";var yc=V((QD,_c)=>{function Qe(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}_c.exports=Qe;Qe.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Qe.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Qe.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0};Qe.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Qe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Qe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Qe.prototype.start=Qe.prototype.try;Qe.prototype.errors=function(){return this._errors};Qe.prototype.attempts=function(){return this._attempts};Qe.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],o=i.message,a=(t[o]||0)+1;t[o]=a,a>=n&&(e=i,n=a)}return e}});var vc=V(dn=>{var Zy=yc();dn.operation=function(t){var e=dn.timeouts(t);return new Zy(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};dn.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<e.retries;i++)r.push(this.createTimeout(i,e));return t&&t.forever&&!r.length&&r.push(this.createTimeout(i,e)),r.sort(function(o,a){return o-a}),r};dn.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,r=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return r=Math.min(r,e.maxTimeout),r};dn.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var r in t)typeof t[r]=="function"&&n.push(r)}for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(c){var d=dn.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){c.apply(t,f)})}.bind(t,a),t[o].options=e}}});var Tc=V((jD,Ec)=>{Ec.exports=vc()});var Ac=V((eb,Xr)=>{"use strict";var jy=Tc(),ev=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],$r=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},tv=(t,e,n)=>{let r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t},nv=t=>ev.includes(t),Cc=(t,e)=>new Promise((n,r)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=jy.operation(e);i.attempt(async o=>{try{n(await t(o))}catch(a){if(!(a instanceof Error)){r(new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`));return}if(a instanceof $r)i.stop(),r(a.originalError);else if(a instanceof TypeError&&!nv(a.message))i.stop(),r(a);else{tv(a,o,e);try{await e.onFailedAttempt(a)}catch(u){r(u);return}i.retry(a)||r(i.mainError())}}})});Xr.exports=Cc;Xr.exports.default=Cc;Xr.exports.AbortError=$r});var Ko=V((tb,Nc)=>{"use strict";var Jr=Object.prototype.hasOwnProperty,xc=Object.prototype.toString,Sc=Object.defineProperty,Ic=Object.getOwnPropertyDescriptor,wc=function(e){return typeof Array.isArray=="function"?Array.isArray(e):xc.call(e)==="[object Array]"},Rc=function(e){if(!e||xc.call(e)!=="[object Object]")return!1;var n=Jr.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Jr.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||Jr.call(e,i)},Pc=function(e,n){Sc&&n.name==="__proto__"?Sc(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},kc=function(e,n){if(n==="__proto__")if(Jr.call(e,n)){if(Ic)return Ic(e,n).value}else return;return e[n]};Nc.exports=function t(){var e,n,r,i,o,a,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)r=kc(u,n),i=kc(e,n),u!==i&&(f&&i&&(Rc(i)||(o=wc(i)))?(o?(o=!1,a=r&&wc(r)?r:[]):a=r&&Rc(r)?r:{},Pc(u,{name:n,newValue:t(f,a,i)})):typeof i<"u"&&Pc(u,{name:n,newValue:i}));return u}});var Dc=V((nb,rv)=>{rv.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 Mc=V((rb,bc)=>{"use strict";var iv=Dc();bc.exports={pkg:iv}});var Qo=V(Ze=>{"use strict";var Gc=Ze&&Ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GaxiosError=Ze.GAXIOS_ERROR_SYMBOL=void 0;Ze.defaultErrorRedactor=Oc;var Uc=Gc(Ko()),ov=Gc(Mc()),Yo=ov.default.pkg;Ze.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Yo.name}-gaxios-error`);var zo=class t extends Error{config;response;code;status;error;[Ze.GAXIOS_ERROR_SYMBOL]=Yo.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Ze.GAXIOS_ERROR_SYMBOL in e&&e[Ze.GAXIOS_ERROR_SYMBOL]===Yo.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,i){if(super(e,{cause:i}),this.config=n,this.response=r,this.error=i instanceof Error?i:void 0,this.config=(0,Uc.default)(!0,{},n),this.response&&(this.response.config=(0,Uc.default)(!0,{},this.response.config)),this.response){try{this.response.data=sv(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}i instanceof DOMException?this.code=i.name:i&&typeof i=="object"&&"code"in i&&(typeof i.code=="string"||typeof i.code=="number")&&(this.code=i.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;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 a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
|
|
2
|
+
`)||r,code:o,status:i},e.data.error)}return Object.assign({message:r,code:o,status:i},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Ze.GaxiosError=zo;function sv(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Oc(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(o){o&&o.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&o.set(u,e)})}function r(o,a){if(typeof o=="object"&&o!==null&&typeof o[a]=="string"){let u=o[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(o[a]=e)}}function i(o){!o||typeof o!="object"||(o instanceof FormData||o instanceof URLSearchParams||"forEach"in o&&"set"in o?o.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&o.set(u,e)}):("grant_type"in o&&(o.grant_type=e),"assertion"in o&&(o.assertion=e),"client_secret"in o&&(o.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),i(t.config.data),r(t.config,"body"),i(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Oc({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),i(t.response.data))),t}});var qc=V(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.getRetryConfig=av;async function av(t){let e=Lc(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||lv)(t))return{shouldRetry:!1,config:t.config};let i=uv(e);t.config.retryConfig.currentRetryAttempt+=1;let o=e.retryBackoff?e.retryBackoff(t,i):new Promise(a=>{setTimeout(a,i)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await o,{shouldRetry:!0,config:t.config}}function lv(t){let e=Lc(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,i]of e.statusCodesToRetry){let o=t.response.status;if(o>=r&&o<=i){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Lc(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function uv(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var es=V(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.GaxiosInterceptorManager=void 0;var jo=class extends Set{};Wr.GaxiosInterceptorManager=jo});var Hc=V(Sn=>{"use strict";var cv=Sn&&Sn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},An;Object.defineProperty(Sn,"__esModule",{value:!0});Sn.Gaxios=void 0;var dv=cv(Ko()),fv=K("https"),fn=Qo(),pv=qc(),Fc=K("stream"),Bc=es(),hv=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),mv=204,Kr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Bc.GaxiosInterceptorManager,response:new Bc.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],i,o=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&An.mergeHeaders(o,n.headers),r&&An.mergeHeaders(o,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:o,url:i}):this.request({...r,headers:o,url:i})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await An.#l(),r={...e};delete r.data;let i=await n(e.url,r),o=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}}),Object.assign(i,{config:e,data:o})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let i=[];for await(let o of n.data)i.push(o);n.data=Buffer.concat(i.map(o=>typeof o=="string"?Buffer.from(o):o)).toString("utf8")}let r=fn.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new fn.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof fn.GaxiosError?r=n:n instanceof Error?r=new fn.GaxiosError(n.message,e,void 0,n):r=new fn.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:i,config:o}=await(0,pv.getRetryConfig)(r);if(i&&o)return r.config.retryConfig.currentRetryAttempt=o.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===mv)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new fn.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),i=[...n],o=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of o)i.push(a.trim());for(let a of i)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(r.hostname.endsWith(u))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);An.mergeHeaders(n,e.headers);let r=(0,dv.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let u=r.url.toString().includes("?")?"&":"?";r.url=r.url+u+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[u,c]of new URLSearchParams(r.params))a.searchParams.append(u,c);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let i=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof Fc.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await hv();n.set("content-type",`multipart/related; boundary=${a}`),r.body=Fc.Readable.from(this.getMultipartRequest(r.multipart,a))}else i?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let o=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(o&&this.#e(r.url,r.noProxy)){let a=await An.#a();this.agentCache.has(o)?r.agent=this.agentCache.get(o):(r.agent=new a(o,{cert:r.cert,key:r.key}),this.agentCache.set(o,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new fv.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=fn.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#i(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#i(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let i of e){let o=i.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
|
|
3
|
+
Content-Type: ${o}\r
|
|
4
|
+
\r
|
|
5
|
+
`,typeof i.content=="string"?yield i.content:yield*i.content,yield`\r
|
|
6
|
+
`}yield r}static#o;static#s;static async#a(){return this.#o||=(await import("./dist-3MH5UCQU.js")).HttpsProxyAgent,this.#o}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("./src-HXQVVTGQ.js")).default,this.#s}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((o,a)=>{a==="set-cookie"?e.append(a,o):e.set(a,o)});return e}};Sn.Gaxios=Kr;An=Kr});var De=V(Le=>{"use strict";var gv=Le&&Le.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),_v=Le&&Le.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gv(e,t,n)};Object.defineProperty(Le,"__esModule",{value:!0});Le.instance=Le.Gaxios=Le.GaxiosError=void 0;Le.request=vv;var Vc=Hc();Object.defineProperty(Le,"Gaxios",{enumerable:!0,get:function(){return Vc.Gaxios}});var yv=Qo();Object.defineProperty(Le,"GaxiosError",{enumerable:!0,get:function(){return yv.GaxiosError}});_v(es(),Le);Le.instance=new Vc.Gaxios;async function vv(t){return Le.instance.request(t)}});var ts=V(($c,Yr)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,i=Math.floor,o="[BigNumber Error] ",a=o+"Number primitive has more than 15 significant digits: ",u=1e14,c=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(I){var k,O,B,D=$.prototype={constructor:$,toString:null,valueOf:null},q=new $(1),H=20,J=4,ne=-7,L=21,X=-1e7,Z=1e7,ge=!1,_e=1,pe=0,He={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ue="0123456789abcdefghijklmnopqrstuvwxyz",Ge=!0;function $(T,S){var w,M,P,N,G,R,x,U,b=this;if(!(b instanceof $))return new $(T,S);if(S==null){if(T&&T._isBigNumber===!0){b.s=T.s,!T.c||T.e>Z?b.c=b.e=null:T.e<X?b.c=[b.e=0]:(b.e=T.e,b.c=T.c.slice());return}if((R=typeof T=="number")&&T*0==0){if(b.s=1/T<0?(T=-T,-1):1,T===~~T){for(N=0,G=T;G>=10;G/=10,N++);N>Z?b.c=b.e=null:(b.e=N,b.c=[T]);return}U=String(T)}else{if(!n.test(U=String(T)))return B(b,U,R);b.s=U.charCodeAt(0)==45?(U=U.slice(1),-1):1}(N=U.indexOf("."))>-1&&(U=U.replace(".","")),(G=U.search(/e/i))>0?(N<0&&(N=G),N+=+U.slice(G+1),U=U.substring(0,G)):N<0&&(N=U.length)}else{if(y(S,2,Ue.length,"Base"),S==10&&Ge)return b=new $(T),Ye(b,H+b.e+1,J);if(U=String(T),R=typeof T=="number"){if(T*0!=0)return B(b,U,R,S);if(b.s=1/T<0?(U=U.slice(1),-1):1,$.DEBUG&&U.replace(/^0\.0*|\./,"").length>15)throw Error(a+T)}else b.s=U.charCodeAt(0)===45?(U=U.slice(1),-1):1;for(w=Ue.slice(0,S),N=G=0,x=U.length;G<x;G++)if(w.indexOf(M=U.charAt(G))<0){if(M=="."){if(G>N){N=x;continue}}else if(!P&&(U==U.toUpperCase()&&(U=U.toLowerCase())||U==U.toLowerCase()&&(U=U.toUpperCase()))){P=!0,G=-1,N=0;continue}return B(b,String(T),R,S)}R=!1,U=O(U,S,10,b.s),(N=U.indexOf("."))>-1?U=U.replace(".",""):N=U.length}for(G=0;U.charCodeAt(G)===48;G++);for(x=U.length;U.charCodeAt(--x)===48;);if(U=U.slice(G,++x)){if(x-=G,R&&$.DEBUG&&x>15&&(T>d||T!==i(T)))throw Error(a+b.s*T);if((N=N-G-1)>Z)b.c=b.e=null;else if(N<X)b.c=[b.e=0];else{if(b.e=N,b.c=[],G=(N+1)%c,N<0&&(G+=c),G<x){for(G&&b.c.push(+U.slice(0,G)),x-=c;G<x;)b.c.push(+U.slice(G,G+=c));G=c-(U=U.slice(G)).length}else G-=x;for(;G--;U+="0");b.c.push(+U)}}else b.c=[b.e=0]}$.clone=g,$.ROUND_UP=0,$.ROUND_DOWN=1,$.ROUND_CEIL=2,$.ROUND_FLOOR=3,$.ROUND_HALF_UP=4,$.ROUND_HALF_DOWN=5,$.ROUND_HALF_EVEN=6,$.ROUND_HALF_CEIL=7,$.ROUND_HALF_FLOOR=8,$.EUCLID=9,$.config=$.set=function(T){var S,w;if(T!=null)if(typeof T=="object"){if(T.hasOwnProperty(S="DECIMAL_PLACES")&&(w=T[S],y(w,0,h,S),H=w),T.hasOwnProperty(S="ROUNDING_MODE")&&(w=T[S],y(w,0,8,S),J=w),T.hasOwnProperty(S="EXPONENTIAL_AT")&&(w=T[S],w&&w.pop?(y(w[0],-h,0,S),y(w[1],0,h,S),ne=w[0],L=w[1]):(y(w,-h,h,S),ne=-(L=w<0?-w:w))),T.hasOwnProperty(S="RANGE"))if(w=T[S],w&&w.pop)y(w[0],-h,-1,S),y(w[1],1,h,S),X=w[0],Z=w[1];else if(y(w,-h,h,S),w)X=-(Z=w<0?-w:w);else throw Error(o+S+" cannot be zero: "+w);if(T.hasOwnProperty(S="CRYPTO"))if(w=T[S],w===!!w)if(w)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))ge=w;else throw ge=!w,Error(o+"crypto unavailable");else ge=w;else throw Error(o+S+" not true or false: "+w);if(T.hasOwnProperty(S="MODULO_MODE")&&(w=T[S],y(w,0,9,S),_e=w),T.hasOwnProperty(S="POW_PRECISION")&&(w=T[S],y(w,0,h,S),pe=w),T.hasOwnProperty(S="FORMAT"))if(w=T[S],typeof w=="object")He=w;else throw Error(o+S+" not an object: "+w);if(T.hasOwnProperty(S="ALPHABET"))if(w=T[S],typeof w=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(w))Ge=w.slice(0,10)=="0123456789",Ue=w;else throw Error(o+S+" invalid: "+w)}else throw Error(o+"Object expected: "+T);return{DECIMAL_PLACES:H,ROUNDING_MODE:J,EXPONENTIAL_AT:[ne,L],RANGE:[X,Z],CRYPTO:ge,MODULO_MODE:_e,POW_PRECISION:pe,FORMAT:He,ALPHABET:Ue}},$.isBigNumber=function(T){if(!T||T._isBigNumber!==!0)return!1;if(!$.DEBUG)return!0;var S,w,M=T.c,P=T.e,N=T.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&P>=-h&&P<=h&&P===i(P)){if(M[0]===0){if(P===0&&M.length===1)return!0;break e}if(S=(P+1)%c,S<1&&(S+=c),String(M[0]).length==S){for(S=0;S<M.length;S++)if(w=M[S],w<0||w>=u||w!==i(w))break e;if(w!==0)return!0}}}else if(M===null&&P===null&&(N===null||N===1||N===-1))return!0;throw Error(o+"Invalid BigNumber: "+T)},$.maximum=$.max=function(){return gc(arguments,-1)},$.minimum=$.min=function(){return gc(arguments,1)},$.random=(function(){var T=9007199254740992,S=Math.random()*T&2097151?function(){return i(Math.random()*T)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(w){var M,P,N,G,R,x=0,U=[],b=new $(q);if(w==null?w=H:y(w,0,h),G=r(w/c),ge)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(G*=2));x<G;)R=M[x]*131072+(M[x+1]>>>11),R>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),M[x]=P[0],M[x+1]=P[1]):(U.push(R%1e14),x+=2);x=G/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(G*=7);x<G;)R=(M[x]&31)*281474976710656+M[x+1]*1099511627776+M[x+2]*4294967296+M[x+3]*16777216+(M[x+4]<<16)+(M[x+5]<<8)+M[x+6],R>=9e15?crypto.randomBytes(7).copy(M,x):(U.push(R%1e14),x+=7);x=G/7}else throw ge=!1,Error(o+"crypto unavailable");if(!ge)for(;x<G;)R=S(),R<9e15&&(U[x++]=R%1e14);for(G=U[--x],w%=c,G&&w&&(R=f[c-w],U[x]=i(G/R)*R);U[x]===0;U.pop(),x--);if(x<0)U=[N=0];else{for(N=-1;U[0]===0;U.splice(0,1),N-=c);for(x=1,R=U[0];R>=10;R/=10,x++);x<c&&(N-=c-x)}return b.e=N,b.c=U,b}})(),$.sum=function(){for(var T=1,S=arguments,w=new $(S[0]);T<S.length;)w=w.plus(S[T++]);return w},O=(function(){var T="0123456789";function S(w,M,P,N){for(var G,R=[0],x,U=0,b=w.length;U<b;){for(x=R.length;x--;R[x]*=M);for(R[0]+=N.indexOf(w.charAt(U++)),G=0;G<R.length;G++)R[G]>P-1&&(R[G+1]==null&&(R[G+1]=0),R[G+1]+=R[G]/P|0,R[G]%=P)}return R.reverse()}return function(w,M,P,N,G){var R,x,U,b,F,j,ee,ve,we=w.indexOf("."),xe=H,ye=J;for(we>=0&&(b=pe,pe=0,w=w.replace(".",""),ve=new $(M),j=ve.pow(w.length-we),pe=b,ve.c=S(A(m(j.c),j.e,"0"),10,P,T),ve.e=ve.c.length),ee=S(w,M,P,G?(R=Ue,T):(R=T,Ue)),U=b=ee.length;ee[--b]==0;ee.pop());if(!ee[0])return R.charAt(0);if(we<0?--U:(j.c=ee,j.e=U,j.s=N,j=k(j,ve,xe,ye,P),ee=j.c,F=j.r,U=j.e),x=U+xe+1,we=ee[x],b=P/2,F=F||x<0||ee[x+1]!=null,F=ye<4?(we!=null||F)&&(ye==0||ye==(j.s<0?3:2)):we>b||we==b&&(ye==4||F||ye==6&&ee[x-1]&1||ye==(j.s<0?8:7)),x<1||!ee[0])w=F?A(R.charAt(1),-xe,R.charAt(0)):R.charAt(0);else{if(ee.length=x,F)for(--P;++ee[--x]>P;)ee[x]=0,x||(++U,ee=[1].concat(ee));for(b=ee.length;!ee[--b];);for(we=0,w="";we<=b;w+=R.charAt(ee[we++]));w=A(w,U,R.charAt(0))}return w}})(),k=(function(){function T(M,P,N){var G,R,x,U,b=0,F=M.length,j=P%p,ee=P/p|0;for(M=M.slice();F--;)x=M[F]%p,U=M[F]/p|0,G=ee*x+U*j,R=j*x+G%p*p+b,b=(R/N|0)+(G/p|0)+ee*U,M[F]=R%N;return b&&(M=[b].concat(M)),M}function S(M,P,N,G){var R,x;if(N!=G)x=N>G?1:-1;else for(R=x=0;R<N;R++)if(M[R]!=P[R]){x=M[R]>P[R]?1:-1;break}return x}function w(M,P,N,G){for(var R=0;N--;)M[N]-=R,R=M[N]<P[N]?1:0,M[N]=R*G+M[N]-P[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,P,N,G,R){var x,U,b,F,j,ee,ve,we,xe,ye,Te,be,Vr,Jo,Wo,Tt,ar,ze=M.s==P.s?1:-1,Oe=M.c,Re=P.c;if(!Oe||!Oe[0]||!Re||!Re[0])return new $(!M.s||!P.s||(Oe?Re&&Oe[0]==Re[0]:!Re)?NaN:Oe&&Oe[0]==0||!Re?ze*0:ze/0);for(we=new $(ze),xe=we.c=[],U=M.e-P.e,ze=N+U+1,R||(R=u,U=_(M.e/c)-_(P.e/c),ze=ze/c|0),b=0;Re[b]==(Oe[b]||0);b++);if(Re[b]>(Oe[b]||0)&&U--,ze<0)xe.push(1),F=!0;else{for(Jo=Oe.length,Tt=Re.length,b=0,ze+=2,j=i(R/(Re[0]+1)),j>1&&(Re=T(Re,j,R),Oe=T(Oe,j,R),Tt=Re.length,Jo=Oe.length),Vr=Tt,ye=Oe.slice(0,Tt),Te=ye.length;Te<Tt;ye[Te++]=0);ar=Re.slice(),ar=[0].concat(ar),Wo=Re[0],Re[1]>=R/2&&Wo++;do{if(j=0,x=S(Re,ye,Tt,Te),x<0){if(be=ye[0],Tt!=Te&&(be=be*R+(ye[1]||0)),j=i(be/Wo),j>1)for(j>=R&&(j=R-1),ee=T(Re,j,R),ve=ee.length,Te=ye.length;S(ee,ye,ve,Te)==1;)j--,w(ee,Tt<ve?ar:Re,ve,R),ve=ee.length,x=1;else j==0&&(x=j=1),ee=Re.slice(),ve=ee.length;if(ve<Te&&(ee=[0].concat(ee)),w(ye,ee,Te,R),Te=ye.length,x==-1)for(;S(Re,ye,Tt,Te)<1;)j++,w(ye,Tt<Te?ar:Re,Te,R),Te=ye.length}else x===0&&(j++,ye=[0]);xe[b++]=j,ye[0]?ye[Te++]=Oe[Vr]||0:(ye=[Oe[Vr]],Te=1)}while((Vr++<Jo||ye[0]!=null)&&ze--);F=ye[0]!=null,xe[0]||xe.splice(0,1)}if(R==u){for(b=1,ze=xe[0];ze>=10;ze/=10,b++);Ye(we,N+(we.e=b+U*c-1)+1,G,F)}else we.e=U,we.r=+F;return we}})();function $o(T,S,w,M){var P,N,G,R,x;if(w==null?w=J:y(w,0,8),!T.c)return T.toString();if(P=T.c[0],G=T.e,S==null)x=m(T.c),x=M==1||M==2&&(G<=ne||G>=L)?C(x,G):A(x,G,"0");else if(T=Ye(new $(T),S,w),N=T.e,x=m(T.c),R=x.length,M==1||M==2&&(S<=N||N<=ne)){for(;R<S;x+="0",R++);x=C(x,N)}else if(S-=G+(M===2&&N>G),x=A(x,N,"0"),N+1>R){if(--S>0)for(x+=".";S--;x+="0");}else if(S+=N-R,S>0)for(N+1==R&&(x+=".");S--;x+="0");return T.s<0&&P?"-"+x:x}function gc(T,S){for(var w,M,P=1,N=new $(T[0]);P<T.length;P++)M=new $(T[P]),(!M.s||(w=v(N,M))===S||w===0&&N.s===S)&&(N=M);return N}function Xo(T,S,w){for(var M=1,P=S.length;!S[--P];S.pop());for(P=S[0];P>=10;P/=10,M++);return(w=M+w*c-1)>Z?T.c=T.e=null:w<X?T.c=[T.e=0]:(T.e=w,T.c=S),T}B=(function(){var T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,w=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,G,R,x){var U,b=R?G:G.replace(P,"");if(M.test(b))N.s=isNaN(b)?null:b<0?-1:1;else{if(!R&&(b=b.replace(T,function(F,j,ee){return U=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!x||x==U?j:F}),x&&(U=x,b=b.replace(S,"$1").replace(w,"0.$1")),G!=b))return new $(b,U);if($.DEBUG)throw Error(o+"Not a"+(x?" base "+x:"")+" number: "+G);N.s=null}N.c=N.e=null}})();function Ye(T,S,w,M){var P,N,G,R,x,U,b,F=T.c,j=f;if(F){e:{for(P=1,R=F[0];R>=10;R/=10,P++);if(N=S-P,N<0)N+=c,G=S,x=F[U=0],b=i(x/j[P-G-1]%10);else if(U=r((N+1)/c),U>=F.length)if(M){for(;F.length<=U;F.push(0));x=b=0,P=1,N%=c,G=N-c+1}else break e;else{for(x=R=F[U],P=1;R>=10;R/=10,P++);N%=c,G=N-c+P,b=G<0?0:i(x/j[P-G-1]%10)}if(M=M||S<0||F[U+1]!=null||(G<0?x:x%j[P-G-1]),M=w<4?(b||M)&&(w==0||w==(T.s<0?3:2)):b>5||b==5&&(w==4||M||w==6&&(N>0?G>0?x/j[P-G]:0:F[U-1])%10&1||w==(T.s<0?8:7)),S<1||!F[0])return F.length=0,M?(S-=T.e+1,F[0]=j[(c-S%c)%c],T.e=-S||0):F[0]=T.e=0,T;if(N==0?(F.length=U,R=1,U--):(F.length=U+1,R=j[c-N],F[U]=G>0?i(x/j[P-G]%j[G])*R:0),M)for(;;)if(U==0){for(N=1,G=F[0];G>=10;G/=10,N++);for(G=F[0]+=R,R=1;G>=10;G/=10,R++);N!=R&&(T.e++,F[0]==u&&(F[0]=1));break}else{if(F[U]+=R,F[U]!=u)break;F[U--]=0,R=1}for(N=F.length;F[--N]===0;F.pop());}T.e>Z?T.c=T.e=null:T.e<X&&(T.c=[T.e=0])}return T}function Nt(T){var S,w=T.e;return w===null?T.toString():(S=m(T.c),S=w<=ne||w>=L?C(S,w):A(S,w,"0"),T.s<0?"-"+S:S)}return D.absoluteValue=D.abs=function(){var T=new $(this);return T.s<0&&(T.s=1),T},D.comparedTo=function(T,S){return v(this,new $(T,S))},D.decimalPlaces=D.dp=function(T,S){var w,M,P,N=this;if(T!=null)return y(T,0,h),S==null?S=J:y(S,0,8),Ye(new $(N),T+N.e+1,S);if(!(w=N.c))return null;if(M=((P=w.length-1)-_(this.e/c))*c,P=w[P])for(;P%10==0;P/=10,M--);return M<0&&(M=0),M},D.dividedBy=D.div=function(T,S){return k(this,new $(T,S),H,J)},D.dividedToIntegerBy=D.idiv=function(T,S){return k(this,new $(T,S),0,1)},D.exponentiatedBy=D.pow=function(T,S){var w,M,P,N,G,R,x,U,b,F=this;if(T=new $(T),T.c&&!T.isInteger())throw Error(o+"Exponent not an integer: "+Nt(T));if(S!=null&&(S=new $(S)),R=T.e>14,!F.c||!F.c[0]||F.c[0]==1&&!F.e&&F.c.length==1||!T.c||!T.c[0])return b=new $(Math.pow(+Nt(F),R?T.s*(2-E(T)):+Nt(T))),S?b.mod(S):b;if(x=T.s<0,S){if(S.c?!S.c[0]:!S.s)return new $(NaN);M=!x&&F.isInteger()&&S.isInteger(),M&&(F=F.mod(S))}else{if(T.e>9&&(F.e>0||F.e<-1||(F.e==0?F.c[0]>1||R&&F.c[1]>=24e7:F.c[0]<8e13||R&&F.c[0]<=9999975e7)))return N=F.s<0&&E(T)?-0:0,F.e>-1&&(N=1/N),new $(x?1/N:N);pe&&(N=r(pe/c+2))}for(R?(w=new $(.5),x&&(T.s=1),U=E(T)):(P=Math.abs(+Nt(T)),U=P%2),b=new $(q);;){if(U){if(b=b.times(F),!b.c)break;N?b.c.length>N&&(b.c.length=N):M&&(b=b.mod(S))}if(P){if(P=i(P/2),P===0)break;U=P%2}else if(T=T.times(w),Ye(T,T.e+1,1),T.e>14)U=E(T);else{if(P=+Nt(T),P===0)break;U=P%2}F=F.times(F),N?F.c&&F.c.length>N&&(F.c.length=N):M&&(F=F.mod(S))}return M?b:(x&&(b=q.div(b)),S?b.mod(S):N?Ye(b,pe,J,G):b)},D.integerValue=function(T){var S=new $(this);return T==null?T=J:y(T,0,8),Ye(S,S.e+1,T)},D.isEqualTo=D.eq=function(T,S){return v(this,new $(T,S))===0},D.isFinite=function(){return!!this.c},D.isGreaterThan=D.gt=function(T,S){return v(this,new $(T,S))>0},D.isGreaterThanOrEqualTo=D.gte=function(T,S){return(S=v(this,new $(T,S)))===1||S===0},D.isInteger=function(){return!!this.c&&_(this.e/c)>this.c.length-2},D.isLessThan=D.lt=function(T,S){return v(this,new $(T,S))<0},D.isLessThanOrEqualTo=D.lte=function(T,S){return(S=v(this,new $(T,S)))===-1||S===0},D.isNaN=function(){return!this.s},D.isNegative=function(){return this.s<0},D.isPositive=function(){return this.s>0},D.isZero=function(){return!!this.c&&this.c[0]==0},D.minus=function(T,S){var w,M,P,N,G=this,R=G.s;if(T=new $(T,S),S=T.s,!R||!S)return new $(NaN);if(R!=S)return T.s=-S,G.plus(T);var x=G.e/c,U=T.e/c,b=G.c,F=T.c;if(!x||!U){if(!b||!F)return b?(T.s=-S,T):new $(F?G:NaN);if(!b[0]||!F[0])return F[0]?(T.s=-S,T):new $(b[0]?G:J==3?-0:0)}if(x=_(x),U=_(U),b=b.slice(),R=x-U){for((N=R<0)?(R=-R,P=b):(U=x,P=F),P.reverse(),S=R;S--;P.push(0));P.reverse()}else for(M=(N=(R=b.length)<(S=F.length))?R:S,R=S=0;S<M;S++)if(b[S]!=F[S]){N=b[S]<F[S];break}if(N&&(P=b,b=F,F=P,T.s=-T.s),S=(M=F.length)-(w=b.length),S>0)for(;S--;b[w++]=0);for(S=u-1;M>R;){if(b[--M]<F[M]){for(w=M;w&&!b[--w];b[w]=S);--b[w],b[M]+=u}b[M]-=F[M]}for(;b[0]==0;b.splice(0,1),--U);return b[0]?Xo(T,b,U):(T.s=J==3?-1:1,T.c=[T.e=0],T)},D.modulo=D.mod=function(T,S){var w,M,P=this;return T=new $(T,S),!P.c||!T.s||T.c&&!T.c[0]?new $(NaN):!T.c||P.c&&!P.c[0]?new $(P):(_e==9?(M=T.s,T.s=1,w=k(P,T,0,3),T.s=M,w.s*=M):w=k(P,T,0,_e),T=P.minus(w.times(T)),!T.c[0]&&_e==1&&(T.s=P.s),T)},D.multipliedBy=D.times=function(T,S){var w,M,P,N,G,R,x,U,b,F,j,ee,ve,we,xe,ye=this,Te=ye.c,be=(T=new $(T,S)).c;if(!Te||!be||!Te[0]||!be[0])return!ye.s||!T.s||Te&&!Te[0]&&!be||be&&!be[0]&&!Te?T.c=T.e=T.s=null:(T.s*=ye.s,!Te||!be?T.c=T.e=null:(T.c=[0],T.e=0)),T;for(M=_(ye.e/c)+_(T.e/c),T.s*=ye.s,x=Te.length,F=be.length,x<F&&(ve=Te,Te=be,be=ve,P=x,x=F,F=P),P=x+F,ve=[];P--;ve.push(0));for(we=u,xe=p,P=F;--P>=0;){for(w=0,j=be[P]%xe,ee=be[P]/xe|0,G=x,N=P+G;N>P;)U=Te[--G]%xe,b=Te[G]/xe|0,R=ee*U+b*j,U=j*U+R%xe*xe+ve[N]+w,w=(U/we|0)+(R/xe|0)+ee*b,ve[N--]=U%we;ve[N]=w}return w?++M:ve.splice(0,1),Xo(T,ve,M)},D.negated=function(){var T=new $(this);return T.s=-T.s||null,T},D.plus=function(T,S){var w,M=this,P=M.s;if(T=new $(T,S),S=T.s,!P||!S)return new $(NaN);if(P!=S)return T.s=-S,M.minus(T);var N=M.e/c,G=T.e/c,R=M.c,x=T.c;if(!N||!G){if(!R||!x)return new $(P/0);if(!R[0]||!x[0])return x[0]?T:new $(R[0]?M:P*0)}if(N=_(N),G=_(G),R=R.slice(),P=N-G){for(P>0?(G=N,w=x):(P=-P,w=R),w.reverse();P--;w.push(0));w.reverse()}for(P=R.length,S=x.length,P-S<0&&(w=x,x=R,R=w,S=P),P=0;S;)P=(R[--S]=R[S]+x[S]+P)/u|0,R[S]=u===R[S]?0:R[S]%u;return P&&(R=[P].concat(R),++G),Xo(T,R,G)},D.precision=D.sd=function(T,S){var w,M,P,N=this;if(T!=null&&T!==!!T)return y(T,1,h),S==null?S=J:y(S,0,8),Ye(new $(N),T,S);if(!(w=N.c))return null;if(P=w.length-1,M=P*c+1,P=w[P]){for(;P%10==0;P/=10,M--);for(P=w[0];P>=10;P/=10,M++);}return T&&N.e+1>M&&(M=N.e+1),M},D.shiftedBy=function(T){return y(T,-d,d),this.times("1e"+T)},D.squareRoot=D.sqrt=function(){var T,S,w,M,P,N=this,G=N.c,R=N.s,x=N.e,U=H+4,b=new $("0.5");if(R!==1||!G||!G[0])return new $(!R||R<0&&(!G||G[0])?NaN:G?N:1/0);if(R=Math.sqrt(+Nt(N)),R==0||R==1/0?(S=m(G),(S.length+x)%2==0&&(S+="0"),R=Math.sqrt(+S),x=_((x+1)/2)-(x<0||x%2),R==1/0?S="5e"+x:(S=R.toExponential(),S=S.slice(0,S.indexOf("e")+1)+x),w=new $(S)):w=new $(R+""),w.c[0]){for(x=w.e,R=x+U,R<3&&(R=0);;)if(P=w,w=b.times(P.plus(k(N,P,U,1))),m(P.c).slice(0,R)===(S=m(w.c)).slice(0,R))if(w.e<x&&--R,S=S.slice(R-3,R+1),S=="9999"||!M&&S=="4999"){if(!M&&(Ye(P,P.e+H+2,0),P.times(P).eq(N))){w=P;break}U+=4,R+=4,M=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(Ye(w,w.e+H+2,1),T=!w.times(w).eq(N));break}}return Ye(w,w.e+H+1,J,T)},D.toExponential=function(T,S){return T!=null&&(y(T,0,h),T++),$o(this,T,S,1)},D.toFixed=function(T,S){return T!=null&&(y(T,0,h),T=T+this.e+1),$o(this,T,S)},D.toFormat=function(T,S,w){var M,P=this;if(w==null)T!=null&&S&&typeof S=="object"?(w=S,S=null):T&&typeof T=="object"?(w=T,T=S=null):w=He;else if(typeof w!="object")throw Error(o+"Argument not an object: "+w);if(M=P.toFixed(T,S),P.c){var N,G=M.split("."),R=+w.groupSize,x=+w.secondaryGroupSize,U=w.groupSeparator||"",b=G[0],F=G[1],j=P.s<0,ee=j?b.slice(1):b,ve=ee.length;if(x&&(N=R,R=x,x=N,ve-=N),R>0&&ve>0){for(N=ve%R||R,b=ee.substr(0,N);N<ve;N+=R)b+=U+ee.substr(N,R);x>0&&(b+=U+ee.slice(N)),j&&(b="-"+b)}M=F?b+(w.decimalSeparator||"")+((x=+w.fractionGroupSize)?F.replace(new RegExp("\\d{"+x+"}\\B","g"),"$&"+(w.fractionGroupSeparator||"")):F):b}return(w.prefix||"")+M+(w.suffix||"")},D.toFraction=function(T){var S,w,M,P,N,G,R,x,U,b,F,j,ee=this,ve=ee.c;if(T!=null&&(R=new $(T),!R.isInteger()&&(R.c||R.s!==1)||R.lt(q)))throw Error(o+"Argument "+(R.isInteger()?"out of range: ":"not an integer: ")+Nt(R));if(!ve)return new $(ee);for(S=new $(q),U=w=new $(q),M=x=new $(q),j=m(ve),N=S.e=j.length-ee.e-1,S.c[0]=f[(G=N%c)<0?c+G:G],T=!T||R.comparedTo(S)>0?N>0?S:U:R,G=Z,Z=1/0,R=new $(j),x.c[0]=0;b=k(R,S,0,1),P=w.plus(b.times(M)),P.comparedTo(T)!=1;)w=M,M=P,U=x.plus(b.times(P=U)),x=P,S=R.minus(b.times(P=S)),R=P;return P=k(T.minus(w),M,0,1),x=x.plus(P.times(U)),w=w.plus(P.times(M)),x.s=U.s=ee.s,N=N*2,F=k(U,M,N,J).minus(ee).abs().comparedTo(k(x,w,N,J).minus(ee).abs())<1?[U,M]:[x,w],Z=G,F},D.toNumber=function(){return+Nt(this)},D.toPrecision=function(T,S){return T!=null&&y(T,1,h),$o(this,T,S,2)},D.toString=function(T){var S,w=this,M=w.s,P=w.e;return P===null?M?(S="Infinity",M<0&&(S="-"+S)):S="NaN":(T==null?S=P<=ne||P>=L?C(m(w.c),P):A(m(w.c),P,"0"):T===10&&Ge?(w=Ye(new $(w),H+P+1,J),S=A(m(w.c),w.e,"0")):(y(T,2,Ue.length,"Base"),S=O(A(m(w.c),P,"0"),10,T,M,!0)),M<0&&w.c[0]&&(S="-"+S)),S},D.valueOf=D.toJSON=function(){return Nt(this)},D._isBigNumber=!0,I!=null&&$.set(I),$}function _(I){var k=I|0;return I>0||I===k?k:k-1}function m(I){for(var k,O,B=1,D=I.length,q=I[0]+"";B<D;){for(k=I[B++]+"",O=c-k.length;O--;k="0"+k);q+=k}for(D=q.length;q.charCodeAt(--D)===48;);return q.slice(0,D+1||1)}function v(I,k){var O,B,D=I.c,q=k.c,H=I.s,J=k.s,ne=I.e,L=k.e;if(!H||!J)return null;if(O=D&&!D[0],B=q&&!q[0],O||B)return O?B?0:-J:H;if(H!=J)return H;if(O=H<0,B=ne==L,!D||!q)return B?0:!D^O?1:-1;if(!B)return ne>L^O?1:-1;for(J=(ne=D.length)<(L=q.length)?ne:L,H=0;H<J;H++)if(D[H]!=q[H])return D[H]>q[H]^O?1:-1;return ne==L?0:ne>L^O?1:-1}function y(I,k,O,B){if(I<k||I>O||I!==i(I))throw Error(o+(B||"Argument")+(typeof I=="number"?I<k||I>O?" out of range: ":" not an integer: ":" not a primitive number: ")+String(I))}function E(I){var k=I.c.length-1;return _(I.e/c)==k&&I.c[k]%2!=0}function C(I,k){return(I.length>1?I.charAt(0)+"."+I.slice(1):I)+(k<0?"e":"e+")+k}function A(I,k,O){var B,D;if(k<0){for(D=O+".";++k;D+=O);I=D+I}else if(B=I.length,++k>B){for(D=O,k-=B;--k;D+=O);I+=D}else k<B&&(I=I.slice(0,k)+"."+I.slice(k));return I}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Yr<"u"&&Yr.exports?Yr.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})($c)});var Kc=V((ub,Wc)=>{var Xc=ts(),Jc=Wc.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,i,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=o[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,g,_,m=r,v,y=f[d],E=y!=null&&(y instanceof Xc||Xc.isBigNumber(y));switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(d)),typeof a=="function"&&(y=a.call(f,d,y)),typeof y){case"string":return E?y:u(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":case"bigint":return String(y);case"object":if(!y)return"null";if(r+=i,v=[],Object.prototype.toString.apply(y)==="[object Array]"){for(_=y.length,p=0;p<_;p+=1)v[p]=c(p,y)||"null";return g=v.length===0?"[]":r?`[
|
|
7
|
+
`+r+v.join(`,
|
|
8
|
+
`+r)+`
|
|
9
|
+
`+m+"]":"["+v.join(",")+"]",r=m,g}if(a&&typeof a=="object")for(_=a.length,p=0;p<_;p+=1)typeof a[p]=="string"&&(h=a[p],g=c(h,y),g&&v.push(u(h)+(r?": ":":")+g));else Object.keys(y).forEach(function(C){var A=c(C,y);A&&v.push(u(C)+(r?": ":":")+A)});return g=v.length===0?"{}":r?`{
|
|
10
|
+
`+r+v.join(`,
|
|
11
|
+
`+r)+`
|
|
12
|
+
`+m+"}":"{"+v.join(",")+"}",r=m,g}}typeof Jc.stringify!="function"&&(Jc.stringify=function(d,f,p){var h;if(r="",i="",typeof p=="number")for(h=0;h<p;h+=1)i+=" ";else typeof p=="string"&&(i=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return c("",{"":d})})})()});var zc=V((cb,Yc)=>{var zr=null,Ev=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Tv=/(?: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)/,Cv=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
13
|
+
`,r:"\r",t:" "},o,a=function(m){throw{name:"SyntaxError",message:m,at:n,text:o}},u=function(m){return m&&m!==r&&a("Expected '"+m+"' instead of '"+r+"'"),r=o.charAt(n),n+=1,r},c=function(){var m,v="";for(r==="-"&&(v="-",u("-"));r>="0"&&r<="9";)v+=r,u();if(r===".")for(v+=".";u()&&r>="0"&&r<="9";)v+=r;if(r==="e"||r==="E")for(v+=r,u(),(r==="-"||r==="+")&&(v+=r,u());r>="0"&&r<="9";)v+=r,u();if(m=+v,!isFinite(m))a("Bad number");else return zr==null&&(zr=ts()),v.length>15?e.storeAsString?v:e.useNativeBigInt?BigInt(v):new zr(v):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new zr(m):m},d=function(){var m,v,y="",E;if(r==='"')for(var C=n;u();){if(r==='"')return n-1>C&&(y+=o.substring(C,n-1)),u(),y;if(r==="\\"){if(n-1>C&&(y+=o.substring(C,n-1)),u(),r==="u"){for(E=0,v=0;v<4&&(m=parseInt(u(),16),!!isFinite(m));v+=1)E=E*16+m;y+=String.fromCharCode(E)}else if(typeof i[r]=="string")y+=i[r];else break;C=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)u()},p=function(){switch(r){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+r+"'")},h,g=function(){var m=[];if(r==="["){if(u("["),f(),r==="]")return u("]"),m;for(;r;){if(m.push(h()),f(),r==="]")return u("]"),m;u(","),f()}}a("Bad array")},_=function(){var m,v=Object.create(null);if(r==="{"){if(u("{"),f(),r==="}")return u("}"),v;for(;r;){if(m=d(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(v,m)&&a('Duplicate key "'+m+'"'),Ev.test(m)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():v[m]=h():Tv.test(m)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():v[m]=h():v[m]=h(),f(),r==="}")return u("}"),v;u(","),f()}}a("Bad object")};return h=function(){switch(f(),r){case"{":return _();case"[":return g();case'"':return d();case"-":return c();default:return r>="0"&&r<="9"?c():p()}},function(m,v){var y;return o=m+"",n=0,r=" ",y=h(),f(),r&&a("Syntax error"),typeof v=="function"?(function E(C,A){var I,k,O=C[A];return O&&typeof O=="object"&&Object.keys(O).forEach(function(B){k=E(O,B),k!==void 0?O[B]=k:delete O[B]}),v.call(C,A,O)})({"":y},""):y}};Yc.exports=Cv});var jc=V((db,Qr)=>{var Qc=Kc().stringify,Zc=zc();Qr.exports=function(t){return{parse:Zc(t),stringify:Qc}};Qr.exports.parse=Zc();Qr.exports.stringify=Qc});var ns=V(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.GCE_LINUX_BIOS_PATHS=void 0;dt.isGoogleCloudServerless=nd;dt.isGoogleComputeEngineLinux=rd;dt.isGoogleComputeEngineMACAddress=id;dt.isGoogleComputeEngine=od;dt.detectGCPResidency=Sv;var ed=K("fs"),td=K("os");dt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Av=/^42:01/;function nd(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function rd(){if((0,td.platform)()!=="linux")return!1;try{(0,ed.statSync)(dt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,ed.readFileSync)(dt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function id(){let t=(0,td.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(Av.test(n))return!0}return!1}function od(){return rd()||id()}function Sv(){return nd()||od()}});var sd=V(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.Colours=void 0;var Me=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Zr.Colours=Me;Me.enabled=!1;Me.reset="";Me.bright="";Me.dim="";Me.red="";Me.green="";Me.yellow="";Me.blue="";Me.magenta="";Me.cyan="";Me.white="";Me.grey="";Me.refresh()});var cd=V(Ce=>{"use strict";var Iv=Ce&&Ce.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wv=Ce&&Ce.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ad=Ce&&Ce.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&Iv(n,e,r[i]);return wv(n,e),n}})();Object.defineProperty(Ce,"__esModule",{value:!0});Ce.env=Ce.DebugLogBackendBase=Ce.placeholder=Ce.AdhocDebugLogger=Ce.LogSeverity=void 0;Ce.getNodeBackend=is;Ce.getDebugBackend=Pv;Ce.getStructuredBackend=kv;Ce.setBackend=xv;Ce.log=ud;var Rv=K("events"),lr=ad(K("process")),ld=ad(K("util")),Ve=sd(),ft;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(ft||(Ce.LogSeverity=ft={}));var ur=class extends Rv.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,i)=>this.on(r,i)}),this.func.debug=(...r)=>this.invokeSeverity(ft.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(ft.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(ft.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(ft.ERROR,...r),this.func.sublog=r=>ud(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Ce.AdhocDebugLogger=ur;Ce.placeholder=new ur("",()=>{}).func;var In=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=lr.env[Ce.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let i=this.cached.get(e);i||(i=this.makeLogger(e),this.cached.set(e,i)),i(n,...r)}catch(i){console.error(i)}}};Ce.DebugLogBackendBase=In;var rs=class extends In{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var i;let o=`${Ve.Colours.green}${e}${Ve.Colours.reset}`,a=`${Ve.Colours.yellow}${lr.pid}${Ve.Colours.reset}`,u;switch(n.severity){case ft.ERROR:u=`${Ve.Colours.red}${n.severity}${Ve.Colours.reset}`;break;case ft.INFO:u=`${Ve.Colours.magenta}${n.severity}${Ve.Colours.reset}`;break;case ft.WARNING:u=`${Ve.Colours.yellow}${n.severity}${Ve.Colours.reset}`;break;default:u=(i=n.severity)!==null&&i!==void 0?i:ft.DEFAULT;break}let c=ld.formatWithOptions({colors:Ve.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${Ve.Colours.grey}${f}${Ve.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,o,u,c,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function is(){return new rs}var os=class extends In{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...i)=>{n(i[0],...i.slice(1))}}setFilters(){var e;let n=(e=lr.env.NODE_DEBUG)!==null&&e!==void 0?e:"";lr.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function Pv(t){return new os(t)}var ss=class extends In{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(i,...o)=>{var a;let u=(a=i.severity)!==null&&a!==void 0?a:ft.INFO,c=Object.assign({severity:u,message:ld.format(...o)},i),d=JSON.stringify(c);r?r(i,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function kv(t){return new ss(t)}Ce.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var as=new Map,$e;function xv(t){$e=t,as.clear()}function ud(t,e){if(!$e&&!lr.env[Ce.env.nodeEnables]||!t)return Ce.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=as.get(t);if(n)return n.func;if($e===null)return Ce.placeholder;$e===void 0&&($e=is());let r=(()=>{let i;return new ur(t,(a,...u)=>{if(i!==$e){if($e===null)return;$e===void 0&&($e=is()),i=$e}$e?.log(t,a,...u)})})();return as.set(t,r),r.func}});var ls=V(pn=>{"use strict";var Nv=pn&&pn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Dv=pn&&pn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Nv(e,t,n)};Object.defineProperty(pn,"__esModule",{value:!0});Dv(cd(),pn)});var dr=V(te=>{"use strict";var fd=te&&te.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bv=te&&te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Mv=te&&te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&fd(n,e,r[i]);return bv(n,e),n}})(),Uv=te&&te.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&fd(e,t,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=Bv;te.project=Hv;te.universe=Vv;te.bulk=$v;te.isAvailable=Jv;te.resetIsAvailableCache=Wv;te.getGCPResidency=ds;te.setGCPResidency=pd;te.requestTimeout=hd;var us=De(),Gv=jc(),Ov=ns(),Lv=Mv(ls());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 dd=Lv.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 cs(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||te.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(te.BASE_PATH,t).href}function qv(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function cr(t,e={},n=3,r=!1){let i=new Headers(te.HEADERS),o="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>i.set(g,h)),o=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else o=t;typeof e=="string"?o+=`/${e}`:(qv(e),e.property&&(o+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>i.set(h,p)),a=e.params||a);let u=r?Fv:us.request,c={url:`${cs()}/${o}`,headers:i,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:hd()};dd.info("instance request %j",c);let d=await u(c);dd.info("instance metadata is %s",d.data);let f=d.headers.get(te.HEADER_NAME);if(f!==te.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${te.HEADER_NAME} header. Expected '${te.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return Gv.parse(d.data)}catch{}return d.data}async function Fv(t){let e={...t,url:t.url?.toString().replace(cs(),cs(te.SECONDARY_HOST_ADDRESS))},n=(0,us.request)(t),r=(0,us.request)(e);return Promise.any([n,r])}function Bv(t){return cr("instance",t)}function Hv(t){return cr("project",t)}function Vv(t){return cr("universe",t)}async function $v(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await cr(n),i=n.metadataKey;e[i]=r})())),e}function Xv(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var jr;async function Jv(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in te.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(te.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return ds();case"ping-only":}}try{return jr===void 0&&(jr=cr("instance",void 0,Xv(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await jr,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Wv(){jr=void 0}te.gcpResidencyCache=null;function ds(){return te.gcpResidencyCache===null&&pd(),te.gcpResidencyCache}function pd(t=null){te.gcpResidencyCache=t!==null?t:(0,Ov.detectGCPResidency)()}function hd(){return ds()?0:3e3}Uv(ns(),te)});var _d=V(ei=>{"use strict";ei.byteLength=Yv;ei.toByteArray=Qv;ei.fromByteArray=eE;var At=[],je=[],Kv=typeof Uint8Array<"u"?Uint8Array:Array,fs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hn=0,md=fs.length;hn<md;++hn)At[hn]=fs[hn],je[fs.charCodeAt(hn)]=hn;var hn,md;je[45]=62;je[95]=63;function gd(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Yv(t){var e=gd(t),n=e[0],r=e[1];return(n+r)*3/4-r}function zv(t,e,n){return(e+n)*3/4-n}function Qv(t){var e,n=gd(t),r=n[0],i=n[1],o=new Kv(zv(t,r,i)),a=0,u=i>0?r-4:r,c;for(c=0;c<u;c+=4)e=je[t.charCodeAt(c)]<<18|je[t.charCodeAt(c+1)]<<12|je[t.charCodeAt(c+2)]<<6|je[t.charCodeAt(c+3)],o[a++]=e>>16&255,o[a++]=e>>8&255,o[a++]=e&255;return i===2&&(e=je[t.charCodeAt(c)]<<2|je[t.charCodeAt(c+1)]>>4,o[a++]=e&255),i===1&&(e=je[t.charCodeAt(c)]<<10|je[t.charCodeAt(c+1)]<<4|je[t.charCodeAt(c+2)]>>2,o[a++]=e>>8&255,o[a++]=e&255),o}function Zv(t){return At[t>>18&63]+At[t>>12&63]+At[t>>6&63]+At[t&63]}function jv(t,e,n){for(var r,i=[],o=e;o<n;o+=3)r=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(Zv(r));return i.join("")}function eE(t){for(var e,n=t.length,r=n%3,i=[],o=16383,a=0,u=n-r;a<u;a+=o)i.push(jv(t,a,a+o>u?u:a+o));return r===1?(e=t[n-1],i.push(At[e>>2]+At[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(At[e>>10]+At[e>>4&63]+At[e<<2&63]+"=")),i.join("")}});var hs=V(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.fromArrayBufferToHex=tE;function tE(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var yd=V(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.BrowserCrypto=void 0;var wn=_d(),nE=hs(),ms=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return wn.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),wn.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),a=wn.toByteArray(t.padBase64(r)),u=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,u,Buffer.from(a),o)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(n),o=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,o,i);return wn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=wn.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return wn.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,nE.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,o=await window.crypto.subtle.importKey("raw",i.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",o,i.encode(n))}};ti.BrowserCrypto=ms});var vd=V(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.NodeCrypto=void 0;var Rn=K("crypto"),gs=class{async sha256DigestBase64(e){return Rn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Rn.randomBytes(e).toString("base64")}async verify(e,n,r){let i=Rn.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,r,"base64")}async sign(e,n){let r=Rn.createSign("RSA-SHA256");return r.update(n),r.end(),r.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 Rn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:iE(e);return rE(Rn.createHmac("sha256",r).update(n).digest())}};ni.NodeCrypto=gs;function rE(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0;r<t.length;++r)n[r]=t[r];return e}function iE(t){return Buffer.from(t)}});var fr=V(Dt=>{"use strict";var oE=Dt&&Dt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sE=Dt&&Dt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&oE(e,t,n)};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.createCrypto=uE;Dt.hasBrowserCrypto=Ed;var aE=yd(),lE=vd();sE(hs(),Dt);function uE(){return Ed()?new aE.BrowserCrypto:new lE.NodeCrypto}function Ed(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Pn=V((_s,Cd)=>{var ri=K("buffer"),St=ri.Buffer;function Td(t,e){for(var n in t)e[n]=t[n]}St.from&&St.alloc&&St.allocUnsafe&&St.allocUnsafeSlow?Cd.exports=ri:(Td(ri,_s),_s.Buffer=mn);function mn(t,e,n){return St(t,e,n)}mn.prototype=Object.create(St.prototype);Td(St,mn);mn.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return St(t,e,n)};mn.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=St(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};mn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return St(t)};mn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ri.SlowBuffer(t)}});var Sd=V((Cb,Ad)=>{"use strict";function ys(t){var e=(t/8|0)+(t%8===0?0:1);return e}var cE={ES256:ys(256),ES384:ys(384),ES512:ys(521)};function dE(t){var e=cE[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Ad.exports=dE});var vs=V((Ab,xd)=>{"use strict";var ii=Pn().Buffer,wd=Sd(),oi=128,Rd=0,fE=32,pE=16,hE=2,Pd=pE|fE|Rd<<6,si=hE|Rd<<6;function mE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function kd(t){if(ii.isBuffer(t))return t;if(typeof t=="string")return ii.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function gE(t,e){t=kd(t);var n=wd(e),r=n+1,i=t.length,o=0;if(t[o++]!==Pd)throw new Error('Could not find expected "seq"');var a=t[o++];if(a===(oi|1)&&(a=t[o++]),i-o<a)throw new Error('"seq" specified length of "'+a+'", only "'+(i-o)+'" remaining');if(t[o++]!==si)throw new Error('Could not find expected "int" for "r"');var u=t[o++];if(i-o-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(i-o-2)+'" available');if(r<u)throw new Error('"r" specified length of "'+u+'", max of "'+r+'" is acceptable');var c=o;if(o+=u,t[o++]!==si)throw new Error('Could not find expected "int" for "s"');var d=t[o++];if(i-o!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(i-o)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=o;if(o+=d,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var p=n-u,h=n-d,g=ii.allocUnsafe(p+u+h+d);for(o=0;o<p;++o)g[o]=0;t.copy(g,o,c+Math.max(-p,0),c+u),o=n;for(var _=o;o<_+h;++o)g[o]=0;return t.copy(g,o,f+Math.max(-h,0),f+d),g=g.toString("base64"),g=mE(g),g}function Id(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var i=t[e+r]>=oi;return i&&--r,r}function _E(t,e){t=kd(t);var n=wd(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var i=Id(t,0,n),o=Id(t,n,t.length),a=n-i,u=n-o,c=2+a+1+1+u,d=c<oi,f=ii.allocUnsafe((d?2:3)+c),p=0;return f[p++]=Pd,d?f[p++]=c:(f[p++]=oi|1,f[p++]=c&255),f[p++]=si,f[p++]=a,i<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,i,n),f[p++]=si,f[p++]=u,o<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+o),f}xd.exports={derToJose:gE,joseToDer:_E}});var pt=V(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.LRUCache=void 0;bt.snakeToCamel=Dd;bt.originalOrCamelOptions=TE;bt.removeUndefinedValuesInObject=CE;bt.isValidFile=AE;bt.getWellKnownCertificateConfigFileLocation=SE;var yE=K("fs"),vE=K("os"),Es=K("path"),EE="certificate_config.json",Nd="gcloud";function Dd(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function TE(t){function e(n){let r=t||{};return r[n]??r[Dd(n)]}return{get:e}}var Ts=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};bt.LRUCache=Ts;function CE(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function AE(t){try{return(await yE.promises.lstat(t)).isFile()}catch{return!1}}function SE(){let t=process.env.CLOUDSDK_CONFIG||(IE()?Es.join(process.env.APPDATA||"",Nd):Es.join(process.env.HOME||"",".config",Nd));return Es.join(t,EE)}function IE(){return vE.platform().startsWith("win")}});var bd=V((Ib,wE)=>{wE.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 Cs=V(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.USER_AGENT=Jt.PRODUCT_NAME=Jt.pkg=void 0;var Md=bd();Jt.pkg=Md;var Ud="google-api-nodejs-client";Jt.PRODUCT_NAME=Ud;var RE=`${Ud}/${Md.version}`;Jt.USER_AGENT=RE});var Xe=V(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.AuthClient=ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=ht.DEFAULT_UNIVERSE=void 0;var PE=K("events"),As=De(),kE=pt(),xE=ls(),Ss=Cs();ht.DEFAULT_UNIVERSE="googleapis.com";ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Is=class t extends PE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=ht.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,kE.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??ht.DEFAULT_UNIVERSE,this.transporter=e.transporter??new As.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],i,o=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&As.Gaxios.mergeHeaders(o,n.headers),r&&As.Gaxios.mergeHeaders(o,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:o,url:i}):this.request({...r,headers:o,url:i})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),i=n.get("authorization");return r&&e.set("x-goog-user-project",r),i&&e.set("authorization",i),e}static log=(0,xE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${Ss.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Ss.USER_AGENT}`):e.headers.set("User-Agent",Ss.USER_AGENT);try{let r=e,i=r[t.RequestMethodNameSymbol],o=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=o;let a={url:e.url,headers:e.headers};i?t.log.info("%s [%s] request %j",i,o,a):t.log.info("[%s] request %j",o,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,i,e.data):t.log.info("[%s] response %j",i,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,i,e.response?.data):t.log.error("[%s] error %j",i,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};ht.AuthClient=Is});var Rs=V(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.LoginTicket=void 0;var ws=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};ai.LoginTicket=ws});var Wt=V(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.OAuth2Client=It.ClientAuthentication=It.CertificateFormat=It.CodeChallengeMethod=void 0;var Gd=De(),NE=K("querystring"),DE=K("stream"),bE=vs(),Od=pt(),Ps=fr(),kn=Xe(),ME=Rs(),Ld;(function(t){t.Plain="plain",t.S256="S256"})(Ld||(It.CodeChallengeMethod=Ld={}));var Mt;(function(t){t.PEM="PEM",t.JWK="JWK"})(Mt||(It.CertificateFormat=Mt={}));var pr;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(pr||(It.ClientAuthentication=pr={}));var ks=class t extends kn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Mt.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),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||pr.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+NE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Ps.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),o=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:o}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(i=>n(null,i.tokens,i.res),i=>n(i,null,i.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=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===pr.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===pr.ClientSecretPost&&(i.client_secret=this._clientSecret);let o={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Od.removeUndefinedValuesInObject)(i)),headers:r};kn.AuthClient.setMethodName(o,"getTokenAsync");let a=await this.transporter.request(o),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},i;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Od.removeUndefinedValuesInObject)(r))};kn.AuthClient.setMethodName(a,"refreshTokenNoCache"),i=await this.transporter.request(a)}catch(a){throw a instanceof Gd.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let o=i.data;return i.data&&i.data.expires_in&&(o.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete o.expires_in),this.emit("tokens",o),{tokens:o,res:i}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);let c=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(c)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,i=null;try{r=await this.refreshToken(n.refresh_token),i=r.tokens}catch(u){let c=u;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let o=this.credentials;o.token_type=o.token_type||"Bearer",i.refresh_token=o.refresh_token,this.credentials=i;let a=new Headers({authorization:o.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(kn.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(i=>n(null,i),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=Gd.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let i=r.response;if(i){let o=i.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=i.config.data instanceof DE.Readable,d=o===401||o===403;if(!n&&d&&!c&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!c&&u){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Ps.hasBrowserCrypto)()?Mt.JWK:Mt.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case Mt.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Mt.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:i};kn.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let o=r?.headers.get("cache-control"),a=-1;if(o){let d=/max-age=(?<maxAge>[0-9]+)/.exec(o)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let u={};switch(n){case Mt.PEM:u=r.data;break;case Mt.JWK:for(let d of r.data.keys)u[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=a===-1?null:new Date(c.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};kn.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,i,o){let a=(0,Ps.createCrypto)();o||(o=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=u[0]+"."+u[1],d=u[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token envelope: ${u[0]}': ${C.message}`),C}if(!f)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token payload '${u[0]}`),C}if(!p)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=bE.joseToDer(d,"ES256").toString("base64")),!await a.verify(h,c,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let _=Number(p.iat);if(isNaN(_))throw new Error("iat field using invalid format");let m=Number(p.exp);if(isNaN(m))throw new Error("exp field using invalid format");let v=new Date().getTime()/1e3;if(m>=v+o)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let y=_-t.CLOCK_SKEW_SECS_,E=m+t.CLOCK_SKEW_SECS_;if(v<y)throw new Error("Token used too early, "+v+" < "+y+": "+JSON.stringify(p));if(v>E)throw new Error("Token used too late, "+v+" > "+E+": "+JSON.stringify(p));if(i&&i.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let C=p.aud,A=!1;if(r.constructor===Array?A=r.indexOf(C)>-1:A=C===r,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new ME.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};It.OAuth2Client=ks});var Ns=V(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.Compute=void 0;var UE=De(),qd=dr(),GE=Wt(),xs=class extends GE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let i={property:e};this.scopes.length>0&&(i.params={scopes:this.scopes.join(",")}),n=await qd.instance(i)}catch(i){throw i instanceof UE.GaxiosError&&(i.message=`Could not refresh access token: ${i.message}`,this.wrapError(i)),i}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let i={property:n};r=await qd.instance(i)}catch(i){throw i instanceof Error&&(i.message=`Could not fetch ID token: ${i.message}`),i}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};li.Compute=xs});var bs=V(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.IdTokenClient=void 0;var OE=Wt(),Ds=class extends OE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};ui.IdTokenClient=Ds});var Ms=V(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.GCPEnv=void 0;xn.clear=LE;xn.getEnv=qE;var Fd=dr(),wt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(wt||(xn.GCPEnv=wt={}));var hr;function LE(){hr=void 0}async function qE(){return hr||(hr=FE(),hr)}async function FE(){let t=wt.NONE;return BE()?t=wt.APP_ENGINE:HE()?t=wt.CLOUD_FUNCTIONS:await JE()?await XE()?t=wt.KUBERNETES_ENGINE:VE()?t=wt.CLOUD_RUN:$E()?t=wt.CLOUD_RUN_JOBS:t=wt.COMPUTE_ENGINE:t=wt.NONE,t}function BE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function HE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function VE(){return!!process.env.K_CONFIGURATION}function $E(){return!!process.env.CLOUD_RUN_JOB}async function XE(){try{return await Fd.instance("attributes/cluster-name"),!0}catch{return!1}}async function JE(){return Fd.isAvailable()}});var Us=V((bb,Bd)=>{var ci=Pn().Buffer,WE=K("stream"),KE=K("util");function di(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ci.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ci.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}KE.inherits(di,WE);di.prototype.write=function(e){this.buffer=ci.concat([this.buffer,ci.from(e)]),this.emit("data",e)};di.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Bd.exports=di});var Vd=V((Mb,Hd)=>{"use strict";var mr=K("buffer").Buffer,Gs=K("buffer").SlowBuffer;Hd.exports=fi;function fi(t,e){if(!mr.isBuffer(t)||!mr.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}fi.install=function(){mr.prototype.equal=Gs.prototype.equal=function(e){return fi(this,e)}};var YE=mr.prototype.equal,zE=Gs.prototype.equal;fi.restore=function(){mr.prototype.equal=YE,Gs.prototype.equal=zE}});var Fs=V((Ub,Zd)=>{var Dn=Pn().Buffer,et=K("crypto"),Xd=vs(),$d=K("util"),QE=`"%s" is not a valid algorithm.
|
|
14
|
+
Supported algorithms are:
|
|
15
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,gr="secret must be a string or buffer",Nn="key must be a string or a buffer",ZE="key must be a string, a buffer or an object",Ls=typeof et.createPublicKey=="function";Ls&&(Nn+=" or a KeyObject",gr+="or a KeyObject");function Jd(t){if(!Dn.isBuffer(t)&&typeof t!="string"&&(!Ls||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw mt(Nn)}function Wd(t){if(!Dn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw mt(ZE)}function jE(t){if(!Dn.isBuffer(t)){if(typeof t=="string")return t;if(!Ls||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw mt(gr)}}function qs(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Kd(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function mt(t){var e=[].slice.call(arguments,1),n=$d.format.bind($d,t).apply(null,e);return new TypeError(n)}function eT(t){return Dn.isBuffer(t)||typeof t=="string"}function _r(t){return eT(t)||(t=JSON.stringify(t)),t}function Yd(t){return function(n,r){jE(r),n=_r(n);var i=et.createHmac("sha"+t,r),o=(i.update(n),i.digest("base64"));return qs(o)}}var Os,tT="timingSafeEqual"in et?function(e,n){return e.byteLength!==n.byteLength?!1:et.timingSafeEqual(e,n)}:function(e,n){return Os||(Os=Vd()),Os(e,n)};function nT(t){return function(n,r,i){var o=Yd(t)(n,i);return tT(Dn.from(r),Dn.from(o))}}function zd(t){return function(n,r){Wd(r),n=_r(n);var i=et.createSign("RSA-SHA"+t),o=(i.update(n),i.sign(r,"base64"));return qs(o)}}function Qd(t){return function(n,r,i){Jd(i),n=_r(n),r=Kd(r);var o=et.createVerify("RSA-SHA"+t);return o.update(n),o.verify(i,r,"base64")}}function rT(t){return function(n,r){Wd(r),n=_r(n);var i=et.createSign("RSA-SHA"+t),o=(i.update(n),i.sign({key:r,padding:et.constants.RSA_PKCS1_PSS_PADDING,saltLength:et.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return qs(o)}}function iT(t){return function(n,r,i){Jd(i),n=_r(n),r=Kd(r);var o=et.createVerify("RSA-SHA"+t);return o.update(n),o.verify({key:i,padding:et.constants.RSA_PKCS1_PSS_PADDING,saltLength:et.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function oT(t){var e=zd(t);return function(){var r=e.apply(null,arguments);return r=Xd.derToJose(r,"ES"+t),r}}function sT(t){var e=Qd(t);return function(r,i,o){i=Xd.joseToDer(i,"ES"+t).toString("base64");var a=e(r,i,o);return a}}function aT(){return function(){return""}}function lT(){return function(e,n){return n===""}}Zd.exports=function(e){var n={hs:Yd,rs:zd,ps:rT,es:oT,none:aT},r={hs:nT,rs:Qd,ps:iT,es:sT,none:lT},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw mt(QE,e);var o=(i[1]||i[3]).toLowerCase(),a=i[2];return{sign:n[o](a),verify:r[o](a)}}});var Bs=V((Gb,jd)=>{var uT=K("buffer").Buffer;jd.exports=function(e){return typeof e=="string"?e:typeof e=="number"||uT.isBuffer(e)?e.toString():JSON.stringify(e)}});var sf=V((Ob,of)=>{var cT=Pn().Buffer,ef=Us(),dT=Fs(),fT=K("stream"),tf=Bs(),Hs=K("util");function nf(t,e){return cT.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function pT(t,e,n){n=n||"utf8";var r=nf(tf(t),"binary"),i=nf(tf(e),n);return Hs.format("%s.%s",r,i)}function rf(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,i=t.encoding,o=dT(e.alg),a=pT(e,n,i),u=o.sign(a,r);return Hs.format("%s.%s",a,u)}function pi(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new ef(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new ef(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Hs.inherits(pi,fT);pi.prototype.sign=function(){try{var e=rf({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};pi.sign=rf;of.exports=pi});var gf=V((Lb,mf)=>{var lf=Pn().Buffer,af=Us(),hT=Fs(),mT=K("stream"),uf=Bs(),gT=K("util"),_T=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function yT(t){return Object.prototype.toString.call(t)==="[object Object]"}function vT(t){if(yT(t))return t;try{return JSON.parse(t)}catch{return}}function cf(t){var e=t.split(".",1)[0];return vT(lf.from(e,"base64").toString("binary"))}function ET(t){return t.split(".",2).join(".")}function df(t){return t.split(".")[2]}function TT(t,e){e=e||"utf8";var n=t.split(".")[1];return lf.from(n,"base64").toString(e)}function ff(t){return _T.test(t)&&!!cf(t)}function pf(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=uf(t);var i=df(t),o=ET(t),a=hT(e);return a.verify(o,i,n)}function hf(t,e){if(e=e||{},t=uf(t),!ff(t))return null;var n=cf(t);if(!n)return null;var r=TT(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:df(t)}}function bn(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new af(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new af(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}gT.inherits(bn,mT);bn.prototype.verify=function(){try{var e=pf(this.signature.buffer,this.algorithm,this.key.buffer),n=hf(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};bn.decode=hf;bn.isValid=ff;bn.verify=pf;mf.exports=bn});var Vs=V(Kt=>{var _f=sf(),hi=gf(),CT=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Kt.ALGORITHMS=CT;Kt.sign=_f.sign;Kt.verify=hi.verify;Kt.decode=hi.decode;Kt.isValid=hi.isValid;Kt.createSign=function(e){return new _f(e)};Kt.createVerify=function(e){return new hi(e)}});var vf=V(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.buildPayloadForJwsSign=yf;mi.getJwsSign=wT;var AT=Vs(),ST="RS256",IT="https://oauth2.googleapis.com/token";function yf(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:IT,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function wT(t){let e=yf(t);return(0,AT.sign)({header:{alg:ST},payload:e,secret:t.key})}});var Ef=V($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.getToken=NT;var RT=vf(),PT="https://oauth2.googleapis.com/token",kT="urn:ietf:params:oauth:grant-type:jwt-bearer",xT=t=>({method:"POST",url:PT,data:new URLSearchParams({grant_type:kT,assertion:(0,RT.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function NT(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=xT(t);return(await t.transporter.request(e)).data}catch(e){let n=e,r=n.response?.data;throw r?.error&&(n.message=`${r.error}: ${r.error_description}`),n}}});var Tf=V(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.ErrorWithCode=void 0;var Xs=class extends Error{code;constructor(e,n){super(e),this.code=n}};gi.ErrorWithCode=Xs});var Qs=V(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.getCredentials=MT;var DT=K("path"),Cf=K("fs"),bT=K("util"),_i=Tf(),Af=Cf.readFile?(0,bT.promisify)(Cf.readFile):async()=>{throw new _i.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Yt;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Yt||(Yt={}));var Js=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Af(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(o){let a=o;throw new Error(`Invalid JSON key file: ${a.message}`)}let r=n.private_key,i=n.client_email;if(!r||!i)throw new _i.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:i}}},Ws=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Af(this.keyFilePath,"utf8")}}},Ks=class{async getCredentials(){throw new _i.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")}},Ys=class{static create(e){switch(DT.extname(e)){case Yt.JSON:return new Js(e);case Yt.DER:case Yt.CRT:case Yt.PEM:return new Ws(e);case Yt.P12:case Yt.PFX:return new Ks;default:throw new _i.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function MT(t){return Ys.create(t).getCredentials()}});var Sf=V(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.TokenHandler=void 0;var UT=Ef(),GT=Qs(),Zs=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,GT.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,UT.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};yi.TokenHandler=Zs});var If=V(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.revokeToken=qT;var OT="https://oauth2.googleapis.com/revoke?token=",LT=!0;async function qT(t,e){let n=OT+t;return await e.request({url:n,retry:LT})}});var ta=V(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.GoogleToken=void 0;var FT=De(),wf=Sf(),BT=If(),ea=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,FT.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new wf.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let r;typeof e=="function"?r=e:typeof e=="object"&&(n=e);let i=this.tokenHandler.getToken(n.forceRefresh??!1);return r&&i.then(o=>r(null,o),r),i}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,BT.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new wf.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};vi.GoogleToken=ea});var ra=V(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.JWTAccess=void 0;var HT=Vs(),VT=pt(),Rf={alg:"RS256",typ:"JWT"},na=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new VT.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,i){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=i??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let i=this.getCachedKey(e,r),o=this.cache.get(i),a=Date.now();if(o&&o.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(o.headers);let u=Math.floor(Date.now()/1e3),c=t.getExpirationTime(u),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:c,iat:u}:d={iss:this.email,sub:this.email,aud:e,exp:c,iat:u},n){for(let _ in d)if(n[_])throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Rf,kid:this.keyId}:Rf,p=Object.assign(d,n),h=HT.sign({header:f,payload:p,secret:this.key}),g=new Headers({authorization:`Bearer ${h}`});return this.cache.set(i,{expiration:c*1e3,headers:g}),g}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",o=>i+=o).on("error",r).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),n()}catch(o){r(o)}})})}};Ei.JWTAccess=na});var oa=V(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.JWT=void 0;var Pf=ta(),$T=Qs(),XT=ra(),JT=Wt(),Ti=Xe(),ia=class t extends JT.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Ti.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Ti.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Ti.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new XT.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let i=this.useJWTAccessWithScope||this.universeDomain!==Ti.DEFAULT_UNIVERSE,o=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?r:void 0);return{headers:this.addSharedMetadataHeaders(o)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Pf.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new Pf.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let i="";e.setEncoding("utf8").on("error",r).on("data",o=>i+=o).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),n()}catch(o){r(o)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,$T.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ci.JWT=ia});var aa=V(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.UserRefreshClient=Mn.USER_REFRESH_ACCOUNT_TYPE=void 0;var WT=Wt(),KT=Xe();Mn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var sa=class t extends WT.OAuth2Client{_refreshToken;constructor(e,n,r,i,o){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:o};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return KT.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let i="";e.setEncoding("utf8").on("error",r).on("data",o=>i+=o).on("end",()=>{try{let o=JSON.parse(i);return this.fromJSON(o),n()}catch(o){return r(o)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};Mn.UserRefreshClient=sa});var ua=V(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.Impersonated=Un.IMPERSONATED_ACCOUNT_TYPE=void 0;var kf=Wt(),YT=De(),zT=pt();Un.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var la=class t extends kf.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new kf.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,zT.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,i={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:i,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},i=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,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 n=0,r="";throw e instanceof YT.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${r}:generateIdToken`,o={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:o,method:"POST"})).data.token}};Un.Impersonated=la});var da=V(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.OAuthClientAuthHandler=void 0;yr.getErrorFromOAuthErrorResponse=jT;var Gn=De(),QT=fr(),ZT=["PUT","POST","PATCH"],ca=class{#e=(0,QT.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Gn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Gn.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=Gn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=Gn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Gn.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,i=this.#t.clientSecret||"",o=this.#e.encodeBase64StringUtf8(`${r}:${i}`);Gn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${o}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!ZT.includes(n))throw new Error(`${n} 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 new 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"]}}}};yr.OAuthClientAuthHandler=ca;function jT(t,e){let n=t.error,r=t.error_description,i=t.error_uri,o=`Error code ${n}`;typeof r<"u"&&(o+=`: ${r}`),typeof i<"u"&&(o+=` - ${i}`);let a=new Error(o);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(c=>{c!=="message"&&Object.defineProperty(a,c,{value:e[c],writable:!1,enumerable:!0})})}return a}});var Si=V(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.StsCredentials=void 0;var e0=De(),t0=Xe(),xf=da(),n0=pt(),fa=class t extends xf.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){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:r&&JSON.stringify(r)},o={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,n0.removeUndefinedValuesInObject)(i)),responseType:"json"};t0.AuthClient.setMethodName(o,"exchangeToken"),this.applyClientAuthenticationOptions(o);try{let a=await this.transporter.request(o),u=a.data;return u.res=a,u}catch(a){throw a instanceof e0.GaxiosError&&a.response?(0,xf.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Ai.StsCredentials=fa});var zt=V(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.BaseExternalAccountClient=tt.CLOUD_RESOURCE_MANAGER=tt.EXTERNAL_ACCOUNT_TYPE=tt.EXPIRATION_TIME_OFFSET=void 0;var r0=De(),i0=K("stream"),pa=Xe(),o0=Si(),Nf=pt(),s0=Cs(),a0="urn:ietf:params:oauth:grant-type:token-exchange",l0="urn:ietf:params:oauth:token-type:access_token",ha="https://www.googleapis.com/auth/cloud-platform",u0=3600;tt.EXPIRATION_TIME_OFFSET=300*1e3;tt.EXTERNAL_ACCOUNT_TYPE="external_account";tt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var c0="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",d0="https://sts.{universeDomain}/v1/token",ma=class t extends pa.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Nf.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==tt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${tt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=n.get("client_id"),o=n.get("client_secret");this.tokenUrl=n.get("token_url")??d0.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,Nf.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:o}),this.stsCredential=new o0.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[ha],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let p=new RegExp(c0);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=u0),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};pa.AuthClient.setMethodName(r,"getProjectId");let i=await this.transporter.request(r);return this.projectId=i.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=r0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof i0.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:a0,audience:this.audience,requestedTokenType:l0,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[ha]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),o=await this.stsCredential.exchangeToken(n,i,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(o.access_token):o.expires_in?this.cachedAccessToken={access_token:o.access_token,expiry_date:new Date().getTime()+o.expires_in*1e3,res:o.res}:this.cachedAccessToken={access_token:o.access_token,res:o.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};pa.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),i=r.data;return{access_token:i.accessToken,expiry_date:new Date(i.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[ha]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${s0.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};tt.BaseExternalAccountClient=ma});var Df=V(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.FileSubjectTokenSupplier=void 0;var _a=K("util"),ya=K("fs"),f0=(0,_a.promisify)(ya.readFile??(()=>{})),p0=(0,_a.promisify)(ya.realpath??(()=>{})),h0=(0,_a.promisify)(ya.lstat??(()=>{})),ga=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await p0(e),!(await h0(e)).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let n,r=await f0(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Ii.FileSubjectTokenSupplier=ga});var bf=V(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.UrlSubjectTokenSupplier=void 0;var m0=Xe(),va=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};m0.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};wi.UrlSubjectTokenSupplier=va});var Mf=V(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.CertificateSubjectTokenSupplier=Je.InvalidConfigurationError=Je.CertificateSourceUnavailableError=Je.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ri=pt(),Pi=K("fs"),ki=K("crypto"),g0=K("https");Je.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Rt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Je.CertificateSourceUnavailableError=Rt;var nt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Je.InvalidConfigurationError=nt;var Ea=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new nt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new nt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new nt("Cannot create mTLS Agent with missing certificate or key");return new g0.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Ri.isValidFile)(e))return e;throw new Rt(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Je.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Ri.isValidFile)(n))return n;throw new Rt(`Path from environment variable "${Je.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Ri.getWellKnownCertificateConfigFileLocation)();if(await(0,Ri.isValidFile)(r))return r;throw new Rt(`Could not find certificate configuration file. Searched override path, the "${Je.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Pi.promises.readFile(e,"utf8")}catch{throw new Rt(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),i=r?.cert_configs?.workload?.cert_path,o=r?.cert_configs?.workload?.key_path;if(!i||!o)throw new nt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:o}}catch(r){throw r instanceof nt?r:new nt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,i;try{r=await Pi.promises.readFile(e),new ki.X509Certificate(r)}catch(o){let a=o instanceof Error?o.message:String(o);throw new Rt(`Failed to read certificate file at ${e}: ${a}`)}try{i=await Pi.promises.readFile(n),(0,ki.createPrivateKey)(i)}catch(o){let a=o instanceof Error?o.message:String(o);throw new Rt(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:i}}async#r(e){let n=new ki.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let o=((await Pi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,d)=>{try{return new ki.X509Certificate(c)}catch(f){let p=f instanceof Error?f.message:String(f);throw new nt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=o.findIndex(c=>n.raw.equals(c.raw)),u;if(a===-1)u=[n,...o];else if(a===0)u=o;else throw new nt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(r){if(r instanceof nt)throw r;let i=r instanceof Error?r.message:String(r);throw new Rt(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};Je.CertificateSubjectTokenSupplier=Ea});var Aa=V(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.IdentityPoolClient=void 0;var _0=zt(),Ta=pt(),y0=Df(),v0=bf(),Uf=Mf(),E0=Si(),Gf=De(),Ca=class t extends _0.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Ta.originalOrCamelOptions)(e),r=n.get("credential_source"),i=n.get("subject_token_supplier");if(!r&&!i)throw new Error("A credential source or subject token supplier must be specified.");if(r&&i)throw new Error("Only one of credential source or subject token supplier can be specified.");if(i)this.subjectTokenSupplier=i,this.credentialSourceType="programmatic";else{let o=(0,Ta.originalOrCamelOptions)(r),a=(0,Ta.originalOrCamelOptions)(o.get("format")),u=a.get("type")||"text",c=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=o.get("file"),f=o.get("url"),p=o.get("certificate"),h=o.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new y0.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new v0.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new Uf.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=g}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Uf.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new E0.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Gf.Gaxios({agent:n})}),this.transporter=new Gf.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};xi.IdentityPoolClient=Ca});var Ia=V(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.AwsRequestSigner=void 0;var Ni=De(),Lf=fr(),Of="AWS4-HMAC-SHA256",T0="aws4_request",Sa=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,Lf.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,i=e.method||"GET",o=e.body||n,a=e.headers,u=await this.getCredentials(),c=new URL(r);if(typeof o!="string"&&o!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${o}`);let d=await A0({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:i,region:this.region,securityCredentials:u,requestPayload:o,additionalAmzHeaders:a}),f=Ni.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},a||{});u.token&&Ni.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token});let p={url:r,method:i,headers:f};return o!==void 0&&(p.body=o),p}};Di.AwsRequestSigner=Sa;async function vr(t,e,n){return await t.signWithHmacSha256(e,n)}async function C0(t,e,n,r,i){let o=await vr(t,`AWS4${e}`,n),a=await vr(t,o,r),u=await vr(t,a,i);return await vr(t,u,"aws4_request")}async function A0(t){let e=Ni.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],i=new Date,o=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=Ni.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":o},e),c="",d=[...u.keys()].sort();d.forEach(E=>{c+=`${E}:${u.get(E)}
|
|
16
|
+
`});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
|
|
17
|
+
${t.canonicalUri}
|
|
18
|
+
${t.canonicalQuerystring}
|
|
19
|
+
${c}
|
|
20
|
+
${f}
|
|
21
|
+
${p}`,g=`${a}/${t.region}/${r}/${T0}`,_=`${Of}
|
|
22
|
+
${o}
|
|
23
|
+
${g}
|
|
24
|
+
`+await t.crypto.sha256DigestHex(h),m=await C0(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),v=await vr(t.crypto,m,_),y=`${Of} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,Lf.fromArrayBufferToHex)(v)}`;return{amzDate:e.has("date")?void 0:o,authorizationHeader:y,canonicalQuerystring:t.canonicalQuerystring}}});var qf=V(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.DefaultAwsSecurityCredentialsSupplier=void 0;var bi=Xe(),wa=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};bi.AuthClient.setMethodName(r,"getAwsRegion");let i=await e.transporter.request(r);return i.data.substr(0,i.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),i=await this.#n(r,n,e.transporter);return{accessKeyId:i.AccessKeyId,secretAccessKey:i.SecretAccessKey,token:i.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return bi.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return bi.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return bi.AuthClient.setMethodName(i,"#retrieveAwsSecurityCredentials"),(await r.request(i)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Mi.DefaultAwsSecurityCredentialsSupplier=wa});var Pa=V(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.AwsClient=void 0;var S0=Ia(),I0=zt(),w0=qf(),Ff=pt(),R0=De(),Ra=class t extends I0.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,Ff.originalOrCamelOptions)(e),r=n.get("credential_source"),i=n.get("aws_security_credentials_supplier");if(!r&&!i)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&i)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let o=(0,Ff.originalOrCamelOptions)(r);this.environmentId=o.get("environment_id");let a=o.get("region_url"),u=o.get("url"),c=o.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new w0.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c}),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 new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new S0.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return R0.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,o)=>n.push({key:o,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Ui.AwsClient=Ra});var ba=V(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.InvalidSubjectTokenError=Pe.InvalidMessageFieldError=Pe.InvalidCodeFieldError=Pe.InvalidTokenTypeFieldError=Pe.InvalidExpirationTimeFieldError=Pe.InvalidSuccessFieldError=Pe.InvalidVersionFieldError=Pe.ExecutableResponseError=Pe.ExecutableResponse=void 0;var Gi="urn:ietf:params:oauth:token-type:saml2",ka="urn:ietf:params:oauth:token-type:id_token",xa="urn:ietf:params:oauth:token-type:jwt",Na=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Oi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Li("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!==Gi&&this.tokenType!==ka&&this.tokenType!==xa)throw new qi(`Executable response must contain a 'token_type' field when successful and it must be one of ${ka}, ${xa}, or ${Gi}.`);if(this.tokenType===Gi){if(!e.saml_response)throw new Er(`Executable response must contain a 'saml_response' field when token_type=${Gi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Er(`Executable response must contain a 'id_token' field when token_type=${ka} or ${xa}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Fi("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Bi("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Pe.ExecutableResponse=Na;var Pt=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Pe.ExecutableResponseError=Pt;var Oi=class extends Pt{};Pe.InvalidVersionFieldError=Oi;var Li=class extends Pt{};Pe.InvalidSuccessFieldError=Li;var Da=class extends Pt{};Pe.InvalidExpirationTimeFieldError=Da;var qi=class extends Pt{};Pe.InvalidTokenTypeFieldError=qi;var Fi=class extends Pt{};Pe.InvalidCodeFieldError=Fi;var Bi=class extends Pt{};Pe.InvalidMessageFieldError=Bi;var Er=class extends Pt{};Pe.InvalidSubjectTokenError=Er});var Ga=V(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.PluggableAuthHandler=On.ExecutableError=void 0;var gn=ba(),P0=K("child_process"),Ma=K("fs"),Hi=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};On.ExecutableError=Hi;var Ua=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let i=P0.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),o="";i.stdout.on("data",u=>{o+=u}),i.stderr.on("data",u=>{o+=u});let a=setTimeout(()=>(i.removeAllListeners(),i.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",u=>{if(clearTimeout(a),u===0)try{let c=JSON.parse(o),d=new gn.ExecutableResponse(c);return n(d)}catch(c){return c instanceof gn.ExecutableResponseError?r(c):r(new gn.ExecutableResponseError(`The executable returned an invalid response: ${o}`))}else return r(new Hi(o,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Ma.promises.realpath(this.outputFile)}catch{return}if(!(await Ma.promises.lstat(e)).isFile())return;let n=await Ma.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new gn.ExecutableResponse(r).isValid()?new gn.ExecutableResponse(r):void 0}catch(r){throw r instanceof gn.ExecutableResponseError?r:new gn.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};On.PluggableAuthHandler=Ua});var La=V(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.PluggableAuthClient=Ln.ExecutableError=void 0;var k0=zt(),x0=ba(),Bf=Ga(),N0=Ga();Object.defineProperty(Ln,"ExecutableError",{enumerable:!0,get:function(){return N0.ExecutableError}});var D0=30*1e3,Hf=5*1e3,Vf=120*1e3,b0="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",$f=1,Oa=class extends k0.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=D0;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Hf||this.timeoutMillis>Vf)throw new Error(`Timeout must be between ${Hf} and ${Vf} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Bf.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[b0]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>$f)throw new Error(`Version of executable is not currently supported, maximum supported version is ${$f}.`);if(!e.success)throw new Bf.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new x0.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};Ln.PluggableAuthClient=Oa});var Fa=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.ExternalAccountClient=void 0;var M0=zt(),U0=Aa(),G0=Pa(),O0=La(),qa=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===M0.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new G0.AwsClient(e):e.credential_source?.executable?new O0.PluggableAuthClient(e):new U0.IdentityPoolClient(e):null}};Vi.ExternalAccountClient=qa});var Va=V(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.ExternalAccountAuthorizedUserClient=qn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Jf=Xe(),Xf=da(),Wf=De(),L0=K("stream"),q0=zt();qn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var F0="https://sts.{universeDomain}/v1/oauthtoken",Ba=class t extends Xf.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};Jf.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let i=await this.transporter.request(r),o=i.data;return o.res=i,o}catch(i){throw i instanceof Wf.GaxiosError&&i.response?(0,Xf.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},Ha=class extends Jf.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ba({tokenRefreshEndpoint:e.token_url??F0.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=q0.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=Wf.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof L0.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};qn.ExternalAccountAuthorizedUserClient=Ha});var Xa=V(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.GdchClient=Qt.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var B0=K("crypto"),H0=K("fs"),V0=K("https"),$0=Wt(),X0=3600;Qt.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var $a=class t extends $0.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||X0,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Qt.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Qt.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(r.agent=await this.getCaAgent());try{let i=await this.transporter.request(r),o=i.data;if(!o.access_token)throw new Error("Token response did not contain an access_token.");if(!o.expires_in)throw new Error("Token response did not contain an expires_in field.");let a={access_token:o.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+o.expires_in*1e3};return this.emit("tokens",a),{res:i,tokens:a}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data=="string"){let o=JSON.parse(i.config.data);o.subject_token&&(o.subject_token="***REDACTED***",i.config.data=JSON.stringify(o))}else typeof i.config.data=="object"&&i.config.data.subject_token&&(i.config.data.subject_token="***REDACTED***")}catch{}throw i instanceof Error&&(i.message=`Error getting access token for GDCH service account: ${i.message}, iss: ${this.serviceIdentityName}`),i}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1e3),i={iss:n,sub:n,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},o=this.base64UrlEncode(JSON.stringify(e)),a=this.base64UrlEncode(JSON.stringify(i)),u=`${o}.${a}`,c=B0.sign("sha256",Buffer.from(u),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(c);return`${u}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();!r.includes("googleapis.com")&&!r.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let i=await H0.promises.readFile(r);return new V0.Agent({ca:i})}catch(i){throw this.cachedCaCertPath===r&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),i instanceof Error&&(i.message=`Error reading certificate file from CA cert path, value '${r}': ${i.message}`),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")}};Qt.GdchClient=$a});var Qf=V(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.GoogleAuth=gt.GoogleAuthExceptionMessages=void 0;var J0=K("child_process"),Tr=K("fs"),W0=De(),Cr=dr(),K0=K("os"),$i=K("path"),Y0=fr(),z0=Ns(),Q0=bs(),Z0=Ms(),Fn=oa(),Kf=aa(),Bn=ua(),j0=Fa(),Ar=zt(),Ja=Xe(),Yf=Va(),Wa=Xa(),zf=pt();gt.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.
|
|
25
|
+
To learn more about authentication and Google APIs, visit:
|
|
26
|
+
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
27
|
+
To learn more about authentication and Google APIs, visit:
|
|
28
|
+
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.
|
|
29
|
+
To learn more about Universe Domain retrieval, visit:
|
|
30
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ka=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(gt.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===gt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(gt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Cr.universe("universe-domain"),e||=Ja.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ja.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,zf.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ja.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(i=>n(null,i.credential,i.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof Fn.JWT?n.scopes=this.scopes:n instanceof Ar.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Fn.JWT?n.scopes=this.scopes:n instanceof Ar.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new z0.Compute(e));throw new Error(gt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Cr.getGCPResidency()||await Cr.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=$i.join(process.env.APPDATA,"gcloud"));else{let o=process.env.HOME;o&&(n=$i.join(o,".config","gcloud"))}if(!n)return null;let r=$i.join(n,"application_default_credentials.json");return Tr.existsSync(r)?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Tr.realpathSync(e),!Tr.lstatSync(e).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let r=Tr.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Bn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Bn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let i=(this.scopes||e.scopes||this.defaultScopes)??[];return new Bn.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let r,i=(0,zf.originalOrCamelOptions)(n).get("universe_domain");return e.type===Kf.USER_REFRESH_ACCOUNT_TYPE?(r=new Kf.UserRefreshClient(n),r.fromJSON(e)):e.type===Bn.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ar.EXTERNAL_ACCOUNT_TYPE?(r=j0.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===Yf.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new Yf.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Wa.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Wa.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Fn.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),i&&(r.universeDomain=i),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){let i={};if(typeof n=="function"?r=n:i=n,r)this.fromStreamAsync(e,i).then(o=>r(null,o),r);else return this.fromStreamAsync(e,i)}fromStreamAsync(e,n){return new Promise((r,i)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let o=[];e.setEncoding("utf8").on("error",i).on("data",a=>o.push(a)).on("end",()=>{try{try{let a=JSON.parse(o.join("")),u=this._cacheClientFromJSON(a,n);return r(u)}catch(a){if(!this.keyFilename)throw a;let u=new Fn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),r(u)}}catch(a){return i(a)}})})}fromAPIKey(e,n={}){return new Fn.JWT({...n,apiKey:e})}_isWindows(){let e=K0.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,J0.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let i=JSON.parse(r).configuration.properties.core.project;e(i);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Ar.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Cr.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Bn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ar.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([Cr.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(gt.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 Wa.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let o=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),a=e.createWithGdchAudience(o);return this.cachedCredential=a,a}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=$i.resolve(this.keyFilename),n=Tr.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new Q0.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,i=await(await this.getClient()).getRequestHeaders(n);return e.headers=W0.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(0,Z0.getEnv)()}async sign(e,n){let r=await this.getClient(),i=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${i}/v1/projects/-/serviceAccounts/`,r instanceof Bn.Impersonated)return(await r.sign(e)).signedBlob;let o=(0,Y0.createCrypto)();if(r instanceof Fn.JWT&&r.key)return await o.sign(r.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(o,a.client_email,e,n)}async signBlob(e,n,r,i){let o=new URL(i+`${n}:signBlob`);return(await this.request({method:"POST",url:o.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};gt.GoogleAuth=Ka});var Zf=V(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.IAMAuth=void 0;var Ya=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Xi.IAMAuth=Ya});var jf=V(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.DownscopedClient=kt.EXPIRATION_TIME_OFFSET=kt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var eC=De(),tC=K("stream"),za=Xe(),nC=Si(),rC="urn:ietf:params:oauth:grant-type:token-exchange",iC="urn:ietf:params:oauth:token-type:access_token",oC="urn:ietf:params:oauth:token-type:access_token";kt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;kt.EXPIRATION_TIME_OFFSET=300*1e3;var Qa=class extends za.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof za.AuthClient?{}:e),e instanceof za.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>kt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${kt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new nC.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=eC.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof tC.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:rC,requestedTokenType:iC,subjectToken:e,subjectTokenType:oC},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,o=r.expires_in?new Date().getTime()+r.expires_in*1e3:i;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:o,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};kt.DownscopedClient=Qa});var ep=V(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.PassThroughClient=void 0;var sC=Xe(),Za=class extends sC.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Ji.PassThroughClient=Za});var sp=V(Y=>{"use strict";var aC=Y&&Y.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lC=Y&&Y.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aC(e,t,n)};Object.defineProperty(Y,"__esModule",{value:!0});Y.GoogleAuth=Y.auth=Y.GDCH_SERVICE_ACCOUNT_TYPE=Y.GdchClient=Y.PassThroughClient=Y.ExternalAccountAuthorizedUserClient=Y.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Y.ExecutableError=Y.PluggableAuthClient=Y.DownscopedClient=Y.BaseExternalAccountClient=Y.ExternalAccountClient=Y.IdentityPoolClient=Y.AwsRequestSigner=Y.AwsClient=Y.UserRefreshClient=Y.LoginTicket=Y.ClientAuthentication=Y.OAuth2Client=Y.CodeChallengeMethod=Y.Impersonated=Y.JWT=Y.JWTAccess=Y.IdTokenClient=Y.IAMAuth=Y.GCPEnv=Y.Compute=Y.DEFAULT_UNIVERSE=Y.AuthClient=Y.gaxios=Y.gcpMetadata=void 0;var tp=Qf();Object.defineProperty(Y,"GoogleAuth",{enumerable:!0,get:function(){return tp.GoogleAuth}});Y.gcpMetadata=dr();Y.gaxios=De();var np=Xe();Object.defineProperty(Y,"AuthClient",{enumerable:!0,get:function(){return np.AuthClient}});Object.defineProperty(Y,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return np.DEFAULT_UNIVERSE}});var uC=Ns();Object.defineProperty(Y,"Compute",{enumerable:!0,get:function(){return uC.Compute}});var cC=Ms();Object.defineProperty(Y,"GCPEnv",{enumerable:!0,get:function(){return cC.GCPEnv}});var dC=Zf();Object.defineProperty(Y,"IAMAuth",{enumerable:!0,get:function(){return dC.IAMAuth}});var fC=bs();Object.defineProperty(Y,"IdTokenClient",{enumerable:!0,get:function(){return fC.IdTokenClient}});var pC=ra();Object.defineProperty(Y,"JWTAccess",{enumerable:!0,get:function(){return pC.JWTAccess}});var hC=oa();Object.defineProperty(Y,"JWT",{enumerable:!0,get:function(){return hC.JWT}});var mC=ua();Object.defineProperty(Y,"Impersonated",{enumerable:!0,get:function(){return mC.Impersonated}});var ja=Wt();Object.defineProperty(Y,"CodeChallengeMethod",{enumerable:!0,get:function(){return ja.CodeChallengeMethod}});Object.defineProperty(Y,"OAuth2Client",{enumerable:!0,get:function(){return ja.OAuth2Client}});Object.defineProperty(Y,"ClientAuthentication",{enumerable:!0,get:function(){return ja.ClientAuthentication}});var gC=Rs();Object.defineProperty(Y,"LoginTicket",{enumerable:!0,get:function(){return gC.LoginTicket}});var _C=aa();Object.defineProperty(Y,"UserRefreshClient",{enumerable:!0,get:function(){return _C.UserRefreshClient}});var yC=Pa();Object.defineProperty(Y,"AwsClient",{enumerable:!0,get:function(){return yC.AwsClient}});var vC=Ia();Object.defineProperty(Y,"AwsRequestSigner",{enumerable:!0,get:function(){return vC.AwsRequestSigner}});var EC=Aa();Object.defineProperty(Y,"IdentityPoolClient",{enumerable:!0,get:function(){return EC.IdentityPoolClient}});var TC=Fa();Object.defineProperty(Y,"ExternalAccountClient",{enumerable:!0,get:function(){return TC.ExternalAccountClient}});var CC=zt();Object.defineProperty(Y,"BaseExternalAccountClient",{enumerable:!0,get:function(){return CC.BaseExternalAccountClient}});var AC=jf();Object.defineProperty(Y,"DownscopedClient",{enumerable:!0,get:function(){return AC.DownscopedClient}});var rp=La();Object.defineProperty(Y,"PluggableAuthClient",{enumerable:!0,get:function(){return rp.PluggableAuthClient}});Object.defineProperty(Y,"ExecutableError",{enumerable:!0,get:function(){return rp.ExecutableError}});var ip=Va();Object.defineProperty(Y,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return ip.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Y,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return ip.ExternalAccountAuthorizedUserClient}});var SC=ep();Object.defineProperty(Y,"PassThroughClient",{enumerable:!0,get:function(){return SC.PassThroughClient}});var op=Xa();Object.defineProperty(Y,"GdchClient",{enumerable:!0,get:function(){return op.GdchClient}});Object.defineProperty(Y,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return op.GDCH_SERVICE_ACCOUNT_TYPE}});lC(ta(),Y);var IC=new tp.GoogleAuth;Y.auth=IC});var Ut=V((yM,up)=>{"use strict";var ap=["nodebuffer","arraybuffer","fragments"],lp=typeof Blob<"u";lp&&ap.push("blob");up.exports={BINARY_TYPES:ap,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:lp,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Sr=V((vM,Hn)=>{"use strict";var{websocketMask:cp,websocketUnmask:wC}=K("http"),{EMPTY_BUFFER:RC}=Ut(),el=Buffer[Symbol.species];function PC(t,e){if(t.length===0)return RC;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new el(n.buffer,n.byteOffset,r):n}function tl(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function nl(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function kC(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function rl(t){if(rl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new el(t):ArrayBuffer.isView(t)?e=new el(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rl.readOnly=!1),e}Hn.exports={concat:PC,mask:tl,toArrayBuffer:kC,toBuffer:rl,unmask:nl};if(cp)Hn.exports.mask=function(t,e,n,r,i){i<24?tl(t,e,n,r,i):cp(t,e,n,r,i)},Hn.exports.unmask=function(t,e){t.length<24?nl(t,e):wC(t,e)};else if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");Hn.exports.mask=function(e,n,r,i,o){o<48?tl(e,n,r,i,o):t.mask(e,n,r,i,o)},Hn.exports.unmask=function(e,n){e.length<32?nl(e,n):t.unmask(e,n)}}catch{}});var pp=V((EM,fp)=>{"use strict";var dp=Symbol("kDone"),il=Symbol("kRun"),ol=class{constructor(e){this[dp]=()=>{this.pending--,this[il]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[il]()}[il](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[dp])}}};fp.exports=ol});var Xn=V((TM,_p)=>{"use strict";var Ir=K("zlib"),hp=Sr(),xC=pp(),{kStatusCode:mp}=Ut(),NC=Buffer[Symbol.species],DC=Buffer.from([0,0,255,255]),Ki=Symbol("permessage-deflate"),Gt=Symbol("total-length"),Vn=Symbol("callback"),Zt=Symbol("buffers"),$n=Symbol("error"),Wi,sl=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Wi){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Wi=new xC(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Vn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?n.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){Wi.add(i=>{this._decompress(e,n,(o,a)=>{i(),r(o,a)})})}compress(e,n,r){Wi.add(i=>{this._compress(e,n,(o,a)=>{i(),r(o,a)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Ir.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Ir.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Ki]=this,this._inflate[Gt]=0,this._inflate[Zt]=[],this._inflate.on("error",MC),this._inflate.on("data",gp)}this._inflate[Vn]=r,this._inflate.write(e),n&&this._inflate.write(DC),this._inflate.flush(()=>{let o=this._inflate[$n];if(o){this._inflate.close(),this._inflate=null,r(o);return}let a=hp.concat(this._inflate[Zt],this._inflate[Gt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Gt]=0,this._inflate[Zt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,a)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Ir.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Ir.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Gt]=0,this._deflate[Zt]=[],this._deflate.on("data",bC)}this._deflate[Vn]=r,this._deflate.write(e),this._deflate.flush(Ir.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=hp.concat(this._deflate[Zt],this._deflate[Gt]);n&&(o=new NC(o.buffer,o.byteOffset,o.length-4)),this._deflate[Vn]=null,this._deflate[Gt]=0,this._deflate[Zt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};_p.exports=sl;function bC(t){this[Zt].push(t),this[Gt]+=t.length}function gp(t){if(this[Gt]+=t.length,this[Ki]._maxPayload<1||this[Gt]<=this[Ki]._maxPayload){this[Zt].push(t);return}this[$n]=new RangeError("Max payload size exceeded"),this[$n].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$n][mp]=1009,this.removeListener("data",gp),this.reset()}function MC(t){if(this[Ki]._inflate=null,this[$n]){this[Vn](this[$n]);return}t[mp]=1007,this[Vn](t)}});var Jn=V((CM,Yi)=>{"use strict";var{isUtf8:yp}=K("buffer"),{hasBlob:UC}=Ut(),GC=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function OC(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function al(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function LC(t){return UC&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yi.exports={isBlob:LC,isValidStatusCode:OC,isValidUTF8:al,tokenChars:GC};if(yp)Yi.exports.isValidUTF8=function(t){return t.length<24?al(t):yp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");Yi.exports.isValidUTF8=function(e){return e.length<32?al(e):t(e)}}catch{}});var fl=V((AM,Ip)=>{"use strict";var{Writable:qC}=K("stream"),vp=Xn(),{BINARY_TYPES:FC,EMPTY_BUFFER:Ep,kStatusCode:BC,kWebSocket:HC}=Ut(),{concat:ll,toArrayBuffer:VC,unmask:$C}=Sr(),{isValidStatusCode:XC,isValidUTF8:Tp}=Jn(),zi=Buffer[Symbol.species],rt=0,Cp=1,Ap=2,Sp=3,ul=4,cl=5,Qi=6,dl=class extends qC{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||FC[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[HC]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=rt}_write(e,n,r){if(this._opcode===8&&this._state==rt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new zi(r.buffer,r.byteOffset+e,r.length-e),new zi(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new zi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case rt:this.getInfo(e);break;case Cp:this.getPayloadLength16(e);break;case Ap:this.getPayloadLength64(e);break;case Sp:this.getMask();break;case ul:this.getData(e);break;case cl:case Qi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[vp.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Cp:this._payloadLength===127?this._state=Ap:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Sp:this._state=ul}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ul}getData(e){let n=Ep;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&$C(n,this._mask)}if(this._mask=void 0,this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=cl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[vp.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(o)}this.dataMessage(n),this._state===rt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=rt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=ll(r,n):this._binaryType==="arraybuffer"?i=VC(ll(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=rt):(this._state=Qi,setImmediate(()=>{this.emit("message",i,!0),this._state=rt,this.startLoop(e)}))}else{let i=ll(r,n);if(!this._skipUTF8Validation&&!Tp(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===cl||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=rt):(this._state=Qi,setImmediate(()=>{this.emit("message",i,!1),this._state=rt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ep),this.end();else{let r=e.readUInt16BE(0);if(!XC(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new zi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Tp(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=rt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=rt):(this._state=Qi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=rt,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let a=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=o,a[BC]=i,a}};Ip.exports=dl});var ml=V((IM,Pp)=>{"use strict";var{Duplex:SM}=K("stream"),{randomFillSync:JC}=K("crypto"),{types:{isUint8Array:WC}}=K("util"),wp=Xn(),{EMPTY_BUFFER:KC,kWebSocket:YC,NOOP:zC}=Ut(),{isBlob:Wn,isValidStatusCode:QC}=Jn(),{mask:Rp,toBuffer:_n}=Sr(),it=Symbol("kByteLength"),ZC=Buffer.alloc(4),Zi=8*1024,yn,Kn=Zi,_t=0,jC=1,eA=2,pl=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=_t,this.onerror=zC,this[YC]=void 0}static frame(e,n){let r,i=!1,o=2,a=!1;n.mask&&(r=n.maskBuffer||ZC,n.generateMask?n.generateMask(r):(Kn===Zi&&(yn===void 0&&(yn=Buffer.alloc(Zi)),JC(yn,0,Zi),Kn=0),r[0]=yn[Kn++],r[1]=yn[Kn++],r[2]=yn[Kn++],r[3]=yn[Kn++]),a=(r[0]|r[1]|r[2]|r[3])===0,o=6);let u;typeof e=="string"?(!n.mask||a)&&n[it]!==void 0?u=n[it]:(e=Buffer.from(e),u=e.length):(u=e.length,i=n.mask&&n.readOnly&&!a);let c=u;u>=65536?(o+=8,c=127):u>125&&(o+=2,c=126);let d=Buffer.allocUnsafe(i?u+o:o);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(u,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(u,4,6)),n.mask?(d[1]|=128,d[o-4]=r[0],d[o-3]=r[1],d[o-2]=r[2],d[o-1]=r[3],u?a?[d,e]:i?(Rp(e,r,d,o,u),[d]):(Rp(e,r,e,0,u),[d,e]):[d]):u?[d,e]:[d]}close(e,n,r,i){let o;if(e===void 0)o=KC;else{if(typeof e!="number"||!QC(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+u),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(WC(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[it]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==_t?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(t.frame(o,a),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Wn(e)?(i=e.size,o=!1):(e=_n(e),i=e.length,o=_n.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[it]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Wn(e)?this._state!==_t?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==_t?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Wn(e)?(i=e.size,o=!1):(e=_n(e),i=e.length,o=_n.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[it]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Wn(e)?this._state!==_t?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==_t?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let i=this._extensions[wp.extensionName],o=n.binary?2:1,a=n.compress,u,c;typeof e=="string"?(u=Buffer.byteLength(e),c=!1):Wn(e)?(u=e.size,c=!1):(e=_n(e),u=e.length,c=_n.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=u>=i._threshold),this._compress=a):(a=!1,o=0),n.fin&&(this._firstFragment=!0);let d={[it]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};Wn(e)?this._state!==_t?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==_t?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[it],this._state=eA,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(hl,this,u,i);return}this._bufferedBytes-=r[it];let a=_n(o);n?this.dispatch(a,n,r,i):(this._state=_t,this.sendFrame(t.frame(a,r),i),this.dequeue())}).catch(o=>{process.nextTick(tA,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[wp.extensionName];this._bufferedBytes+=r[it],this._state=jC,o.compress(e,r.fin,(a,u)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");hl(this,c,i);return}this._bufferedBytes-=r[it],this._state=_t,r.readOnly=!1,this.sendFrame(t.frame(u,r),i),this.dequeue()})}dequeue(){for(;this._state===_t&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][it],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][it],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Pp.exports=pl;function hl(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function tA(t,e,n){hl(t,e,n),t.onerror(e)}});var Op=V((wM,Gp)=>{"use strict";var{kForOnEventAttribute:wr,kListener:gl}=Ut(),kp=Symbol("kCode"),xp=Symbol("kData"),Np=Symbol("kError"),Dp=Symbol("kMessage"),bp=Symbol("kReason"),Yn=Symbol("kTarget"),Mp=Symbol("kType"),Up=Symbol("kWasClean"),Ot=class{constructor(e){this[Yn]=null,this[Mp]=e}get target(){return this[Yn]}get type(){return this[Mp]}};Object.defineProperty(Ot.prototype,"target",{enumerable:!0});Object.defineProperty(Ot.prototype,"type",{enumerable:!0});var vn=class extends Ot{constructor(e,n={}){super(e),this[kp]=n.code===void 0?0:n.code,this[bp]=n.reason===void 0?"":n.reason,this[Up]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[kp]}get reason(){return this[bp]}get wasClean(){return this[Up]}};Object.defineProperty(vn.prototype,"code",{enumerable:!0});Object.defineProperty(vn.prototype,"reason",{enumerable:!0});Object.defineProperty(vn.prototype,"wasClean",{enumerable:!0});var zn=class extends Ot{constructor(e,n={}){super(e),this[Np]=n.error===void 0?null:n.error,this[Dp]=n.message===void 0?"":n.message}get error(){return this[Np]}get message(){return this[Dp]}};Object.defineProperty(zn.prototype,"error",{enumerable:!0});Object.defineProperty(zn.prototype,"message",{enumerable:!0});var Rr=class extends Ot{constructor(e,n={}){super(e),this[xp]=n.data===void 0?null:n.data}get data(){return this[xp]}};Object.defineProperty(Rr.prototype,"data",{enumerable:!0});var nA={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[wr]&&i[gl]===e&&!i[wr])return;let r;if(t==="message")r=function(o,a){let u=new Rr("message",{data:a?o:o.toString()});u[Yn]=this,ji(e,this,u)};else if(t==="close")r=function(o,a){let u=new vn("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Yn]=this,ji(e,this,u)};else if(t==="error")r=function(o){let a=new zn("error",{error:o,message:o.message});a[Yn]=this,ji(e,this,a)};else if(t==="open")r=function(){let o=new Ot("open");o[Yn]=this,ji(e,this,o)};else return;r[wr]=!!n[wr],r[gl]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[gl]===e&&!n[wr]){this.removeListener(t,n);break}}};Gp.exports={CloseEvent:vn,ErrorEvent:zn,Event:Ot,EventTarget:nA,MessageEvent:Rr};function ji(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var eo=V((RM,Lp)=>{"use strict";var{tokenChars:Pr}=Jn();function xt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function rA(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,a,u,c=-1,d=-1,f=-1,p=0;for(;p<t.length;p++)if(d=t.charCodeAt(p),a===void 0)if(f===-1&&Pr[d]===1)c===-1&&(c=p);else if(p!==0&&(d===32||d===9))f===-1&&c!==-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let g=t.slice(c,f);d===44?(xt(e,g,n),n=Object.create(null)):a=g,c=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(u===void 0)if(f===-1&&Pr[d]===1)c===-1&&(c=p);else if(d===32||d===9)f===-1&&c!==-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),xt(n,t.slice(c,f),!0),d===44&&(xt(e,a,n),n=Object.create(null),a=void 0),c=f=-1}else if(d===61&&c!==-1&&f===-1)u=t.slice(c,p),c=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(i){if(Pr[d]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),i=!1}else if(o)if(Pr[d]===1)c===-1&&(c=p);else if(d===34&&c!==-1)o=!1,f=p;else if(d===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&t.charCodeAt(p-1)===61)o=!0;else if(f===-1&&Pr[d]===1)c===-1&&(c=p);else if(c!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let g=t.slice(c,f);r&&(g=g.replace(/\\/g,""),r=!1),xt(n,u,g),d===44&&(xt(e,a,n),n=Object.create(null),a=void 0),u=void 0,c=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||o||d===32||d===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let h=t.slice(c,f);return a===void 0?xt(e,h,n):(u===void 0?xt(n,h,!0):r?xt(n,u,h.replace(/\\/g,"")):xt(n,u,h),xt(e,a,n)),e}function iA(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Lp.exports={format:iA,parse:rA}});var io=V((xM,Qp)=>{"use strict";var oA=K("events"),sA=K("https"),aA=K("http"),Hp=K("net"),qp=K("querystring"),lA=K("tls"),{randomBytes:uA,createHash:cA}=K("crypto"),{Duplex:PM,Readable:kM}=K("stream"),{URL:to}=K("url"),jt=Xn(),dA=fl(),fA=ml(),{isBlob:pA}=Jn(),{BINARY_TYPES:Fp,CLOSE_TIMEOUT:hA,EMPTY_BUFFER:kr,GUID:mA,kForOnEventAttribute:_l,kListener:gA,kStatusCode:_A,kWebSocket:Ne,NOOP:Vp}=Ut(),{EventTarget:{addEventListener:yA,removeEventListener:vA}}=Op(),{format:EA,parse:TA}=eo(),{toBuffer:CA}=Sr(),$p=Symbol("kAborted"),yl=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],AA=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Se=class t extends oA{constructor(e,n,r){super(),this._binaryType=Fp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=kr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?!r||r.protocols===void 0?n=[]:Array.isArray(r.protocols)?n=r.protocols:n=[r.protocols]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,r.protocols===void 0?n=[]:Array.isArray(r.protocols)?n=r.protocols:n=[r.protocols]):n=[n]),Xp(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Fp.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new dA({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new fA(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Ne]=this,o[Ne]=this,e[Ne]=this,i.on("conclude",wA),i.on("drain",RA),i.on("error",PA),i.on("message",kA),i.on("ping",xA),i.on("pong",NA),o.onerror=DA,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Kp),e.on("data",ro),e.on("end",Yp),e.on("error",zp),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[jt.extensionName]&&this._extensions[jt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=t.CLOSING,Wp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){vl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||kr,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){vl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||kr,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){vl(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[jt.extensionName]||(i.compress=!1),this._sender.send(e||kr,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Se,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")});Object.defineProperty(Se.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")});Object.defineProperty(Se,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")});Object.defineProperty(Se.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")});Object.defineProperty(Se,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")});Object.defineProperty(Se.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")});Object.defineProperty(Se,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")});Object.defineProperty(Se.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Se.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Se.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[_l])return e[gA];return null},set(e){for(let n of this.listeners(t))if(n[_l]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[_l]:!0})}})});Se.prototype.addEventListener=yA;Se.prototype.removeEventListener=vA;Qp.exports=Se;function Xp(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:hA,protocolVersion:yl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!yl.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${yl.join(", ")})`);let o;if(e instanceof to)o=e;else try{o=new to(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}(o.protocol==="http:"||o.protocol==="https:")&&(o=new to(o),o.protocol=o.protocol==="http:"?"ws:":"wss:"),t._url=o.href;let a=o.protocol==="wss:",u=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!a&&!u?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;no(t,m);return}let d=a?443:80,f=uA(16).toString("base64"),p=a?sA.request:aA.request,h=new Set,g;if(i.createConnection=i.createConnection||(a?IA:SA),i.defaultPort=i.defaultPort||d,i.port=o.port||d,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new jt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=EA({[jt.extensionName]:g.offer()})),n.length){for(let m of n){if(typeof m!="string"||!AA.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),o.username||o.password){let m=qp.unescape(o.username),v=qp.unescape(o.password);i.auth=`${m}:${v}`}if(u){let m=i.path.indexOf(":");m===-1?(i.socketPath=i.path,i.path=""):(i.socketPath=i.path.slice(0,m),i.path=i.path.slice(m+1))}let _;if(i.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=a,t._originalHostOrSocketPath=u?i.socketPath:o.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[v,y]of Object.entries(m))r.headers[v.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=u?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,m||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),_=t._req=p(i),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=p(i);i.timeout&&_.on("timeout",()=>{We(t,_,"Opening handshake has timed out")}),_.on("error",m=>{_===null||_[$p]||(_=t._req=null,no(t,m))}),_.on("response",m=>{let v=m.headers.location,y=m.statusCode;if(v&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){We(t,_,"Maximum redirects exceeded");return}_.abort();let E;try{E=new to(v,e)}catch{let A=new SyntaxError(`Invalid URL: ${v}`);no(t,A);return}Xp(t,E,n,r)}else t.emit("unexpected-response",_,m)||We(t,_,`Unexpected server response: ${m.statusCode}`)}),_.on("upgrade",(m,v,y)=>{if(t.emit("upgrade",m),t.readyState!==Se.CONNECTING)return;_=t._req=null;let E=m.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){We(t,v,"Invalid Upgrade header");return}let C=cA("sha1").update(f+mA).digest("base64");if(m.headers["sec-websocket-accept"]!==C){We(t,v,"Invalid Sec-WebSocket-Accept header");return}let A=m.headers["sec-websocket-protocol"],I;if(A!==void 0?h.size?h.has(A)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":h.size&&(I="Server sent no subprotocol"),I){We(t,v,I);return}A&&(t._protocol=A);let k=m.headers["sec-websocket-extensions"];if(k!==void 0){if(!g){We(t,v,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=TA(k)}catch{We(t,v,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(O);if(B.length!==1||B[0]!==jt.extensionName){We(t,v,"Server indicated an extension that was not requested");return}try{g.accept(O[jt.extensionName])}catch{We(t,v,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[jt.extensionName]=g}t.setSocket(v,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(_,t):_.end()}function no(t,e){t._readyState=Se.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function SA(t){return t.path=t.socketPath,Hp.connect(t)}function IA(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Hp.isIP(t.host)?"":t.host),lA.connect(t)}function We(t,e,n){t._readyState=Se.CLOSING;let r=new Error(n);Error.captureStackTrace(r,We),e.setHeader?(e[$p]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(no,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function vl(t,e,n){if(e){let r=pA(e)?e.size:CA(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Lt[t.readyState]})`);process.nextTick(n,r)}}function wA(t,e){let n=this[Ne];n._closeFrameReceived=!0,n._closeCode=t,e.length===0?n._closeMessage=kr:(n._closeMessage=Buffer.allocUnsafeSlow(e.length),n._closeMessage.set(e)),n._socket[Ne]!==void 0&&(n._socket.removeListener("data",ro),process.nextTick(Jp,n._socket),t===1005?n.close():n.close(t,e))}function RA(){let t=this[Ne];t.isPaused||t._socket.resume()}function PA(t){let e=this[Ne];e._socket[Ne]!==void 0&&(e._socket.removeListener("data",ro),process.nextTick(Jp,e._socket),e.close(t[_A])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Bp(){this[Ne].emitClose()}function kA(t,e){this[Ne].emit("message",t,e)}function xA(t){let e=this[Ne];e._autoPong&&e.pong(t,!this._isServer,Vp),e.emit("ping",t)}function NA(t){this[Ne].emit("pong",t)}function Jp(t){t.resume()}function DA(t){let e=this[Ne];e.readyState!==Se.CLOSED&&(e.readyState===Se.OPEN&&(e._readyState=Se.CLOSING,Wp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Wp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Kp(){let t=this[Ne];if(this.removeListener("close",Kp),this.removeListener("data",ro),this.removeListener("end",Yp),t._readyState=Se.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ne]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Bp),t._receiver.on("finish",Bp))}function ro(t){this[Ne]._receiver.write(t)||this.pause()}function Yp(){let t=this[Ne];t._readyState=Se.CLOSING,t._receiver.end(),this.end()}function zp(){let t=this[Ne];this.removeListener("error",zp),this.on("error",Vp),t&&(t._readyState=Se.CLOSING,this.destroy())}});var th=V((DM,eh)=>{"use strict";var NM=io(),{Duplex:bA}=K("stream");function Zp(t){t.emit("close")}function MA(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jp(t){this.removeListener("error",jp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function UA(t,e){let n=!0,r=new bA({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let u=!a&&r._readableState.objectMode?o.toString():o;r.push(u)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(Zp,r);return}let a=!1;t.once("error",function(c){a=!0,o(c)}),t.once("close",function(){a||o(i),process.nextTick(Zp,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,a)});return}t.send(i,a)},r.on("end",MA),r.on("error",jp),r}eh.exports=UA});var El=V((bM,nh)=>{"use strict";var{tokenChars:GA}=Jn();function OA(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(r===-1&&GA[a]===1)n===-1&&(n=i);else if(i!==0&&(a===32||a===9))r===-1&&n!==-1&&(r=i);else if(a===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let u=t.slice(n,r);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}nh.exports={parse:OA}});var uh=V((UM,lh)=>{"use strict";var LA=K("events"),oo=K("http"),{Duplex:MM}=K("stream"),{createHash:qA}=K("crypto"),rh=eo(),En=Xn(),FA=El(),BA=io(),{CLOSE_TIMEOUT:HA,GUID:VA,kWebSocket:$A}=Ut(),XA=/^[+/0-9A-Za-z]{22}==$/,ih=0,oh=1,ah=2,Tl=class extends LA{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:HA,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:BA,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=oo.createServer((r,i)=>{let o=oo.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=JA(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ih}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===ah){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xr,this);return}if(e&&this.once("close",e),this._state!==oh)if(this._state=oh,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xr,this):process.nextTick(xr,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{xr(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",sh);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Tn(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Tn(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!XA.test(o)){Tn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Tn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Nr(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=FA.parse(c)}catch{Tn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let h=new En({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=rh.parse(f);g[En.extensionName]&&(h.accept(g[En.extensionName]),p[En.extensionName]=h)}catch{Tn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(g,_,m,v)=>{if(!g)return Nr(n,_||401,m,v);this.completeUpgrade(p,o,d,e,n,r,i)});return}if(!this.options.verifyClient(h))return Nr(n,401)}this.completeUpgrade(p,o,d,e,n,r,i)}completeUpgrade(e,n,r,i,o,a,u){if(!o.readable||!o.writable)return o.destroy();if(o[$A])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ih)return Nr(o,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qA("sha1").update(n+VA).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;p&&(d.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[En.extensionName]){let p=e[En.extensionName].params,h=rh.format({[En.extensionName]:[p]});d.push(`Sec-WebSocket-Extensions: ${h}`),f._extensions=e}this.emit("headers",d,i),o.write(d.concat(`\r
|
|
31
|
+
`).join(`\r
|
|
32
|
+
`)),o.removeListener("error",sh),f.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(xr,this)})),u(f,i)}};lh.exports=Tl;function JA(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function xr(t){t._state=ah,t.emit("close")}function sh(){this.destroy()}function Nr(t,e,n,r){n=n||oo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${oo.STATUS_CODES[e]}\r
|
|
33
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
34
|
+
`)+`\r
|
|
35
|
+
\r
|
|
36
|
+
`+n)}function Tn(t,e,n,r,i,o){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,Tn),t.emit("wsClientError",a,n,e)}else Nr(n,r,i,o)}});var Kg=Ct(Ac(),1),Yg=Ct(sp(),1);import{createWriteStream as tS}from"fs";import*as qo from"fs/promises";import{writeFile as nS}from"fs/promises";import{Readable as rS}from"node:stream";import{finished as iS}from"node:stream/promises";var WA=Ct(th(),1),KA=Ct(eo(),1),YA=Ct(Xn(),1),zA=Ct(fl(),1),QA=Ct(ml(),1),ZA=Ct(El(),1),Cl=Ct(io(),1),jA=Ct(uh(),1);import*as zg from"path";var Qg,Zg;function FM(t){Qg=t.geminiUrl,Zg=t.vertexUrl}function oS(){return{geminiUrl:Qg,vertexUrl:Zg}}function sS(t,e,n,r){var i,o;if(!t?.baseUrl){let a=oS();return e?(i=a.vertexUrl)!==null&&i!==void 0?i:n:(o=a.geminiUrl)!==null&&o!==void 0?o:r}return t.baseUrl}var vt=class{};function W(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(r,i)=>{if(e&&Object.prototype.hasOwnProperty.call(e,i)){let o=e[i];return o!=null?String(o):""}else{if(i==="api_version")return r;throw new Error(`Key '${i}' not found in valueMap.`)}})}function l(t,e,n){for(let o=0;o<e.length-1;o++){let a=e[o];if(a.endsWith("[]")){let u=a.slice(0,-2);if(!(u in t))if(Array.isArray(n))t[u]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(t[u])){let c=t[u];if(Array.isArray(n))for(let d=0;d<c.length;d++){let f=c[d];l(f,e.slice(o+1),n[d])}else for(let d of c)l(d,e.slice(o+1),n)}return}else if(a.endsWith("[0]")){let u=a.slice(0,-3);u in t||(t[u]=[{}]);let c=t[u];l(c[0],e.slice(o+1),n);return}(!t[a]||typeof t[a]!="object")&&(t[a]={}),t=t[a]}let r=e[e.length-1],i=t[r];if(i!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===i)return;if(typeof i=="object"&&typeof n=="object"&&i!==null&&n!==null)Object.assign(i,n);else throw new Error(`Cannot set value for an existing key. Key: ${r}`)}else r==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(t,n):t[r]=n}function s(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self")return t;for(let r=0;r<e.length;r++){if(typeof t!="object"||t===null)return n;let i=e[r];if(i.endsWith("[]")){let o=i.slice(0,-2);if(o in t){let a=t[o];return Array.isArray(a)?a.map(u=>s(u,e.slice(r+1),n)):n}else return n}else t=t[i]}return t}catch(r){if(r instanceof TypeError)return n;throw r}}function aS(t,e){for(let[n,r]of Object.entries(e)){let i=n.split("."),o=r.split("."),a=new Set,u=-1;for(let c=0;c<i.length;c++)if(i[c]==="*"){u=c;break}if(u!==-1&&o.length>u)for(let c=u;c<o.length;c++){let d=o[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&a.add(d)}wl(t,i,o,0,a)}}function wl(t,e,n,r,i){if(r>=e.length||typeof t!="object"||t===null)return;let o=e[r];if(o.endsWith("[]")){let a=o.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(let c of u[a])wl(c,e,n,r+1,i)}else if(o==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!i.has(d)),c={};for(let d of u)c[d]=a[d];for(let[d,f]of Object.entries(c)){let p=[];for(let h of n.slice(r))h==="*"?p.push(d):p.push(h);l(a,p,f)}for(let d of u)delete a[d]}}else{let a=t;o in a&&wl(a[o],e,n,r+1,i)}}function ac(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function lS(t){let e={},n=s(t,["operationName"]);n!=null&&l(e,["operationName"],n);let r=s(t,["resourceName"]);return r!=null&&l(e,["_url","resourceName"],r),e}function uS(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],dS(a)),e}function cS(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],fS(a)),e}function dS(t){let e={},n=s(t,["generatedSamples"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(a=>pS(a))),l(e,["generatedVideos"],o)}let r=s(t,["raiMediaFilteredCount"]);r!=null&&l(e,["raiMediaFilteredCount"],r);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function fS(t){let e={},n=s(t,["videos"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(a=>hS(a))),l(e,["generatedVideos"],o)}let r=s(t,["raiMediaFilteredCount"]);r!=null&&l(e,["raiMediaFilteredCount"],r);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function pS(t){let e={},n=s(t,["video"]);return n!=null&&l(e,["video"],ES(n)),e}function hS(t){let e={},n=s(t,["_self"]);return n!=null&&l(e,["video"],TS(n)),e}function mS(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function gS(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function _S(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],yS(a)),e}function yS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function lc(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],vS(a)),e}function vS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function ES(t){let e={},n=s(t,["uri"]);n!=null&&l(e,["uri"],n);let r=s(t,["encodedVideo"]);r!=null&&l(e,["videoBytes"],ac(r));let i=s(t,["encoding"]);return i!=null&&l(e,["mimeType"],i),e}function TS(t){let e={},n=s(t,["gcsUri"]);n!=null&&l(e,["uri"],n);let r=s(t,["bytesBase64Encoded"]);r!=null&&l(e,["videoBytes"],ac(r));let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}var ch;(function(t){t.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",t.STATIC="STATIC",t.AGENTIC="AGENTIC"})(ch||(ch={}));var dh;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(dh||(dh={}));var fh;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(fh||(fh={}));var ph;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(ph||(ph={}));var en;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(en||(en={}));var hh;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(hh||(hh={}));var mh;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(mh||(mh={}));var gh;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(gh||(gh={}));var _h;(function(t){t.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",t.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",t.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",t.COMMUNICATION_TOOL="COMMUNICATION_TOOL",t.ACCOUNT_CREATION="ACCOUNT_CREATION",t.DATA_MODIFICATION="DATA_MODIFICATION",t.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",t.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(_h||(_h={}));var yh;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(yh||(yh={}));var vh;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(vh||(vh={}));var Eh;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Eh||(Eh={}));var Th;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Th||(Th={}));var Ch;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ch||(Ch={}));var Ah;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Ah||(Ah={}));var Sh;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(Sh||(Sh={}));var Ih;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(Ih||(Ih={}));var wh;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(wh||(wh={}));var Rh;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(Rh||(Rh={}));var Ph;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(Ph||(Ph={}));var kh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.VERBATIM="VERBATIM",t.SMART="SMART"})(kh||(kh={}));var po;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER",t.CONTINUATION="CONTINUATION",t.MALFORMED_RESPONSE="MALFORMED_RESPONSE"})(po||(po={}));var xh;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(xh||(xh={}));var Nh;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(Nh||(Nh={}));var Dh;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Dh||(Dh={}));var bh;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(bh||(bh={}));var Mh;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Mh||(Mh={}));var Uh;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(Uh||(Uh={}));var Gh;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})(Gh||(Gh={}));var Oh;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Oh||(Oh={}));var ho;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(ho||(ho={}));var Lh;(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(Lh||(Lh={}));var qh;(function(t){t.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",t.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",t.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",t.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",t.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",t.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",t.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",t.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",t.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",t.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",t.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",t.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",t.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(qh||(qh={}));var Fh;(function(t){t.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",t.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",t.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",t.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",t.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(Fh||(Fh={}));var Bh;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Bh||(Bh={}));var Hh;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Hh||(Hh={}));var Vh;(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(Vh||(Vh={}));var $h;(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})($h||($h={}));var Xh;(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(Xh||(Xh={}));var Rl;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(Rl||(Rl={}));var Jh;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(Jh||(Jh={}));var Wh;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(Wh||(Wh={}));var Kh;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(Kh||(Kh={}));var Yh;(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(Yh||(Yh={}));var zh;(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(zh||(zh={}));var Qh;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Qh||(Qh={}));var Zh;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(Zh||(Zh={}));var jh;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(jh||(jh={}));var em;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(em||(em={}));var tm;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH",t.MEDIA_PROCESSING="MEDIA_PROCESSING"})(tm||(tm={}));var Pl;(function(t){t.COLLECTION="COLLECTION"})(Pl||(Pl={}));var nm;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(nm||(nm={}));var mo;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(mo||(mo={}));var rm;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(rm||(rm={}));var im;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(im||(im={}));var om;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(om||(om={}));var sm;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(sm||(sm={}));var am;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(am||(am={}));var lm;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(lm||(lm={}));var um;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(um||(um={}));var cm;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(cm||(cm={}));var dm;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(dm||(dm={}));var fm;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(fm||(fm={}));var pm;(function(t){t.CROP="CROP",t.PAD="PAD"})(pm||(pm={}));var hm;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(hm||(hm={}));var mm;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(mm||(mm={}));var gm;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(gm||(gm={}));var _m;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(_m||(_m={}));var ym;(function(t){t.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",t.IN_PROGRESS="IN_PROGRESS",t.REQUIRES_ACTION="REQUIRES_ACTION",t.IDLE="IDLE"})(ym||(ym={}));var vm;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(vm||(vm={}));var Em;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(Em||(Em={}));var Tm;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Tm||(Tm={}));var Cm;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Cm||(Cm={}));var Am;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(Am||(Am={}));var Sm;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Sm||(Sm={}));var Im;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Im||(Im={}));var wm;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(wm||(wm={}));var Zn;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(Zn||(Zn={}));var Rm=class{},Pm=class{},km=class{},xm=class{};function BM(t,e){return{inlineData:{data:t,mimeType:e}}}function HM(t,e){return{fileData:{fileUri:t,mimeType:e}}}var Nm=class{};function VM(t,e,n){return Object.assign({fileData:{fileUri:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function Dm(t){return{text:t}}function $M(t,e){return{functionCall:{name:t,args:e}}}function XM(t,e,n,r=[]){return{functionResponse:Object.assign({id:t,name:e,response:n},r.length>0&&{parts:r})}}function JM(t,e,n){return Object.assign({inlineData:{data:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function WM(t,e){return{codeExecutionResult:{outcome:t,output:e}}}function KM(t,e){return{executableCode:{code:t,language:e}}}function bm(t){return typeof t=="object"&&t!==null?"fileData"in t||"text"in t||"functionCall"in t||"functionResponse"in t||"inlineData"in t||"videoMetadata"in t||"codeExecutionResult"in t||"executableCode"in t:!1}function jg(t){let e=[];if(typeof t=="string")e.push(Dm(t));else if(bm(t))e.push(t);else if(Array.isArray(t)){if(t.length===0)throw new Error("partOrString cannot be an empty array");for(let n of t)if(typeof n=="string")e.push(Dm(n));else if(bm(n))e.push(n);else throw new Error("element in PartUnion must be a Part object or string")}else throw new Error("partOrString must be a Part object, string, or array");return e}function YM(t){return{role:"user",parts:jg(t)}}function zM(t){return{role:"model",parts:jg(t)}}var Ht=class{constructor(e){let n={};for(let r of e.headers.entries())n[r[0]]=r[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}},kl=class{},go=class{},yt=class{get text(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let d="",f=!1,p=[];for(let h of(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[g,_]of Object.entries(h))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(_!==null||_!==void 0)&&p.push(g);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,d+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?d:void 0}get data(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let d="",f=[];for(let p of(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[h,g]of Object.entries(p))h!=="inlineData"&&(g!==null||g!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(d+=atob(p.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let d=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(d?.length!==0)return d}get executableCode(){var e,n,r,i,o,a,u,c,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let f=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,r,i,o,a,u,c,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let f=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.output}get initialPromptTokenCount(){var e;if(this.usageMetadata)return(e=this.usageMetadata._initialPromptTokenCount)!==null&&e!==void 0?e:this.usageMetadata.promptTokenCount}},_o=class{},xl=class{},Nl=class{},Dl=class{},bl=class{},Ml=class{},yo=class{},vo=class{},Mm=class{},Um=class{},Gm=class{},Om=class{},Lm=class{},Eo=class{},Ul=class{},qm=class{},Gl=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,i,o=e;return n?i=cS(o):i=uS(o),Object.assign(r,i),r}},Fm=class{},Bm=class{},Hm=class{},Ol=class{},To=class{},Ll=class{},Co=class{},Ao=class{},ql=class{},Fl=class{},Bl=class{},Vm=class{},Hl=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,o=_S(e);return Object.assign(r,o),r}},Vl=class{},$l=class{},Xl=class{},Jl=class{},$m=class{},Xm=class{},Jm=class{},So=class{},Wm=class{},Km=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},Ym=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},zm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},Qm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},Zm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},jm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},Wl=class{get text(){var e,n,r;let i="",o=!1,a=[];for(let u of(r=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(let[c,d]of Object.entries(u))c!=="text"&&c!=="thought"&&d!==null&&a.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;o=!0,i+=u.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),o?i:void 0}get data(){var e,n,r;let i="",o=[];for(let a of(r=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(let[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&o.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(i+=atob(a.inlineData.data))}return 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.`),i.length>0?btoa(i):void 0}},eg=class{},tg=class{constructor(){this.functionResponses=[]}},Kl=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},ng=class{},Io=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,o=lc(e);return Object.assign(r,o),r}};function Ee(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){let n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function e_(t,e){let n=Ee(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function t_(t){return Array.isArray(t)?t.map(e=>wo(e)):[wo(t)]}function wo(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function n_(t){let e=wo(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function r_(t){let e=wo(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function rg(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function i_(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>rg(e)):[rg(t)]}function Yl(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function ig(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function og(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function ke(t){if(t==null)throw new Error("ContentUnion is required");return Yl(t)?t:{role:"user",parts:i_(t)}}function uc(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let r=ke(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(t.isVertexAI()){let n=ke(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>ke(n)):[ke(e)]}function Fe(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(ig(t)||og(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[ke(t)]}let e=[],n=[],r=Yl(t[0]);for(let i of t){let o=Yl(i);if(o!=r)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(o)e.push(i);else{if(ig(i)||og(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(i)}}return r||e.push({role:"user",parts:i_(n)}),e}function CS(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1)e.type=Object.values(en).includes(n[0].toUpperCase())?n[0].toUpperCase():en.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let r of n)e.anyOf.push({type:Object.values(en).includes(r.toUpperCase())?r.toUpperCase():en.TYPE_UNSPECIFIED})}}function er(t){let e={},n=["items"],r=["anyOf"],i=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let o=t.anyOf;o!=null&&o.length==2&&(o[0].type==="null"?(e.nullable=!0,t=o[1]):o[1].type==="null"&&(e.nullable=!0,t=o[0])),t.type instanceof Array&&CS(t.type,e);for(let[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(en).includes(u.toUpperCase())?u.toUpperCase():en.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=er(u);else if(r.includes(a)){let c=[];for(let d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(er(d))}e[a]=c}else if(i.includes(a)){let c={};for(let[d,f]of Object.entries(u))c[d]=er(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function cc(t){return er(t)}function dc(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function fc(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function un(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=er(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=er(e.response));return t}function cn(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");let e=[];for(let n of t)e.push(n);return e}function AS(t,e,n,r=1){let i=!e.startsWith(`${n}/`)&&e.split("/").length===r;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:i?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:i?`${n}/${e}`:e}function Xt(t,e){if(typeof e!="string")throw new Error("name must be a string");return AS(t,e,"cachedContents")}function o_(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function Fo(t){return ac(t)}function SS(t){return t!=null&&typeof t=="object"&&"name"in t}function s_(t){return t!=null&&typeof t=="object"&&"video"in t}function a_(t){return t!=null&&typeof t=="object"&&"uri"in t}function pc(t){var e;let n;if(SS(t)&&(n=t.name),!(a_(t)&&(n=t.uri,n===void 0))&&!(s_(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){let i=n.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${n}`);n=i[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function l_(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function u_(t){for(let e of["models","tunedModels","publisherModels"])if(IS(t,e))return t[e];return[]}function IS(t,e){return t!==null&&typeof t=="object"&&e in t}function wS(t,e={}){let n=t,r={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(r.responseJsonSchema=n.outputSchema),e.behavior&&(r.behavior=e.behavior),{functionDeclarations:[r]}}function RS(t,e={}){let n=[],r=new Set;for(let i of t){let o=i.name;if(r.has(o))throw new Error(`Duplicate function name ${o} found in MCP tools. Please ensure function names are unique.`);r.add(o);let a=wS(i,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function c_(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;let r=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(i>0||r!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(r>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function PS(t){if(typeof t!="string")return t;let e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function d_(t){if(typeof t!="object"||t===null)return{};let e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;let i=n.inlinedResponses;if(!Array.isArray(i)||i.length===0)return t;let o=!1;for(let a of i){if(typeof a!="object"||a===null)continue;let c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){o=!0;break}}return o&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function or(t,e){let n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function f_(t){let e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function kS(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function xS(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function NS(t){let e={},n=s(t,["responsesFile"]);n!=null&&l(e,["fileName"],n);let r=s(t,["inlinedResponses","inlinedResponses"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>uI(a))),l(e,["inlinedResponses"],o)}let i=s(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["inlinedEmbedContentResponses"],o)}return e}function DS(t){let e={},n=s(t,["predictionsFormat"]);n!=null&&l(e,["format"],n);let r=s(t,["gcsDestination","outputUriPrefix"]);r!=null&&l(e,["gcsUri"],r);let i=s(t,["bigqueryDestination","outputUri"]);i!=null&&l(e,["bigqueryUri"],i);let o=s(t,["vertexMultimodalDatasetDestination"]);return o!=null&&l(e,["vertexDataset"],EI(o)),e}function bS(t){let e={},n=s(t,["format"]);n!=null&&l(e,["predictionsFormat"],n);let r=s(t,["gcsUri"]);r!=null&&l(e,["gcsDestination","outputUriPrefix"],r);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigqueryDestination","outputUri"],i);let o=s(t,["vertexDataset"]);if(o!=null&&l(e,["vertexMultimodalDatasetDestination"],TI(o)),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function co(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata","displayName"]);r!=null&&l(e,["displayName"],r);let i=s(t,["metadata","state"]);i!=null&&l(e,["state"],f_(i));let o=s(t,["metadata","createTime"]);o!=null&&l(e,["createTime"],o);let a=s(t,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let u=s(t,["metadata","updateTime"]);u!=null&&l(e,["updateTime"],u);let c=s(t,["metadata","model"]);c!=null&&l(e,["model"],c);let d=s(t,["metadata","output"]);return d!=null&&l(e,["dest"],NS(d_(d))),e}function zl(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["displayName"]);r!=null&&l(e,["displayName"],r);let i=s(t,["state"]);i!=null&&l(e,["state"],f_(i));let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["createTime"]);a!=null&&l(e,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(e,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(e,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(e,["updateTime"],d);let f=s(t,["model"]);f!=null&&l(e,["model"],f);let p=s(t,["inputConfig"]);p!=null&&l(e,["src"],MS(p));let h=s(t,["outputConfig"]);h!=null&&l(e,["dest"],DS(d_(h)));let g=s(t,["outputInfo"]);g!=null&&l(e,["outputInfo"],g);let _=s(t,["completionStats"]);return _!=null&&l(e,["completionStats"],_),e}function MS(t){let e={},n=s(t,["instancesFormat"]);n!=null&&l(e,["format"],n);let r=s(t,["gcsSource","uris"]);r!=null&&l(e,["gcsUri"],r);let i=s(t,["bigquerySource","inputUri"]);i!=null&&l(e,["bigqueryUri"],i);let o=s(t,["vertexMultimodalDatasetSource","datasetName"]);return o!=null&&l(e,["vertexDatasetName"],o),e}function US(t,e){let n={};if(s(e,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(e,["fileName"]);r!=null&&l(n,["fileName"],r);let i=s(e,["inlinedRequests"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>lI(t,a))),l(n,["requests","requests"],o)}return n}function GS(t){let e={},n=s(t,["format"]);n!=null&&l(e,["instancesFormat"],n);let r=s(t,["gcsUri"]);r!=null&&l(e,["gcsSource","uris"],r);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigquerySource","inputUri"],i);let o=s(t,["vertexDatasetName"]);if(o!=null&&l(e,["vertexMultimodalDatasetSource","datasetName"],o),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function OS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function LS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function qS(t){let e={},n=s(t,["content"]);n!=null&&l(e,["content"],n);let r=s(t,["citationMetadata"]);r!=null&&l(e,["citationMetadata"],FS(r));let i=s(t,["tokenCount"]);i!=null&&l(e,["tokenCount"],i);let o=s(t,["finishReason"]);o!=null&&l(e,["finishReason"],o);let a=s(t,["groundingMetadata"]);a!=null&&l(e,["groundingMetadata"],a);let u=s(t,["avgLogprobs"]);u!=null&&l(e,["avgLogprobs"],u);let c=s(t,["index"]);c!=null&&l(e,["index"],c);let d=s(t,["logprobsResult"]);d!=null&&l(e,["logprobsResult"],d);let f=s(t,["safetyRatings"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["safetyRatings"],g)}let p=s(t,["urlContextMetadata"]);p!=null&&l(e,["urlContextMetadata"],p);let h=s(t,["continuationToken"]);return h!=null&&l(e,["continuationToken"],h),e}function FS(t){let e={},n=s(t,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),l(e,["citations"],r)}return e}function p_(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>gI(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function BS(t,e){let n={},r=s(t,["displayName"]);if(e!==void 0&&r!=null&&l(e,["batch","displayName"],r),s(t,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["webhookConfig"]);return e!==void 0&&i!=null&&l(e,["batch","webhookConfig"],i),n}function HS(t,e){let n={},r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let i=s(t,["dest"]);if(e!==void 0&&i!=null&&l(e,["outputConfig"],bS(PS(i))),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function sg(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["_url","model"],Ee(t,r));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],US(t,c_(t,i)));let o=s(e,["config"]);return o!=null&&BS(o,n),n}function VS(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],Ee(t,r));let i=s(e,["src"]);i!=null&&l(n,["inputConfig"],GS(c_(t,i)));let o=s(e,["config"]);return o!=null&&HS(o,n),n}function $S(t,e){let n={},r=s(t,["displayName"]);return e!==void 0&&r!=null&&l(e,["batch","displayName"],r),n}function XS(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["_url","model"],Ee(t,r));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],ZS(t,i));let o=s(e,["config"]);return o!=null&&$S(o,n),n}function JS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function WS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function KS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);return o!=null&&l(e,["error"],o),e}function YS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);return o!=null&&l(e,["error"],o),e}function zS(t,e){let n={},r=s(e,["contents"]);if(r!=null){let o=uc(t,r);Array.isArray(o)&&(o=o.map(a=>a)),l(n,["requests[]","request","content"],o)}let i=s(e,["config"]);return i!=null&&(l(n,["_self"],QS(i,n)),aS(n,{"requests[].*":"requests[].request.*"})),n}function QS(t,e){let n={},r=s(t,["taskType"]);e!==void 0&&r!=null&&l(e,["requests[]","taskType"],r);let i=s(t,["title"]);e!==void 0&&i!=null&&l(e,["requests[]","title"],i);let o=s(t,["outputDimensionality"]);if(e!==void 0&&o!=null&&l(e,["requests[]","outputDimensionality"],o),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function ZS(t,e){let n={},r=s(e,["fileName"]);r!=null&&l(n,["file_name"],r);let i=s(e,["inlinedRequests"]);return i!=null&&l(n,["requests"],zS(t,i)),n}function jS(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function eI(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let r=s(t,["mode"]);if(r!=null&&l(e,["mode"],r),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function tI(t,e,n){let r={},i=s(e,["serviceTier"]);n!==void 0&&i!=null&&l(n,["serviceTier"],i);let o=s(e,["systemInstruction"]);n!==void 0&&o!=null&&l(n,["systemInstruction"],p_(ke(o)));let a=s(e,["temperature"]);a!=null&&l(r,["temperature"],a);let u=s(e,["topP"]);u!=null&&l(r,["topP"],u);let c=s(e,["topK"]);c!=null&&l(r,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(r,["candidateCount"],d);let f=s(e,["maxOutputTokens"]);f!=null&&l(r,["maxOutputTokens"],f);let p=s(e,["stopSequences"]);p!=null&&l(r,["stopSequences"],p);let h=s(e,["responseLogprobs"]);h!=null&&l(r,["responseLogprobs"],h);let g=s(e,["logprobs"]);g!=null&&l(r,["logprobs"],g);let _=s(e,["presencePenalty"]);_!=null&&l(r,["presencePenalty"],_);let m=s(e,["frequencyPenalty"]);m!=null&&l(r,["frequencyPenalty"],m);let v=s(e,["seed"]);v!=null&&l(r,["seed"],v);let y=s(e,["responseMimeType"]);y!=null&&l(r,["responseMimeType"],y);let E=s(e,["responseSchema"]);E!=null&&l(r,["responseSchema"],cc(E));let C=s(e,["responseJsonSchema"]);if(C!=null&&l(r,["responseJsonSchema"],C),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let A=s(e,["safetySettings"]);if(n!==void 0&&A!=null){let _e=A;Array.isArray(_e)&&(_e=_e.map(pe=>_I(pe))),l(n,["safetySettings"],_e)}let I=s(e,["tools"]);if(n!==void 0&&I!=null){let _e=cn(I);Array.isArray(_e)&&(_e=_e.map(pe=>vI(un(pe)))),l(n,["tools"],_e)}let k=s(e,["toolConfig"]);n!==void 0&&k!=null&&l(n,["toolConfig"],yI(k));let O=s(e,["labels"]);n!==void 0&&O!=null&&l(n,["labels"],O);let B=s(e,["cachedContent"]);n!==void 0&&B!=null&&l(n,["cachedContent"],Xt(t,B));let D=s(e,["responseModalities"]);D!=null&&l(r,["responseModalities"],D);let q=s(e,["mediaResolution"]);q!=null&&l(r,["mediaResolution"],q);let H=s(e,["speechConfig"]);if(H!=null&&l(r,["speechConfig"],dc(H)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let J=s(e,["thinkingConfig"]);J!=null&&l(r,["thinkingConfig"],J);let ne=s(e,["audioTranscriptionConfig"]);ne!=null&&l(r,["audioTranscriptionConfig"],ne);let L=s(e,["imageConfig"]);L!=null&&l(r,["imageConfig"],aI(L));let X=s(e,["enableEnhancedCivicAnswers"]);if(X!=null&&l(r,["enableEnhancedCivicAnswers"],X),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Z=s(e,["continuationToken"]);if(n!==void 0&&Z!=null&&l(n,["continuationToken"],Z),s(e,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ge=s(e,["store"]);return n!==void 0&&ge!=null&&l(n,["store"],ge),r}function nI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["candidates"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>qS(f))),l(e,["candidates"],d)}let i=s(t,["modelVersion"]);i!=null&&l(e,["modelVersion"],i);let o=s(t,["promptFeedback"]);o!=null&&l(e,["promptFeedback"],o);let a=s(t,["responseId"]);a!=null&&l(e,["responseId"],a);let u=s(t,["usageMetadata"]);u!=null&&l(e,["usageMetadata"],u);let c=s(t,["modelStatus"]);return c!=null&&l(e,["modelStatus"],c),e}function rI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function iI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],or(t,r)),n}function oI(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],xS(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function sI(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function aI(t){let e={},n=s(t,["aspectRatio"]);n!=null&&l(e,["aspectRatio"],n);let r=s(t,["imageSize"]);if(r!=null&&l(e,["imageSize"],r),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function lI(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["request","model"],Ee(t,r));let i=s(e,["contents"]);if(i!=null){let u=Fe(i);Array.isArray(u)&&(u=u.map(c=>p_(c))),l(n,["request","contents"],u)}let o=s(e,["metadata"]);o!=null&&l(n,["metadata"],o);let a=s(e,["config"]);return a!=null&&l(n,["request","generationConfig"],tI(t,a,s(n,["request"],{}))),n}function uI(t){let e={},n=s(t,["response"]);n!=null&&l(e,["response"],nI(n));let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["error"]);return i!=null&&l(e,["error"],i),e}function cI(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);if(e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),s(t,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function dI(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);e!==void 0&&i!=null&&l(e,["_query","pageToken"],i);let o=s(t,["filter"]);return e!==void 0&&o!=null&&l(e,["_query","filter"],o),n}function fI(t){let e={},n=s(t,["config"]);return n!=null&&cI(n,e),e}function pI(t){let e={},n=s(t,["config"]);return n!=null&&dI(n,e),e}function hI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["operations"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>co(a))),l(e,["batchJobs"],o)}return e}function mI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["batchPredictionJobs"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>zl(a))),l(e,["batchJobs"],o)}return e}function gI(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],jS(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function _I(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function yI(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],eI(n));let r=s(t,["retrievalConfig"]);r!=null&&l(e,["retrievalConfig"],r);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function vI(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],oI(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],sI(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function EI(t){let e={},n=s(t,["bigqueryDestination","outputUri"]);n!=null&&l(e,["bigqueryDestination"],n);let r=s(t,["displayName"]);return r!=null&&l(e,["displayName"],r),e}function TI(t){let e={},n=s(t,["bigqueryDestination"]);n!=null&&l(e,["bigqueryDestination","outputUri"],n);let r=s(t,["displayName"]);return r!=null&&l(e,["displayName"],r),e}var Vt;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents",t.PAGED_ITEM_SKILLS="skills"})(Vt||(Vt={}));var $t=class{constructor(e,n,r,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,r,i)}init(e,n,r){var i,o;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!r||Object.keys(r).length===0?a={config:{}}:typeof r=="object"?a=Object.assign({},r):a=r,a.config&&(a.config.pageToken=n.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(o=(i=a.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 new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};var Ql=class extends vt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new $t(Vt.PAGED_ITEM_BATCH_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){let n=sg(this.apiClient,e),r=n._url,i=W("{model}:batchGenerateContent",r),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(let f of c){let p=Object.assign({},f);if(p.systemInstruction){let h=p.systemInstruction;delete p.systemInstruction;let g=p.request;g.systemInstruction=h,p.request=g}d.push(p)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:i,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){let r=n?Object.assign({},n):{},i=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${i}`),r.dest===void 0){let o=this.getGcsUri(e),a=this.getBigqueryUri(e);if(o)o.endsWith(".jsonl")?r.dest=`${o.slice(0,-6)}/dest`:r.dest=`${o}_dest_${i}`;else if(a)r.dest=`${a}_dest_${i}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return r}async createInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=VS(this.apiClient,e);return u=W("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>zl(f))}else{let d=sg(this.apiClient,e);return u=W("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>co(f))}}async createEmbeddingsInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=XS(this.apiClient,e);return o=W("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>co(c))}}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=iI(this.apiClient,e);return u=W("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>zl(f))}else{let d=rI(this.apiClient,e);return u=W("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>co(f))}}async cancel(e){var n,r,i,o;let a="",u={};if(this.apiClient.isVertexAI()){let c=LS(this.apiClient,e);a=W("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}else{let c=OS(this.apiClient,e);a=W("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(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 n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=pI(e);return u=W("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=mI(f),h=new So;return Object.assign(h,p),h})}else{let d=fI(e);return u=W("batches",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=hI(f),h=new So;return Object.assign(h,p),h})}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=WS(this.apiClient,e);return u=W("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>YS(f))}else{let d=JS(this.apiClient,e);return u=W("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>KS(f))}}};function CI(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function ag(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>JI(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function lg(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>WI(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function AI(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let f=Fe(a);Array.isArray(f)&&(f=f.map(p=>ag(p))),l(e,["contents"],f)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],ag(ke(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>zI(p))),l(e,["tools"],f)}let d=s(t,["toolConfig"]);if(e!==void 0&&d!=null&&l(e,["toolConfig"],KI(d)),s(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function SI(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let p=Fe(a);Array.isArray(p)&&(p=p.map(h=>lg(h))),l(e,["contents"],p)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],lg(ke(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>QI(h))),l(e,["tools"],p)}let d=s(t,["toolConfig"]);e!==void 0&&d!=null&&l(e,["toolConfig"],YI(d));let f=s(t,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),n}function II(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],e_(t,r));let i=s(e,["config"]);return i!=null&&AI(i,n),n}function wI(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],e_(t,r));let i=s(e,["config"]);return i!=null&&SI(i,n),n}function RI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],Xt(t,r)),n}function PI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],Xt(t,r)),n}function kI(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function xI(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function NI(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function DI(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let r=s(t,["mode"]);if(r!=null&&l(e,["mode"],r),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function bI(t){let e={},n=s(t,["fileData"]);n!=null&&l(e,["fileData"],n);let r=s(t,["inlineData"]);if(r!=null&&l(e,["inlineData"],r),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function MI(t){let e={},n=s(t,["id"]);n!=null&&l(e,["id"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["parts"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>bI(c))),l(e,["parts"],u)}let o=s(t,["response"]);o!=null&&l(e,["response"],o);let a=s(t,["scheduling"]);if(a!=null&&l(e,["scheduling"],a),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function UI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],Xt(t,r)),n}function GI(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],Xt(t,r)),n}function OI(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],CI(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function LI(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function qI(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function FI(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function BI(t){let e={},n=s(t,["config"]);return n!=null&&qI(n,e),e}function HI(t){let e={},n=s(t,["config"]);return n!=null&&FI(n,e),e}function VI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["cachedContents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["cachedContents"],o)}return e}function $I(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["cachedContents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["cachedContents"],o)}return e}function XI(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function JI(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],NI(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function WI(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=s(t,["executableCode"]);o!=null&&l(e,["executableCode"],o);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],MI(c));let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let g=s(t,["videoMetadata"]);if(g!=null&&l(e,["videoMetadata"],g),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);_!=null&&l(e,["mediaProcessing"],_);let m=s(t,["speechMetadata"]);return m!=null&&l(e,["speechMetadata"],m),e}function KI(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],DI(n));let r=s(t,["retrievalConfig"]);r!=null&&l(e,["retrievalConfig"],r);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function YI(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],n);let r=s(t,["retrievalConfig"]);if(r!=null&&l(e,["retrievalConfig"],r),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function zI(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],OI(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],LI(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function QI(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let r=s(t,["googleMaps"]);r!=null&&l(e,["googleMaps"],r);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(m=>XI(m))),l(e,["mcpServers"],_)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],a);let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(m=>m)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let g=s(t,["urlContext"]);if(g!=null&&l(e,["urlContext"],g),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function ZI(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function jI(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function ew(t,e){let n={},r=s(e,["name"]);r!=null&&l(n,["_url","name"],Xt(t,r));let i=s(e,["config"]);return i!=null&&ZI(i,n),n}function tw(t,e){let n={},r=s(e,["name"]);r!=null&&l(n,["_url","name"],Xt(t,r));let i=s(e,["config"]);return i!=null&&jI(i,n),n}var Zl=class extends vt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new $t(Vt.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=wI(this.apiClient,e);return u=W("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=II(this.apiClient,e);return u=W("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=GI(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=UI(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=PI(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=xI(f),h=new Co;return Object.assign(h,p),h})}else{let d=RI(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=kI(f),h=new Co;return Object.assign(h,p),h})}}async update(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=tw(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=ew(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=HI(e);return u=W("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=$I(f),h=new Ao;return Object.assign(h,p),h})}else{let d=BI(e);return u=W("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=VI(f),h=new Ao;return Object.assign(h,p),h})}}};function Ie(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function ug(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function se(t){return this instanceof se?(this.v=t,this):new se(t)}function Bt(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),i[Symbol.asyncIterator]=function(){return this},i;function a(g){return function(_){return Promise.resolve(_).then(g,p)}}function u(g,_){r[g]&&(i[g]=function(m){return new Promise(function(v,y){o.push([g,m,v,y])>1||c(g,m)})},_&&(i[g]=_(i[g])))}function c(g,_){try{d(r[g](_))}catch(m){h(o[0][3],m)}}function d(g){g.value instanceof se?Promise.resolve(g.value.v).then(f,p):h(o[0][2],g)}function f(g){c("next",g)}function p(g){c("throw",g)}function h(g,_){g(_),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Cn(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ug=="function"?ug(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(a){return new Promise(function(u,c){a=t[o](a),i(u,c,a.done,a.value)})}}function i(o,a,u,c){Promise.resolve(c).then(function(d){o({value:d,done:u})},a)}}function nw(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:h_(n)}function h_(t){if(t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function rw(t){if(t.length!==0){for(let e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function cg(t){if(t===void 0||t.length===0)return[];let e=[],n=t.length,r=0;for(;r<n;)if(t[r].role==="user")e.push(t[r]),r++;else{let i=[],o=!0;for(;r<n&&t[r].role==="model";)i.push(t[r]),o&&!h_(t[r])&&(o=!1),r++;o?e.push(...i):e.pop()}return e}var jl=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new eu(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},eu=class{constructor(e,n,r,i={},o=[]){this.apiClient=e,this.modelsModule=n,this.model=r,this.config=i,this.history=o,this.sendPromise=Promise.resolve(),rw(o)}async sendMessage(e){var n;await this.sendPromise;let r=ke(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=e.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var o,a,u;let c=await i,d=(a=(o=c.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,p=this.getHistory(!0).length,h=[];f!=null&&(h=(u=f.slice(p))!==null&&u!==void 0?u:[]);let g=d?[d]:[];this.recordHistory(r,g,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let r=ke(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=i.then(()=>{}).catch(()=>{});let o=await i;return this.processStreamResponse(o,r)}getHistory(e=!1){let n=e?cg(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Bt(this,arguments,function*(){var i,o,a,u,c,d,f,p;let h=[],g=!0,_=!1;try{for(var m=!0,v=Cn(e),y;y=yield se(v.next()),i=y.done,!i;m=!0){u=y.value,m=!1;let E=u;if(nw(E)){let C=(d=(c=E.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;C!==void 0&&h.push(C)}else g=!1;((p=(f=E.candidates)===null||f===void 0?void 0:f[0])===null||p===void 0?void 0:p.finishReason)!==void 0&&(_=!0),yield yield se(E)}}catch(E){o={error:E}}finally{try{!m&&!i&&(a=v.return)&&(yield se(a.call(v)))}finally{if(o)throw o.error}}this.recordHistory(n,g&&_?h:[])})}recordHistory(e,n,r){let i=[];n.length>0&&n.every(o=>o.role!==void 0)?i=n:i.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...cg(r)):this.history.push(e),this.history.push(...i)}};var Gr=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}},Ro=class t extends Error{constructor(e){var n;super(e.message,{cause:e.cause}),this.name="ContinuationInterruptedError",typeof this.cause>"u"&&(this.cause=e.cause),this.partialInteraction=e.partialInteraction,this.continuationToken=e.continuationToken,this.interactionId=e.interactionId,this.continuationIds=[...(n=e.continuationIds)!==null&&n!==void 0?n:[]],Object.setPrototypeOf(this,t.prototype)}};function iw(t){let e={},n=s(t,["file"]);return n!=null&&l(e,["file"],n),e}function ow(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function sw(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],pc(n)),e}function aw(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function lw(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],pc(n)),e}function uw(t){let e={},n=s(t,["uris"]);return n!=null&&l(e,["uris"],n),e}function cw(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function dw(t){let e={},n=s(t,["config"]);return n!=null&&cw(n,e),e}function fw(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["files"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["files"],o)}return e}function pw(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["files"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["files"],i)}return e}var hw=class extends vt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new $t(Vt.PAGED_ITEM_FILES,r=>this.listInternal(r),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=dw(e);return o=W("files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=fw(c),f=new Vl;return Object.assign(f,d),f})}}async createInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=iw(e);return o=W("upload/{api_version}/files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=ow(c),f=new $l;return Object.assign(f,d),f})}}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=lw(e);return o=W("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=sw(e);return o=W("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=aw(c),f=new Xl;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=uw(e);return o=W("files:register",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=pw(c),f=new Jl;return Object.assign(f,d),f})}}};function mw(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function m_(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>Ow(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function g_(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>Lw(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function gw(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function _w(t){let e={},n=s(t,["fileData"]);n!=null&&l(e,["fileData"],n);let r=s(t,["inlineData"]);if(r!=null&&l(e,["inlineData"],r),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function yw(t){let e={},n=s(t,["id"]);n!=null&&l(e,["id"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["parts"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>_w(c))),l(e,["parts"],u)}let o=s(t,["response"]);o!=null&&l(e,["response"],o);let a=s(t,["scheduling"]);if(a!=null&&l(e,["scheduling"],a),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function vw(t){let e={},n=s(t,["modelSelectionConfig"]);n!=null&&l(e,["modelConfig"],n);let r=s(t,["responseJsonSchema"]);r!=null&&l(e,["responseJsonSchema"],r);let i=s(t,["audioTranscriptionConfig"]);i!=null&&l(e,["audioTranscriptionConfig"],i);let o=s(t,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let a=s(t,["candidateCount"]);a!=null&&l(e,["candidateCount"],a);let u=s(t,["enableAffectiveDialog"]);u!=null&&l(e,["enableAffectiveDialog"],u);let c=s(t,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(t,["logprobs"]);d!=null&&l(e,["logprobs"],d);let f=s(t,["maxOutputTokens"]);f!=null&&l(e,["maxOutputTokens"],f);let p=s(t,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let h=s(t,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let g=s(t,["responseFormat"]);if(g!=null){let H=g;Array.isArray(H)&&(H=H.map(J=>J)),l(e,["responseFormat"],H)}let _=s(t,["responseLogprobs"]);_!=null&&l(e,["responseLogprobs"],_);let m=s(t,["responseMimeType"]);m!=null&&l(e,["responseMimeType"],m);let v=s(t,["responseModalities"]);v!=null&&l(e,["responseModalities"],v);let y=s(t,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);let E=s(t,["routingConfig"]);E!=null&&l(e,["routingConfig"],E);let C=s(t,["seed"]);C!=null&&l(e,["seed"],C);let A=s(t,["speechConfig"]);A!=null&&l(e,["speechConfig"],__(A));let I=s(t,["stopSequences"]);I!=null&&l(e,["stopSequences"],I);let k=s(t,["temperature"]);k!=null&&l(e,["temperature"],k);let O=s(t,["thinkingConfig"]);O!=null&&l(e,["thinkingConfig"],O);let B=s(t,["topK"]);B!=null&&l(e,["topK"],B);let D=s(t,["topP"]);if(D!=null&&l(e,["topP"],D),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let q=s(t,["translationConfig"]);return q!=null&&l(e,["translationConfig"],q),e}function Ew(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],mw(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Tw(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function Cw(t){let e={},n=s(t,["systemInstruction"]);n!=null&&l(e,["systemInstruction"],m_(ke(n)));let r=s(t,["tools"]);return r!=null&&l(e,["tools"],Sw(r)),e}function Aw(t){let e={},n=s(t,["systemInstruction"]);n!=null&&l(e,["systemInstruction"],g_(ke(n)));let r=s(t,["tools"]);return r!=null&&l(e,["tools"],Iw(r)),e}function Sw(t){let e={},n=s(t,["tools"]);if(n!=null){let r=cn(n);Array.isArray(r)&&(r=r.map(i=>y_(un(i)))),l(e,["tools"],r)}return e}function Iw(t){let e={},n=s(t,["tools"]);if(n!=null){let r=cn(n);Array.isArray(r)&&(r=r.map(i=>v_(un(i)))),l(e,["tools"],r)}return e}function ww(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],r);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],fc(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],m_(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let q=cn(m);Array.isArray(q)&&(q=q.map(H=>y_(un(H)))),l(e,["setup","tools"],q)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],Bw(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let A=s(t,["contextWindowCompression"]);e!==void 0&&A!=null&&l(e,["setup","contextWindowCompression"],A);let I=s(t,["proactivity"]);if(e!==void 0&&I!=null&&l(e,["setup","proactivity"],I),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let k=s(t,["avatarConfig"]);e!==void 0&&k!=null&&l(e,["setup","avatarConfig"],k);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let q=O;Array.isArray(q)&&(q=q.map(H=>Fw(H))),l(e,["setup","safetySettings"],q)}let B=s(t,["translationConfig"]);e!==void 0&&B!=null&&l(e,["setup","generationConfig","translationConfig"],B);let D=s(t,["labels"]);return e!==void 0&&D!=null&&l(e,["setup","labels"],D),n}function Rw(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],vw(r));let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],__(fc(p)));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],g_(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let H=cn(m);Array.isArray(H)&&(H=H.map(J=>v_(un(J)))),l(e,["setup","tools"],H)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],v);let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let A=s(t,["contextWindowCompression"]);e!==void 0&&A!=null&&l(e,["setup","contextWindowCompression"],A);let I=s(t,["proactivity"]);e!==void 0&&I!=null&&l(e,["setup","proactivity"],I);let k=s(t,["explicitVadSignal"]);e!==void 0&&k!=null&&l(e,["setup","explicitVadSignal"],k);let O=s(t,["avatarConfig"]);e!==void 0&&O!=null&&l(e,["setup","avatarConfig"],O);let B=s(t,["safetySettings"]);if(e!==void 0&&B!=null){let H=B;Array.isArray(H)&&(H=H.map(J=>J)),l(e,["setup","safetySettings"],H)}let D=s(t,["translationConfig"]);e!==void 0&&D!=null&&l(e,["setup","generationConfig","translationConfig"],D);let q=s(t,["labels"]);return e!==void 0&&q!=null&&l(e,["setup","labels"],q),n}function Pw(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],Ee(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],ww(i,n)),n}function kw(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],Ee(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],Rw(i,n)),n}function xw(t){let e={},n=s(t,["musicGenerationConfig"]);return n!=null&&l(e,["musicGenerationConfig"],n),e}function Nw(t){let e={},n=s(t,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),l(e,["weightedPrompts"],r)}return e}function Dw(t){let e={},n=s(t,["media"]);if(n!=null){let d=t_(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let r=s(t,["audio"]);r!=null&&l(e,["audio"],r_(r));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let o=s(t,["video"]);o!=null&&l(e,["video"],n_(o));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function bw(t){let e={},n=s(t,["media"]);if(n!=null){let d=t_(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let r=s(t,["audio"]);r!=null&&l(e,["audio"],r_(r));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let o=s(t,["video"]);o!=null&&l(e,["video"],n_(o));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function Mw(t){let e={},n=s(t,["setupComplete"]);n!=null&&l(e,["setupComplete"],n);let r=s(t,["serverContent"]);r!=null&&l(e,["serverContent"],r);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolCallCancellation"]);o!=null&&l(e,["toolCallCancellation"],o);let a=s(t,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],Vw(a));let u=s(t,["goAway"]);u!=null&&l(e,["goAway"],u);let c=s(t,["sessionResumptionUpdate"]);c!=null&&l(e,["sessionResumptionUpdate"],c);let d=s(t,["voiceActivityDetectionSignal"]);d!=null&&l(e,["voiceActivityDetectionSignal"],d);let f=s(t,["voiceActivity"]);return f!=null&&l(e,["voiceActivity"],$w(f)),e}function Uw(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Gw(t){let e={},n=s(t,["speakerVoiceConfigs"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>Hw(i))),l(e,["speakerVoiceConfigs"],r)}return e}function Ow(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],gw(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function Lw(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=s(t,["executableCode"]);o!=null&&l(e,["executableCode"],o);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],yw(c));let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let g=s(t,["videoMetadata"]);if(g!=null&&l(e,["videoMetadata"],g),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);_!=null&&l(e,["mediaProcessing"],_);let m=s(t,["speechMetadata"]);return m!=null&&l(e,["speechMetadata"],m),e}function qw(t){let e={},n=s(t,["mimeType"]);n!=null&&l(e,["mimeType"],n);let r=s(t,["voiceSampleAudio"]);if(r!=null&&l(e,["voiceSampleAudio"],r),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Fw(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function Bw(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Hw(t){let e={},n=s(t,["speaker"]);n!=null&&l(e,["speaker"],n);let r=s(t,["voiceConfig"]);return r!=null&&l(e,["voiceConfig"],E_(r)),e}function __(t){let e={},n=s(t,["voiceConfig"]);n!=null&&l(e,["voiceConfig"],E_(n));let r=s(t,["languageCode"]);r!=null&&l(e,["languageCode"],r);let i=s(t,["multiSpeakerVoiceConfig"]);return i!=null&&l(e,["multiSpeakerVoiceConfig"],Gw(i)),e}function y_(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],Ew(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],Tw(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function v_(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let r=s(t,["googleMaps"]);r!=null&&l(e,["googleMaps"],r);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(m=>Uw(m))),l(e,["mcpServers"],_)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],a);let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(m=>m)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let g=s(t,["urlContext"]);if(g!=null&&l(e,["urlContext"],g),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Vw(t){let e={},n=s(t,["candidatesTokenCount"]);n!=null&&l(e,["responseTokenCount"],n);let r=s(t,["candidatesTokensDetails"]);if(r!=null){let g=r;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["responseTokensDetails"],g)}let i=s(t,["cacheTokensDetails"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["cacheTokensDetails"],g)}let o=s(t,["cachedContentTokenCount"]);o!=null&&l(e,["cachedContentTokenCount"],o);let a=s(t,["promptTokenCount"]);a!=null&&l(e,["promptTokenCount"],a);let u=s(t,["promptTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["promptTokensDetails"],g)}let c=s(t,["thoughtsTokenCount"]);c!=null&&l(e,["thoughtsTokenCount"],c);let d=s(t,["toolUsePromptTokenCount"]);d!=null&&l(e,["toolUsePromptTokenCount"],d);let f=s(t,["toolUsePromptTokensDetails"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["toolUsePromptTokensDetails"],g)}let p=s(t,["totalTokenCount"]);p!=null&&l(e,["totalTokenCount"],p);let h=s(t,["trafficType"]);return h!=null&&l(e,["trafficType"],h),e}function $w(t){let e={},n=s(t,["type"]);n!=null&&l(e,["voiceActivityType"],n);let r=s(t,["audioOffset"]);return r!=null&&l(e,["audioOffset"],r),e}function E_(t){let e={},n=s(t,["replicatedVoiceConfig"]);n!=null&&l(e,["replicatedVoiceConfig"],qw(n));let r=s(t,["prebuiltVoiceConfig"]);r!=null&&l(e,["prebuiltVoiceConfig"],r);let i=s(t,["voice"]);return i!=null&&l(e,["voice"],i),e}function Xw(t,e){let n={},r=s(t,["apiKey"]);if(r!=null&&l(n,["apiKey"],r),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Jw(t,e){let n={},r=s(t,["content"]);r!=null&&l(n,["content"],r);let i=s(t,["citationMetadata"]);i!=null&&l(n,["citationMetadata"],Ww(i));let o=s(t,["tokenCount"]);o!=null&&l(n,["tokenCount"],o);let a=s(t,["finishReason"]);a!=null&&l(n,["finishReason"],a);let u=s(t,["groundingMetadata"]);u!=null&&l(n,["groundingMetadata"],u);let c=s(t,["avgLogprobs"]);c!=null&&l(n,["avgLogprobs"],c);let d=s(t,["index"]);d!=null&&l(n,["index"],d);let f=s(t,["logprobsResult"]);f!=null&&l(n,["logprobsResult"],f);let p=s(t,["safetyRatings"]);if(p!=null){let _=p;Array.isArray(_)&&(_=_.map(m=>m)),l(n,["safetyRatings"],_)}let h=s(t,["urlContextMetadata"]);h!=null&&l(n,["urlContextMetadata"],h);let g=s(t,["continuationToken"]);return g!=null&&l(n,["continuationToken"],g),n}function Ww(t,e){let n={},r=s(t,["citationSources"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(n,["citations"],i)}return n}function Kw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let a=Fe(o);Array.isArray(a)&&(a=a.map(u=>sr(u))),l(r,["contents"],a)}return r}function Yw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["tokensInfo"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(n,["tokensInfo"],o)}return n}function zw(t,e){let n={},r=s(t,["values"]);r!=null&&l(n,["values"],r);let i=s(t,["statistics"]);return i!=null&&l(n,["statistics"],Qw(i)),n}function Qw(t,e){let n={},r=s(t,["truncated"]);r!=null&&l(n,["truncated"],r);let i=s(t,["token_count"]);i!=null&&l(n,["tokenCount"],i);let o=s(t,["tokensDetails"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["tokensDetails"],a)}return n}function Hr(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>QR(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function sr(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>ZR(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function Zw(t,e){let n={},r=s(t,["controlType"]);r!=null&&l(n,["controlType"],r);let i=s(t,["enableControlImageComputation"]);return i!=null&&l(n,["computeControl"],i),n}function jw(t,e){let n={};if(s(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function eR(t,e,n){let r={},i=s(t,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],sr(ke(i)));let o=s(t,["tools"]);if(e!==void 0&&o!=null){let u=o;Array.isArray(u)&&(u=u.map(c=>S_(c))),l(e,["tools"],u)}let a=s(t,["generationConfig"]);return e!==void 0&&a!=null&&l(e,["generationConfig"],UR(a)),r}function tR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let u=Fe(o);Array.isArray(u)&&(u=u.map(c=>Hr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&jw(a),r}function nR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let u=Fe(o);Array.isArray(u)&&(u=u.map(c=>sr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&eR(a,r),r}function rR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["totalTokens"]);i!=null&&l(n,["totalTokens"],i);let o=s(t,["cachedContentTokenCount"]);return o!=null&&l(n,["cachedContentTokenCount"],o),n}function iR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["totalTokens"]);return i!=null&&l(n,["totalTokens"],i),n}function oR(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],Ee(t,i)),r}function sR(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],Ee(t,i)),r}function aR(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function lR(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function uR(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let g=s(t,["includeRaiReason"]);e!==void 0&&g!=null&&l(e,["parameters","includeRaiReason"],g);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let m=s(t,["outputMimeType"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","mimeType"],m);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let E=s(t,["labels"]);e!==void 0&&E!=null&&l(e,["labels"],E);let C=s(t,["editMode"]);e!==void 0&&C!=null&&l(e,["parameters","editMode"],C);let A=s(t,["baseSteps"]);return e!==void 0&&A!=null&&l(e,["parameters","editConfig","baseSteps"],A),r}function cR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["referenceImages"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(d=>iP(d))),l(r,["instances[0]","referenceImages"],c)}let u=s(e,["config"]);return u!=null&&uR(u,r),r}function dR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>Bo(a))),l(n,["generatedImages"],o)}return n}function fR(t,e,n){let r={},i=s(t,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=s(t,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let a=s(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&l(e,["requests[]","outputDimensionality"],a),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function pR(t,e,n){let r={},i=s(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["instances[]","task_type"],p)}else if(i==="EMBED_CONTENT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","taskType"],p)}let o=s(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["instances[]","title"],p)}else if(o==="EMBED_CONTENT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","title"],p)}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["parameters","outputDimensionality"],p)}else if(a==="EMBED_CONTENT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","outputDimensionality"],p)}let u=s(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){let p=s(t,["mimeType"]);e!==void 0&&p!=null&&l(e,["instances[]","mimeType"],p)}let c=s(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","autoTruncate"],p)}let d=s(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){let p=s(t,["documentOcr"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","documentOcr"],p)}let f=s(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=s(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","audioTrackExtraction"],p)}return r}function hR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let d=uc(t,o);Array.isArray(d)&&(d=d.map(f=>f)),l(r,["requests[]","content"],d)}let a=s(e,["content"]);a!=null&&Hr(ke(a));let u=s(e,["config"]);u!=null&&fR(u,r);let c=s(e,["model"]);return c!==void 0&&l(r,["requests[]","model"],Ee(t,c)),r}function mR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let c=s(e,["contents"]);if(c!=null){let d=uc(t,c);Array.isArray(d)&&(d=d.map(f=>f)),l(r,["instances[]","content"],d)}}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="EMBED_CONTENT"){let c=s(e,["content"]);c!=null&&l(r,["content"],sr(ke(c)))}let u=s(e,["config"]);return u!=null&&pR(u,r,n),r}function gR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["embeddings"],a)}let o=s(t,["metadata"]);return o!=null&&l(n,["metadata"],o),n}function _R(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions[]","embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>zw(u))),l(n,["embeddings"],a)}let o=s(t,["metadata"]);if(o!=null&&l(n,["metadata"],o),e&&s(e,["embeddingApiType"])==="EMBED_CONTENT"){let a=s(t,["embedding"]),u=s(t,["usageMetadata"]),c=s(t,["truncated"]);if(a){let d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),u&&u.promptTokensDetails&&(d.tokensDetails=u.promptTokensDetails),c&&(d.truncated=c),a.statistics=d,l(n,["embeddings"],[a])}}return n}function yR(t,e){let n={},r=s(t,["endpoint"]);r!=null&&l(n,["name"],r);let i=s(t,["deployedModelId"]);return i!=null&&l(n,["deployedModelId"],i),n}function vR(t,e){let n={},r=s(t,["args"]);r!=null&&l(n,["args"],r);let i=s(t,["id"]);i!=null&&l(n,["id"],i);let o=s(t,["name"]);if(o!=null&&l(n,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function ER(t,e){let n={},r=s(t,["allowedFunctionNames"]);r!=null&&l(n,["allowedFunctionNames"],r);let i=s(t,["mode"]);if(i!=null&&l(n,["mode"],i),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function TR(t,e){let n={},r=s(t,["fileData"]);r!=null&&l(n,["fileData"],r);let i=s(t,["inlineData"]);if(i!=null&&l(n,["inlineData"],i),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function CR(t,e){let n={},r=s(t,["id"]);r!=null&&l(n,["id"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["parts"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>TR(d))),l(n,["parts"],c)}let a=s(t,["response"]);a!=null&&l(n,["response"],a);let u=s(t,["scheduling"]);if(u!=null&&l(n,["scheduling"],u),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function AR(t,e,n,r){let i={},o=s(e,["serviceTier"]);n!==void 0&&o!=null&&l(n,["serviceTier"],o);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],Hr(ke(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let g=s(e,["responseLogprobs"]);g!=null&&l(i,["responseLogprobs"],g);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let m=s(e,["presencePenalty"]);m!=null&&l(i,["presencePenalty"],m);let v=s(e,["frequencyPenalty"]);v!=null&&l(i,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let E=s(e,["responseMimeType"]);E!=null&&l(i,["responseMimeType"],E);let C=s(e,["responseSchema"]);C!=null&&l(i,["responseSchema"],cc(C));let A=s(e,["responseJsonSchema"]);if(A!=null&&l(i,["responseJsonSchema"],A),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let I=s(e,["safetySettings"]);if(n!==void 0&&I!=null){let pe=I;Array.isArray(pe)&&(pe=pe.map(He=>sP(He))),l(n,["safetySettings"],pe)}let k=s(e,["tools"]);if(n!==void 0&&k!=null){let pe=cn(k);Array.isArray(pe)&&(pe=pe.map(He=>mP(un(He)))),l(n,["tools"],pe)}let O=s(e,["toolConfig"]);n!==void 0&&O!=null&&l(n,["toolConfig"],pP(O));let B=s(e,["labels"]);n!==void 0&&B!=null&&l(n,["labels"],B);let D=s(e,["cachedContent"]);n!==void 0&&D!=null&&l(n,["cachedContent"],Xt(t,D));let q=s(e,["responseModalities"]);q!=null&&l(i,["responseModalities"],q);let H=s(e,["mediaResolution"]);H!=null&&l(i,["mediaResolution"],H);let J=s(e,["speechConfig"]);if(J!=null&&l(i,["speechConfig"],dc(J)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ne=s(e,["thinkingConfig"]);ne!=null&&l(i,["thinkingConfig"],ne);let L=s(e,["audioTranscriptionConfig"]);L!=null&&l(i,["audioTranscriptionConfig"],L);let X=s(e,["imageConfig"]);X!=null&&l(i,["imageConfig"],FR(X));let Z=s(e,["enableEnhancedCivicAnswers"]);if(Z!=null&&l(i,["enableEnhancedCivicAnswers"],Z),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ge=s(e,["continuationToken"]);if(n!==void 0&&ge!=null&&l(n,["continuationToken"],ge),s(e,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let _e=s(e,["store"]);return n!==void 0&&_e!=null&&l(n,["store"],_e),i}function SR(t,e,n,r){let i={},o=s(e,["serviceTier"]);n!==void 0&&o!=null&&l(n,["serviceTier"],o);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],sr(ke(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let g=s(e,["responseLogprobs"]);g!=null&&l(i,["responseLogprobs"],g);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let m=s(e,["presencePenalty"]);m!=null&&l(i,["presencePenalty"],m);let v=s(e,["frequencyPenalty"]);v!=null&&l(i,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let E=s(e,["responseMimeType"]);E!=null&&l(i,["responseMimeType"],E);let C=s(e,["responseSchema"]);C!=null&&l(i,["responseSchema"],cc(C));let A=s(e,["responseJsonSchema"]);A!=null&&l(i,["responseJsonSchema"],A);let I=s(e,["routingConfig"]);I!=null&&l(i,["routingConfig"],I);let k=s(e,["modelSelectionConfig"]);k!=null&&l(i,["modelConfig"],k);let O=s(e,["safetySettings"]);if(n!==void 0&&O!=null){let Ge=O;Array.isArray(Ge)&&(Ge=Ge.map($=>$)),l(n,["safetySettings"],Ge)}let B=s(e,["tools"]);if(n!==void 0&&B!=null){let Ge=cn(B);Array.isArray(Ge)&&(Ge=Ge.map($=>S_(un($)))),l(n,["tools"],Ge)}let D=s(e,["toolConfig"]);n!==void 0&&D!=null&&l(n,["toolConfig"],hP(D));let q=s(e,["labels"]);n!==void 0&&q!=null&&l(n,["labels"],q);let H=s(e,["cachedContent"]);n!==void 0&&H!=null&&l(n,["cachedContent"],Xt(t,H));let J=s(e,["responseModalities"]);J!=null&&l(i,["responseModalities"],J);let ne=s(e,["mediaResolution"]);ne!=null&&l(i,["mediaResolution"],ne);let L=s(e,["speechConfig"]);L!=null&&l(i,["speechConfig"],A_(dc(L)));let X=s(e,["audioTimestamp"]);X!=null&&l(i,["audioTimestamp"],X);let Z=s(e,["thinkingConfig"]);Z!=null&&l(i,["thinkingConfig"],Z);let ge=s(e,["audioTranscriptionConfig"]);ge!=null&&l(i,["audioTranscriptionConfig"],ge);let _e=s(e,["imageConfig"]);if(_e!=null&&l(i,["imageConfig"],BR(_e)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let pe=s(e,["modelArmorConfig"]);n!==void 0&&pe!=null&&l(n,["modelArmorConfig"],pe);let He=s(e,["continuationToken"]);n!==void 0&&He!=null&&l(n,["continuationToken"],He);let Ue=s(e,["generationOutputConfig"]);if(n!==void 0&&Ue!=null&&l(n,["outputConfig"],Ue),s(e,["store"])!==void 0)throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return i}function dg(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let u=Fe(o);Array.isArray(u)&&(u=u.map(c=>Hr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(r,["generationConfig"],AR(t,a,r)),r}function fg(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["contents"]);if(o!=null){let u=Fe(o);Array.isArray(u)&&(u=u.map(c=>sr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(r,["generationConfig"],SR(t,a,r)),r}function pg(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>Jw(p))),l(n,["candidates"],f)}let o=s(t,["modelVersion"]);o!=null&&l(n,["modelVersion"],o);let a=s(t,["promptFeedback"]);a!=null&&l(n,["promptFeedback"],a);let u=s(t,["responseId"]);u!=null&&l(n,["responseId"],u);let c=s(t,["usageMetadata"]);c!=null&&l(n,["usageMetadata"],c);let d=s(t,["modelStatus"]);return d!=null&&l(n,["modelStatus"],d),n}function hg(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>p)),l(n,["candidates"],f)}let o=s(t,["createTime"]);o!=null&&l(n,["createTime"],o);let a=s(t,["modelVersion"]);a!=null&&l(n,["modelVersion"],a);let u=s(t,["promptFeedback"]);u!=null&&l(n,["promptFeedback"],u);let c=s(t,["responseId"]);c!=null&&l(n,["responseId"],c);let d=s(t,["usageMetadata"]);return d!=null&&l(n,["usageMetadata"],d),n}function IR(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let g=s(t,["includeRaiReason"]);e!==void 0&&g!=null&&l(e,["parameters","includeRaiReason"],g);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let m=s(t,["outputMimeType"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","mimeType"],m);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let E=s(t,["labels"]);e!==void 0&&E!=null&&l(e,["labels"],E);let C=s(t,["imageSize"]);e!==void 0&&C!=null&&l(e,["parameters","sampleImageSize"],C);let A=s(t,["enhancePrompt"]);return e!==void 0&&A!=null&&l(e,["parameters","enhancePrompt"],A),r}function wR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["config"]);return a!=null&&IR(a,r),r}function RR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>Bo(u))),l(n,["generatedImages"],a)}let o=s(t,["positivePromptSafetyAttributes"]);return o!=null&&l(n,["positivePromptSafetyAttributes"],C_(o)),n}function PR(t,e,n){let r={},i=s(t,["numberOfVideos"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=s(t,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let a=s(t,["fps"]);e!==void 0&&a!=null&&l(e,["parameters","fps"],a);let u=s(t,["durationSeconds"]);e!==void 0&&u!=null&&l(e,["parameters","durationSeconds"],u);let c=s(t,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=s(t,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let f=s(t,["resolution"]);e!==void 0&&f!=null&&l(e,["parameters","resolution"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let g=s(t,["negativePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","negativePrompt"],g);let _=s(t,["enhancePrompt"]);e!==void 0&&_!=null&&l(e,["parameters","enhancePrompt"],_);let m=s(t,["generateAudio"]);e!==void 0&&m!=null&&l(e,["parameters","generateAudio"],m);let v=s(t,["lastFrame"]);e!==void 0&&v!=null&&l(e,["instances[0]","lastFrame"],Et(v));let y=s(t,["referenceImages"]);if(e!==void 0&&y!=null){let k=y;Array.isArray(k)&&(k=k.map(O=>RP(O))),l(e,["instances[0]","referenceImages"],k)}let E=s(t,["mask"]);e!==void 0&&E!=null&&l(e,["instances[0]","mask"],wP(E));let C=s(t,["compressionQuality"]);e!==void 0&&C!=null&&l(e,["parameters","compressionQuality"],C);let A=s(t,["labels"]);if(e!==void 0&&A!=null&&l(e,["labels"],A),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let I=s(t,["resizeMode"]);return e!==void 0&&I!=null&&l(e,["parameters","resizeMode"],I),r}function kR(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["metadata"]);i!=null&&l(n,["metadata"],i);let o=s(t,["done"]);o!=null&&l(n,["done"],o);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response"]);return u!=null&&l(n,["response"],NR(u)),n}function xR(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["image"]);a!=null&&l(r,["instances[0]","image"],Et(a));let u=s(e,["video"]);u!=null&&l(r,["instances[0]","video"],I_(u));let c=s(e,["source"]);c!=null&&DR(c,r);let d=s(e,["config"]);return d!=null&&PR(d,r),r}function NR(t,e){let n={},r=s(t,["videos"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>MR(u))),l(n,["generatedVideos"],a)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(n,["raiMediaFilteredCount"],i);let o=s(t,["raiMediaFilteredReasons"]);return o!=null&&l(n,["raiMediaFilteredReasons"],o),n}function DR(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Et(o));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],I_(a)),r}function Bo(t,e){let n={},r=s(t,["_self"]);r!=null&&l(n,["image"],T_(r));let i=s(t,["raiFilteredReason"]);i!=null&&l(n,["raiFilteredReason"],i);let o=s(t,["_self"]);o!=null&&l(n,["safetyAttributes"],C_(o));let a=s(t,["prompt"]);return a!=null&&l(n,["enhancedPrompt"],a),n}function bR(t,e){let n={},r=s(t,["_self"]);r!=null&&l(n,["mask"],T_(r));let i=s(t,["labels"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(n,["labels"],o)}return n}function MR(t,e){let n={},r=s(t,["_self"]);return r!=null&&l(n,["video"],IP(r)),n}function UR(t,e){let n={},r=s(t,["modelSelectionConfig"]);r!=null&&l(n,["modelConfig"],r);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let o=s(t,["audioTranscriptionConfig"]);o!=null&&l(n,["audioTranscriptionConfig"],o);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let g=s(t,["presencePenalty"]);g!=null&&l(n,["presencePenalty"],g);let _=s(t,["responseFormat"]);if(_!=null){let J=_;Array.isArray(J)&&(J=J.map(ne=>ne)),l(n,["responseFormat"],J)}let m=s(t,["responseLogprobs"]);m!=null&&l(n,["responseLogprobs"],m);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let E=s(t,["responseSchema"]);E!=null&&l(n,["responseSchema"],E);let C=s(t,["routingConfig"]);C!=null&&l(n,["routingConfig"],C);let A=s(t,["seed"]);A!=null&&l(n,["seed"],A);let I=s(t,["speechConfig"]);I!=null&&l(n,["speechConfig"],A_(I));let k=s(t,["stopSequences"]);k!=null&&l(n,["stopSequences"],k);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let B=s(t,["thinkingConfig"]);B!=null&&l(n,["thinkingConfig"],B);let D=s(t,["topK"]);D!=null&&l(n,["topK"],D);let q=s(t,["topP"]);if(q!=null&&l(n,["topP"],q),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let H=s(t,["translationConfig"]);return H!=null&&l(n,["translationConfig"],H),n}function GR(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],Ee(t,i)),r}function OR(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],Ee(t,i)),r}function LR(t,e){let n={},r=s(t,["authConfig"]);r!=null&&l(n,["authConfig"],Xw(r));let i=s(t,["enableWidget"]);if(i!=null&&l(n,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function qR(t,e){let n={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["searchTypes"]);r!=null&&l(n,["searchTypes"],r);let i=s(t,["timeRangeFilter"]);return i!=null&&l(n,["timeRangeFilter"],i),n}function FR(t,e){let n={},r=s(t,["aspectRatio"]);r!=null&&l(n,["aspectRatio"],r);let i=s(t,["imageSize"]);if(i!=null&&l(n,["imageSize"],i),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function BR(t,e){let n={},r=s(t,["aspectRatio"]);r!=null&&l(n,["aspectRatio"],r);let i=s(t,["imageSize"]);i!=null&&l(n,["imageSize"],i);let o=s(t,["personGeneration"]);o!=null&&l(n,["personGeneration"],o);let a=s(t,["outputMimeType"]);a!=null&&l(n,["imageOutputOptions","mimeType"],a);let u=s(t,["outputCompressionQuality"]);u!=null&&l(n,["imageOutputOptions","compressionQuality"],u);let c=s(t,["imageOutputOptions"]);c!=null&&l(n,["imageOutputOptions"],c);let d=s(t,["prominentPeople"]);return d!=null&&l(n,["prominentPeople"],d),n}function T_(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["imageBytes"],Fo(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function Et(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["imageBytes"]);i!=null&&l(n,["bytesBase64Encoded"],Fo(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function HR(t,e,n,r){let i={},o=s(e,["pageSize"]);n!==void 0&&o!=null&&l(n,["_query","pageSize"],o);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],l_(t,c)),i}function VR(t,e,n,r){let i={},o=s(e,["pageSize"]);n!==void 0&&o!=null&&l(n,["_query","pageSize"],o);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],l_(t,c)),i}function $R(t,e,n){let r={},i=s(e,["config"]);return i!=null&&HR(t,i,r),r}function XR(t,e,n){let r={},i=s(e,["config"]);return i!=null&&VR(t,i,r),r}function JR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["_self"]);if(o!=null){let a=u_(o);Array.isArray(a)&&(a=a.map(u=>tu(u))),l(n,["models"],a)}return n}function WR(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["_self"]);if(o!=null){let a=u_(o);Array.isArray(a)&&(a=a.map(u=>nu(u))),l(n,["models"],a)}return n}function KR(t,e){let n={},r=s(t,["maskMode"]);r!=null&&l(n,["maskMode"],r);let i=s(t,["segmentationClasses"]);i!=null&&l(n,["maskClasses"],i);let o=s(t,["maskDilation"]);return o!=null&&l(n,["dilation"],o),n}function YR(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function tu(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let o=s(t,["description"]);o!=null&&l(n,["description"],o);let a=s(t,["version"]);a!=null&&l(n,["version"],a);let u=s(t,["_self"]);u!=null&&l(n,["tunedModelInfo"],gP(u));let c=s(t,["inputTokenLimit"]);c!=null&&l(n,["inputTokenLimit"],c);let d=s(t,["outputTokenLimit"]);d!=null&&l(n,["outputTokenLimit"],d);let f=s(t,["supportedGenerationMethods"]);f!=null&&l(n,["supportedActions"],f);let p=s(t,["temperature"]);p!=null&&l(n,["temperature"],p);let h=s(t,["maxTemperature"]);h!=null&&l(n,["maxTemperature"],h);let g=s(t,["topP"]);g!=null&&l(n,["topP"],g);let _=s(t,["topK"]);_!=null&&l(n,["topK"],_);let m=s(t,["thinking"]);return m!=null&&l(n,["thinking"],m),n}function nu(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let o=s(t,["description"]);o!=null&&l(n,["description"],o);let a=s(t,["versionId"]);a!=null&&l(n,["version"],a);let u=s(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(g=>yR(g))),l(n,["endpoints"],h)}let c=s(t,["labels"]);c!=null&&l(n,["labels"],c);let d=s(t,["_self"]);d!=null&&l(n,["tunedModelInfo"],_P(d));let f=s(t,["defaultCheckpointId"]);f!=null&&l(n,["defaultCheckpointId"],f);let p=s(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["checkpoints"],h)}return n}function zR(t,e){let n={},r=s(t,["speakerVoiceConfigs"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>fP(o))),l(n,["speakerVoiceConfigs"],i)}return n}function QR(t,e){let n={},r=s(t,["mediaResolution"]);r!=null&&l(n,["mediaResolution"],r);let i=s(t,["toolCall"]);i!=null&&l(n,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(n,["toolResponse"],o);let a=s(t,["audioTranscription"]);a!=null&&l(n,["audioTranscription"],a);let u=s(t,["codeExecutionResult"]);u!=null&&l(n,["codeExecutionResult"],u);let c=s(t,["executableCode"]);c!=null&&l(n,["executableCode"],c);let d=s(t,["fileData"]);d!=null&&l(n,["fileData"],d);let f=s(t,["functionCall"]);f!=null&&l(n,["functionCall"],vR(f));let p=s(t,["functionResponse"]);p!=null&&l(n,["functionResponse"],p);let h=s(t,["inlineData"]);h!=null&&l(n,["inlineData"],h);let g=s(t,["text"]);g!=null&&l(n,["text"],g);let _=s(t,["thought"]);_!=null&&l(n,["thought"],_);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let v=s(t,["videoMetadata"]);v!=null&&l(n,["videoMetadata"],v);let y=s(t,["partMetadata"]);y!=null&&l(n,["partMetadata"],y);let E=s(t,["mediaProcessing"]);E!=null&&l(n,["mediaProcessing"],E);let C=s(t,["speechMetadata"]);return C!=null&&l(n,["speechMetadata"],C),n}function ZR(t,e){let n={},r=s(t,["mediaResolution"]);if(r!=null&&l(n,["mediaResolution"],r),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(n,["codeExecutionResult"],o);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],CR(d));let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let m=s(t,["mediaProcessing"]);m!=null&&l(n,["mediaProcessing"],m);let v=s(t,["speechMetadata"]);return v!=null&&l(n,["speechMetadata"],v),n}function jR(t,e){let n={},r=s(t,["productImage"]);return r!=null&&l(n,["image"],Et(r)),n}function eP(t,e,n){let r={},i=s(t,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=s(t,["baseSteps"]);e!==void 0&&o!=null&&l(e,["parameters","baseSteps"],o);let a=s(t,["outputGcsUri"]);e!==void 0&&a!=null&&l(e,["parameters","storageUri"],a);let u=s(t,["seed"]);e!==void 0&&u!=null&&l(e,["parameters","seed"],u);let c=s(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=s(t,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let f=s(t,["addWatermark"]);e!==void 0&&f!=null&&l(e,["parameters","addWatermark"],f);let p=s(t,["outputMimeType"]);e!==void 0&&p!=null&&l(e,["parameters","outputOptions","mimeType"],p);let h=s(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let g=s(t,["enhancePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","enhancePrompt"],g);let _=s(t,["labels"]);return e!==void 0&&_!=null&&l(e,["labels"],_),r}function tP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["source"]);o!=null&&rP(o,r);let a=s(e,["config"]);return a!=null&&eP(a,r),r}function nP(t,e){let n={},r=s(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>Bo(o))),l(n,["generatedImages"],i)}return n}function rP(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["personImage"]);e!==void 0&&o!=null&&l(e,["instances[0]","personImage","image"],Et(o));let a=s(t,["productImages"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>jR(c))),l(e,["instances[0]","productImages"],u)}return r}function iP(t,e){let n={},r=s(t,["referenceImage"]);r!=null&&l(n,["referenceImage"],Et(r));let i=s(t,["referenceId"]);i!=null&&l(n,["referenceId"],i);let o=s(t,["referenceType"]);o!=null&&l(n,["referenceType"],o);let a=s(t,["maskImageConfig"]);a!=null&&l(n,["maskImageConfig"],KR(a));let u=s(t,["controlImageConfig"]);u!=null&&l(n,["controlImageConfig"],Zw(u));let c=s(t,["styleImageConfig"]);c!=null&&l(n,["styleImageConfig"],c);let d=s(t,["subjectImageConfig"]);return d!=null&&l(n,["subjectImageConfig"],d),n}function oP(t,e){let n={},r=s(t,["mimeType"]);r!=null&&l(n,["mimeType"],r);let i=s(t,["voiceSampleAudio"]);if(i!=null&&l(n,["voiceSampleAudio"],i),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function C_(t,e){let n={},r=s(t,["safetyAttributes","categories"]);r!=null&&l(n,["categories"],r);let i=s(t,["safetyAttributes","scores"]);i!=null&&l(n,["scores"],i);let o=s(t,["contentType"]);return o!=null&&l(n,["contentType"],o),n}function sP(t,e){let n={},r=s(t,["category"]);if(r!=null&&l(n,["category"],r),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(n,["threshold"],i),n}function aP(t,e){let n={},r=s(t,["image"]);return r!=null&&l(n,["image"],Et(r)),n}function lP(t,e,n){let r={},i=s(t,["mode"]);e!==void 0&&i!=null&&l(e,["parameters","mode"],i);let o=s(t,["maxPredictions"]);e!==void 0&&o!=null&&l(e,["parameters","maxPredictions"],o);let a=s(t,["confidenceThreshold"]);e!==void 0&&a!=null&&l(e,["parameters","confidenceThreshold"],a);let u=s(t,["maskDilation"]);e!==void 0&&u!=null&&l(e,["parameters","maskDilation"],u);let c=s(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=s(t,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),r}function uP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["source"]);o!=null&&dP(o,r);let a=s(e,["config"]);return a!=null&&lP(a,r),r}function cP(t,e){let n={},r=s(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>bR(o))),l(n,["generatedMasks"],i)}return n}function dP(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Et(o));let a=s(t,["scribbleImage"]);return e!==void 0&&a!=null&&l(e,["instances[0]","scribble"],aP(a)),r}function fP(t,e){let n={},r=s(t,["speaker"]);r!=null&&l(n,["speaker"],r);let i=s(t,["voiceConfig"]);return i!=null&&l(n,["voiceConfig"],w_(i)),n}function A_(t,e){let n={},r=s(t,["voiceConfig"]);r!=null&&l(n,["voiceConfig"],w_(r));let i=s(t,["languageCode"]);i!=null&&l(n,["languageCode"],i);let o=s(t,["multiSpeakerVoiceConfig"]);return o!=null&&l(n,["multiSpeakerVoiceConfig"],zR(o)),n}function pP(t,e){let n={},r=s(t,["functionCallingConfig"]);r!=null&&l(n,["functionCallingConfig"],ER(r));let i=s(t,["retrievalConfig"]);i!=null&&l(n,["retrievalConfig"],i);let o=s(t,["includeServerSideToolInvocations"]);return o!=null&&l(n,["includeServerSideToolInvocations"],o),n}function hP(t,e){let n={},r=s(t,["functionCallingConfig"]);r!=null&&l(n,["functionCallingConfig"],r);let i=s(t,["retrievalConfig"]);if(i!=null&&l(n,["retrievalConfig"],i),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function mP(t,e){let n={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["googleMaps"]);r!=null&&l(n,["googleMaps"],LR(r));let i=s(t,["mcpServers"]);if(i!=null){let h=i;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["mcpServers"],h)}let o=s(t,["codeExecution"]);o!=null&&l(n,["codeExecution"],o);let a=s(t,["computerUse"]);if(a!=null&&l(n,["computerUse"],a),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["functionDeclarations"],h)}let c=s(t,["googleSearch"]);c!=null&&l(n,["googleSearch"],qR(c));let d=s(t,["googleSearchRetrieval"]);if(d!=null&&l(n,["googleSearchRetrieval"],d),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=s(t,["urlContext"]);f!=null&&l(n,["urlContext"],f);let p=s(t,["fileSearch"]);return p!=null&&l(n,["fileSearch"],p),n}function S_(t,e){let n={},r=s(t,["retrieval"]);r!=null&&l(n,["retrieval"],r);let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],i);let o=s(t,["mcpServers"]);if(o!=null){let m=o;Array.isArray(m)&&(m=m.map(v=>YR(v))),l(n,["mcpServers"],m)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],u);let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),l(n,["functionDeclarations"],m)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let g=s(t,["parallelAiSearch"]);g!=null&&l(n,["parallelAiSearch"],g);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function gP(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let o=s(t,["updateTime"]);return o!=null&&l(n,["updateTime"],o),n}function _P(t,e){let n={},r=s(t,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let o=s(t,["updateTime"]);return o!=null&&l(n,["updateTime"],o),n}function yP(t,e,n){let r={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),r}function vP(t,e,n){let r={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),r}function EP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","name"],Ee(t,i));let o=s(e,["config"]);return o!=null&&yP(o,r),r}function TP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["config"]);return o!=null&&vP(o,r),r}function CP(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["safetyFilterLevel"]);e!==void 0&&o!=null&&l(e,["parameters","safetySetting"],o);let a=s(t,["personGeneration"]);e!==void 0&&a!=null&&l(e,["parameters","personGeneration"],a);let u=s(t,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let c=s(t,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=s(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let f=s(t,["enhanceInputImage"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=s(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=s(t,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let g=s(t,["numberOfImages"]);e!==void 0&&g!=null&&l(e,["parameters","sampleCount"],g);let _=s(t,["mode"]);return e!==void 0&&_!=null&&l(e,["parameters","mode"],_),r}function AP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],Ee(t,i));let o=s(e,["image"]);o!=null&&l(r,["instances[0]","image"],Et(o));let a=s(e,["upscaleFactor"]);a!=null&&l(r,["parameters","upscaleConfig","upscaleFactor"],a);let u=s(e,["config"]);return u!=null&&CP(u,r),r}function SP(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>Bo(a))),l(n,["generatedImages"],o)}return n}function IP(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["uri"],r);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["videoBytes"],Fo(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function wP(t,e){let n={},r=s(t,["image"]);r!=null&&l(n,["_self"],Et(r));let i=s(t,["maskMode"]);return i!=null&&l(n,["maskMode"],i),n}function RP(t,e){let n={},r=s(t,["image"]);r!=null&&l(n,["image"],Et(r));let i=s(t,["referenceType"]);return i!=null&&l(n,["referenceType"],i),n}function I_(t,e){let n={},r=s(t,["uri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["videoBytes"]);i!=null&&l(n,["bytesBase64Encoded"],Fo(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function w_(t,e){let n={},r=s(t,["replicatedVoiceConfig"]);r!=null&&l(n,["replicatedVoiceConfig"],oP(r));let i=s(t,["prebuiltVoiceConfig"]);i!=null&&l(n,["prebuiltVoiceConfig"],i);let o=s(t,["voice"]);return o!=null&&l(n,["voice"],o),n}function PP(t,e,n){let r={},i=s(e,["displayName"]);n!==void 0&&i!=null&&l(n,["displayName"],i);let o=s(e,["embeddingModel"]);return n!==void 0&&o!=null&&l(n,["embeddingModel"],Ee(t,o)),r}function kP(t,e){let n={},r=s(e,["config"]);return r!=null&&PP(t,r,n),n}function xP(t,e){let n={},r=s(t,["force"]);return e!==void 0&&r!=null&&l(e,["_query","force"],r),n}function NP(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let r=s(t,["config"]);return r!=null&&xP(r,e),e}function DP(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function bP(t,e){let n={},r=s(t,["customMetadata"]);if(e!==void 0&&r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["customMetadata"],o)}let i=s(t,["chunkingConfig"]);return e!==void 0&&i!=null&&l(e,["chunkingConfig"],i),n}function MP(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],GP(a)),e}function UP(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let r=s(t,["fileName"]);r!=null&&l(e,["fileName"],r);let i=s(t,["config"]);return i!=null&&bP(i,e),e}function GP(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function OP(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function LP(t){let e={},n=s(t,["config"]);return n!=null&&OP(n,e),e}function qP(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["fileSearchStores"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["fileSearchStores"],o)}return e}function R_(t,e){let n={},r=s(t,["mimeType"]);e!==void 0&&r!=null&&l(e,["mimeType"],r);let i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["customMetadata"]);if(e!==void 0&&o!=null){let u=o;Array.isArray(u)&&(u=u.map(c=>c)),l(e,["customMetadata"],u)}let a=s(t,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),n}function FP(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let r=s(t,["config"]);return r!=null&&R_(r,e),e}function BP(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}var HP="Content-Type",VP="X-Server-Timeout",$P="User-Agent",ru="x-goog-api-client",XP="3.0.0",JP=`google-genai-sdk/${XP}`,WP="v1beta1",KP="v1",YP,zP=new Set(["us","eu"]),mg=Symbol.for("undici.globalDispatcher.1");function QP(){var t,e;return typeof((e=(t=globalThis.process)===null||t===void 0?void 0:t.versions)===null||e===void 0?void 0:e.node)=="string"}function ZP(){return{dispatch(t,e){let n=globalThis[mg];if(!n&&typeof Headers<"u"&&(new Headers,n=globalThis[mg]),!n||typeof n.dispatch!="function")throw new Error("Undici globalDispatcher is not available.");return n.dispatch(Object.assign(Object.assign({},t),{headersTimeout:0,bodyTimeout:0}),e)}}}function jP(t,e){let n=()=>{};if(!(t&&t>0)&&!e)return{signal:void 0,dispose:n};let r=new AbortController,i;t&&t>0&&(i=setTimeout(()=>r.abort(),t),i&&typeof i.unref=="function"&&i.unref());let o=()=>r.abort();return e&&(e.aborted?r.abort():e.addEventListener("abort",o)),{signal:r.signal,dispose:()=>{i!==void 0&&clearTimeout(i),e?.removeEventListener("abort",o)}}}var ek=5,tk=1,nk=60,rk=2,ik=1,ok=[408,429,500,502,503,504],iu=class{constructor(e){var n,r,i,o;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let a={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let c=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!c?(a.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?a.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&zP.has(this.clientOptions.location)?a.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(a.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),a.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:WP}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),a.apiVersion=(o=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:YP)!==null&&o!==void 0?o:KP,a.baseUrl="https://generativelanguage.googleapis.com/";a.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=a,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(a,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}getTimeout(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.timeout}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let r=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&r.push(e.apiVersion),r.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}resolveApiVersionInPath(e,n){let r="{api_version}";return n!==""?e.replaceAll(r,n):e.replaceAll(`${r}/`,"").replaceAll(`/${r}`,"").replaceAll(r,"")}constructUrl(e,n,r){if(e.includes("{api_version}")){if(!n||n.baseUrl===void 0||n.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let u=[n.baseUrl.endsWith("/")?n.baseUrl.slice(0,-1):n.baseUrl];r&&u.push(this.getBaseResourcePath());let c=this.resolveApiVersionInPath(e,n.apiVersion);return c!==""&&u.push(c),new URL(`${u.join("/")}`)}let i=[this.getRequestUrlInternal(n)];return r&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===Pl.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,r);if(e.queryParams)for(let[a,u]of Object.entries(e.queryParams))i.searchParams.append(a,String(u));let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else o.body=e.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,n,i.toString()),this.unaryApiCall(i,o,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}patchHttpOptions(e,n){let r=JSON.parse(JSON.stringify(e));e.fetch&&(r.fetch=e.fetch);for(let[i,o]of Object.entries(n))typeof o=="object"?r[i]=Object.assign(Object.assign({},r[i]),o):o!==void 0&&(r[i]=o);return r}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,r);(!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,n,i.toString()),this.streamApiCall(i,o,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}async includeExtraHttpOptionsToRequestInit(e,n,r){return QP()&&!n?.fetch&&!("dispatcher"in e)&&(e.dispatcher=ZP()),n&&n.extraBody!==null&&sk(e,n.extraBody),e.headers=await this.getHeadersInternal(n,r),e}async unaryApiCall(e,n,r,i,o,a,u){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,o,a,u).then(async c=>(await Al(c),new Ht(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,n,r,i,o,a,u){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,o,a,u).then(async c=>(await Al(c),this.processStreamResponse(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return Bt(this,arguments,function*(){var r;let i=(r=e?.body)===null||r===void 0?void 0:r.getReader(),o=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let a="",u="data:",c=[`
|
|
37
|
+
|
|
38
|
+
`,"\r\r",`\r
|
|
39
|
+
\r
|
|
40
|
+
`];for(;;){let{done:d,value:f}=yield se(i.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=o.decode(f,{stream:!0});gg(p),a+=p;let h=-1,g=0;for(;;){h=-1,g=0;for(let v of c){let y=a.indexOf(v);y!==-1&&(h===-1||y<h)&&(h=y,g=v.length)}if(h===-1)break;let _=a.substring(0,h);a=a.substring(h+g);let m=_.trim();if(m.startsWith(u)){let v=m.substring(u.length).trim();gg(v);try{let y=new Response(v,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield se(new Ht(y))}catch(y){throw new Error(`exception parsing stream chunk ${v}. ${y}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n,r,i,o,a){var u,c,d,f,p,h;let g=a??fetch,_=(u=r?.httpStatusCodes)!==null&&u!==void 0?u:ok,m=async()=>{let C=jP(i,o),A;try{A=await g(e,Object.assign(Object.assign({},n),{signal:C.signal}))}catch(I){throw C.dispose(),I}if(!r||A.ok||!_.includes(A.status))return A;try{await Al(A)}finally{C.dispose()}return A};if(!r)return m();let v=Math.max(1,(c=r.attempts)!==null&&c!==void 0?c:ek),y=Math.round(((d=r.initialDelay)!==null&&d!==void 0?d:tk)*1e3),E=Math.max(y,Math.round(((f=r.maxDelay)!==null&&f!==void 0?f:nk)*1e3));return(0,Kg.default)(m,{retries:v-1,factor:(p=r.expBase)!==null&&p!==void 0?p:rk,minTimeout:y,maxTimeout:E,randomize:((h=r.jitter)!==null&&h!==void 0?h:ik)>0,onFailedAttempt:C=>{var A;if(o?.aborted)throw(A=C.error)!==null&&A!==void 0?A:C}})}getDefaultHeaders(){let e={},n=JP+" "+this.clientOptions.userAgentExtra;return e[$P]=n,e[ru]=n,e[HP]="application/json",e}async getHeadersInternal(e,n){let r=new Headers;if(e&&e.headers)for(let[i,o]of Object.entries(e.headers))r.append(i,o);return e?.timeout&&e.timeout>0&&r.append(VP,String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(r,n),r}getFileName(e){var n;let r="";return typeof e=="string"&&(r=e.replace(/[/\\]+$/,""),r=(n=r.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),r}async uploadFile(e,n){var r;let i={};n!=null&&(i.mimeType=n.mimeType,i.name=n.name,i.displayName=n.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);let o=this.clientOptions.uploader,a=await o.stat(e);i.sizeBytes=String(a.size);let u=(r=n?.mimeType)!==null&&r!==void 0?r:a.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=u;let c={file:i},d=this.getFileName(e),f=await this.fetchUploadUrl("upload/{api_version}/files",i.sizeBytes,i.mimeType,d,c,n?.httpOptions);return o.upload(e,f,this)}async uploadFileToFileSearchStore(e,n,r){var i;let o=this.clientOptions.uploader,a=await o.stat(n),u=String(a.size),c=(i=r?.mimeType)!==null&&i!==void 0?i:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let d=`upload/{api_version}/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};r!=null&&R_(r,p);let h=await this.fetchUploadUrl(d,u,c,f,p,r?.httpOptions);return o.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,r,i,o,a){var u;let c=Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign(Object.assign({},a?.headers),{"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`}),i?{"X-Goog-Upload-File-Name":i}:{})}),d=await this.request({path:e,body:JSON.stringify(o),httpMethod:"POST",httpOptions:c});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(u=d?.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};function gg(t){try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&"error"in e&&e.error!==null&&typeof e.error=="object"){let n=e.error,r=n.status,i=n.code,o=`got status: ${r}. ${JSON.stringify(e)}`;if(typeof i=="number"&&i>=400&&i<600)throw new Gr({message:o,status:i})}}catch(e){let n=e;if(n?.name==="ApiError")throw e}}async function Al(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){let n=t.status,r;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?r=await t.json():r={error:{message:await t.text(),code:t.status,status:t.statusText}};let i=JSON.stringify(r);throw n>=400&&n<600?new Gr({message:i,status:n}):new Error(i)}}function sk(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{let o=JSON.parse(t.body);if(typeof o=="object"&&o!==null&&!Array.isArray(o))n=o;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function r(o,a){let u=Object.assign({},o);for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let d=a[c],f=u[c];d&&typeof d=="object"&&!Array.isArray(d)&&f&&typeof f=="object"&&!Array.isArray(f)?u[c]=r(f,d):(f&&d&&typeof f!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`),u[c]=d)}return u}let i=r(n,e);t.body=JSON.stringify(i)}var ak="mcp_used/unknown",P_=!1;function k_(t){for(let e of t)if(lk(e)||typeof e=="object"&&"inputSchema"in e)return!0;return P_}function x_(t){var e;let n=(e=t[ru])!==null&&e!==void 0?e:"";t[ru]=(n+` ${ak}`).trimStart()}function lk(t){return t!==null&&typeof t=="object"&&t instanceof Or}function uk(t){return Bt(this,arguments,function*(n,r=100){let i,o=0;for(;o<r;){let a=yield se(n.listTools({cursor:i}));for(let u of a.tools)yield yield se(u),o++;if(!a.nextCursor)break;i=a.nextCursor}})}var Or=class t{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new t(e,n)}async initialize(){var e,n,r,i;if(this.mcpTools.length>0)return;let o={},a=[];for(let f of this.mcpClients)try{for(var u=!0,c=(n=void 0,Cn(uk(f))),d;d=await c.next(),e=d.done,!e;u=!0){i=d.value,u=!1;let p=i;a.push(p);let h=p.name;if(o[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);o[h]=f}}catch(p){n={error:p}}finally{try{!u&&!e&&(r=c.return)&&await r.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=o}async tool(){return await this.initialize(),RS(this.mcpTools,this.config)}async callTool(e){await this.initialize();let n=[];for(let r of e)if(r.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[r.name],o;this.config.timeout&&(o={timeout:this.config.timeout});let a=await i.callTool({name:r.name,arguments:r.args},void 0,o);n.push({functionResponse:{name:r.name,response:a.isError?{error:a}:a}})}return n}};function ck(t){return t!==null&&typeof t=="object"&&"listTools"in t&&typeof t.listTools=="function"}function ZM(...t){if(P_=!0,t.length===0)throw new Error("No MCP clients provided");let e=t[t.length-1];return ck(e)?Or.create(t,{}):Or.create(t.slice(0,t.length-1),e)}async function dk(t,e,n){let r=new Kl,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(r,i),e(r)}var ou=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r}async connect(e){var n,r;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),o=this.apiClient.getApiVersion(),a=pk(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${i}/ws/google.ai.generativelanguage.${o}.GenerativeService.BidiGenerateMusic?key=${u}`,d=()=>{},f=new Promise(C=>{d=C}),p=e.callbacks,h=function(){d({})},g=this.apiClient,_={onopen:h,onmessage:C=>{dk(g,p.onmessage,C)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(C){},onclose:(r=p?.onclose)!==null&&r!==void 0?r:function(C){}},m=this.webSocketFactory.create(c,fk(a),_);m.connect(),await f;let E={setup:{model:Ee(this.apiClient,e.model)}};return m.send(JSON.stringify(E)),new su(m,this.apiClient)}},su=class{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let n=Nw(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=xw(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(Zn.PLAY)}pause(){this.sendPlaybackControl(Zn.PAUSE)}stop(){this.sendPlaybackControl(Zn.STOP)}resetContext(){this.sendPlaybackControl(Zn.RESET_CONTEXT)}close(){this.conn.close()}};function fk(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function pk(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var hk="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function mk(t,e,n){let r=new Wl,i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;let o=JSON.parse(i);if(t.isVertexAI()){let a=Mw(o);Object.assign(r,a)}else Object.assign(r,o);e(r)}var au=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r,this.music=new ou(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,r,i,o;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let a=this.apiClient.getWebsocketBaseUrl(),u=this.apiClient.getApiVersion(),c,d=this.apiClient.getHeaders();e.config&&e.config.tools&&k_(e.config.tools)&&x_(d);let f=yk(d);if(this.apiClient.isVertexAI()){let X=this.apiClient.getProject(),Z=this.apiClient.getLocation(),ge=this.apiClient.getApiKey(),_e=!!X&&!!Z||!!ge;this.apiClient.getCustomBaseUrl()&&!_e?c=a:(c=`${a}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,c))}else{let X=this.apiClient.getApiKey(),Z="BidiGenerateContent",ge="key";X?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),u!=="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."),Z="BidiGenerateContentConstrained",ge="access_token"),c=`${a}/ws/google.ai.generativelanguage.${u}.GenerativeService.${Z}?${ge}=${X}`}let p=()=>{},h=()=>{},g=new Promise((X,Z)=>{p=X,h=Z});g.catch(()=>{});let _=e.callbacks,m=function(){var X;(X=_?.onopen)===null||X===void 0||X.call(_),p({})},v=this.apiClient,y=!1,E=[],C=()=>{},A=()=>{},I=new Promise((X,Z)=>{C=X,A=Z});I.catch(()=>{});let k=X=>{h(X),A(X)},O={onopen:m,onmessage:X=>{mk(v,Z=>{Z.setupComplete&&!L.setupComplete&&(L.setupComplete=Z.setupComplete,C({})),y?_.onmessage(Z):E.push(Z)},X)},onerror:X=>{var Z;try{(Z=_?.onerror)===null||Z===void 0||Z.call(_,X)}finally{k(new Error(`Live connection failed before setup completed: ${X?.message||"WebSocket error"}`))}},onclose:X=>{var Z,ge;try{(Z=_?.onclose)===null||Z===void 0||Z.call(_,X)}finally{k(new Error(`Live connection closed before setup completed (code ${(ge=X?.code)!==null&&ge!==void 0?ge:1006}): ${X?.reason||"Abnormal closure."}`))}}},B=this.webSocketFactory.create(c,_k(f),O);B.connect(),await g;let D=Ee(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&D.startsWith("publishers/")){let X=this.apiClient.getProject(),Z=this.apiClient.getLocation();X&&Z&&(D=`projects/${X}/locations/${Z}/`+D)}let q={};this.apiClient.isVertexAI()&&((n=e.config)===null||n===void 0?void 0:n.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[ho.AUDIO]}:e.config.responseModalities=[ho.AUDIO]),!((r=e.config)===null||r===void 0)&&r.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let H=(o=(i=e.config)===null||i===void 0?void 0:i.tools)!==null&&o!==void 0?o:[],J=[];for(let X of H)if(this.isCallableTool(X)){let Z=X;J.push(await Z.tool())}else J.push(X);J.length>0&&(e.config.tools=J);let ne={model:D,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?q=kw(this.apiClient,ne):q=Pw(this.apiClient,ne),delete q.config;let L=new lu(B,this.apiClient);B.send(JSON.stringify(q));try{await I}catch(X){throw B.close(),X}y=!0;for(let X of E)_.onmessage(X);return L}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},gk={turnComplete:!0},lu=class{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let r=[];try{r=Fe(n.turns),e.isVertexAI()||(r=r.map(i=>Hr(i)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:r,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let r=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?r=n.functionResponses:r=[n.functionResponses],r.length===0)throw new Error("functionResponses is required.");for(let o of r){if(typeof o!="object"||o===null||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw new Error(hk)}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},gk),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:bw(e)}:n={realtimeInput:Dw(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendContextUpdate(e){let n={};this.apiClient.isVertexAI()?n={contextUpdate:Aw(e)}:n={contextUpdate:Cw(e)},this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function _k(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function yk(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var _g=10;function yg(t){var e,n,r;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let a of(n=t?.tools)!==null&&n!==void 0?n:[])if(tr(a)){i=!0;break}if(!i)return!0;let o=(r=t?.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls;return o&&(o<0||!Number.isInteger(o))||o==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",o),!0):!1}function tr(t){return"callTool"in t&&typeof t.callTool=="function"}function vk(t){var e,n,r;return(r=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(i=>tr(i)))!==null&&r!==void 0?r:!1}function vg(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((r,i)=>{if(tr(r))return;let o=r;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(i)}),n}function Eg(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}function fo(t,e=!0){return!t||t.automaticContinuation===void 0||t.automaticContinuation===null?e:!!t.automaticContinuation}function hc(t){return t===void 0||t===po.CONTINUATION}function N_(t,e,n,r=!1){return t&&!r&&!!e&&hc(n)}var Ek=3;function Tk(t,e,n){var r;let i=(r=t.candidates)===null||r===void 0?void 0:r[0];i?.finishReason!==void 0&&N_(e,n,i.finishReason)&&(i.finishReason=void 0)}function Ck(t,e){var n;return!!(!((n=e?.abortSignal)===null||n===void 0)&&n.aborted)||t instanceof Error&&t.name==="AbortError"}var Ak=class{constructor(e){this.config=e,this.reconnectsWithoutProgress=0,this.hop=Tg(void 0),this.enableContinuation=fo(e,!0)}startHop(){return this.hop=Tg(this.resumeToken),D_(this.config,this.resumeToken)}observe(e){var n,r;let i=this.hop;if(i.receivedAnyChunk=!0,e.promptFeedback!==void 0&&e.promptFeedback!==null&&(i.hasPromptFeedback=!0),e.usageMetadata)if(this.accumulatedUsageAcrossHops){let a=b_(this.accumulatedUsageAcrossHops,e.usageMetadata);e=Object.assign(new yt,e,{usageMetadata:a}),i.usage=a}else Mr(e.usageMetadata),i.usage=e.usageMetadata;let o=(n=e.candidates)===null||n===void 0?void 0:n[0];return o&&(!((r=o.content)===null||r===void 0)&&r.parts&&o.content.parts.length>0&&(i.hasYieldedContent=!0),o.finishReason!==void 0&&(i.finishReason=o.finishReason),o.continuationToken?i.token=o.continuationToken:o.finishReason!==void 0&&!hc(o.finishReason)&&(i.token=void 0),Tk(e,this.enableContinuation,i.token)),e}endHop(e){let n=this.hop;if(n.usage&&(this.accumulatedUsageAcrossHops=n.usage),e&&(Ck(e.error,this.config)||e.error instanceof Gr&&!n.receivedAnyChunk))throw e.error;let r=n.hasYieldedContent||!!n.token&&n.token!==n.startToken;if(e?this.lastError=e:r&&(this.lastError=void 0),[this.resumeToken,this.reconnectsWithoutProgress]=this.nextResumeToken(),N_(this.enableContinuation,this.resumeToken,n.finishReason,n.hasPromptFeedback))return!0;if(e)throw e.error;if(n.finishReason===void 0&&!n.hasPromptFeedback&&this.lastError)throw this.lastError.error;return!1}nextResumeToken(){let e=this.hop,n=this.reconnectsWithoutProgress;return e.finishReason!==void 0||e.hasPromptFeedback?e.finishReason===po.CONTINUATION&&!e.hasPromptFeedback&&e.token&&e.token!==e.startToken?[e.token,0]:[void 0,0]:e.token&&e.token!==e.startToken?[e.token,0]:e.hasYieldedContent||n>=Ek?[void 0,n]:[e.startToken,n+1]}};function Tg(t){return{startToken:t,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function Sk(t){var e;let n=(e=t?.candidates)===null||e===void 0?void 0:e[0];if(n?.continuationToken&&hc(n.finishReason))return n.continuationToken}function D_(t,e,n=!1){let r=t?.automaticContinuation!==void 0&&t?.automaticContinuation!==null,i=n&&r;if(!e&&!i)return t;if(!t)return e?{continuationToken:e}:void 0;let o=Object.assign({},t);return e&&(o.continuationToken=e),i&&delete o.automaticContinuation,o}function Ik(t,e){var n,r;let i=new Map,o=[];for(let a of[...t,...e]){let u=a.modality;i.has(u)||(i.set(u,0),o.push(u)),i.set(u,((n=i.get(u))!==null&&n!==void 0?n:0)+((r=a.tokenCount)!==null&&r!==void 0?r:0))}return o.map(a=>{var u;return{modality:a,tokenCount:(u=i.get(a))!==null&&u!==void 0?u:0}})}function wk(t,e){let n=new Map,r=[];for(let i of[...t,...e]){let o=i.category;n.has(o)||r.push(o),n.set(o,i)}return r.map(i=>n.get(i))}function Cg(t){if(typeof t!="object"||t===null||Array.isArray(t)||t instanceof Ht)return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||t instanceof yt||t instanceof kl||t instanceof go}function Ag(t,e){return t.endsWith("TokensDetails")?!0:e.length>0&&typeof e[0]=="object"&&e[0]!==null&&"modality"in e[0]}function Rk(t,e){if(t.length===0)return e;if(e.length===0)return t.map(i=>Lr(i,{},!0,!1));let n=[],r=Math.min(t.length,e.length);for(let i=0;i<r;i++)n.push(Lr(t[i],e[i],!0,!1));return t.length>r&&n.push(...t.slice(r)),e.length>r&&n.push(...e.slice(r)),n}function Po(t){var e;if(t)return(e=t._initialPromptTokenCount)!==null&&e!==void 0?e:t.promptTokenCount}function Mr(t,e){let n=e??Po(t);return n!==void 0&&Object.defineProperty(t,"_initialPromptTokenCount",{value:n,enumerable:!1,configurable:!0,writable:!0}),!(t instanceof go)&&!Object.prototype.hasOwnProperty.call(t,"initialPromptTokenCount")&&Object.defineProperty(t,"initialPromptTokenCount",{get(){return Po(this)},enumerable:!1,configurable:!0}),t}function b_(t,e){var n;if(!e)return t&&Mr(t);if(!t)return Mr(e);let r=(n=Po(t))!==null&&n!==void 0?n:Po(e),i=Lr(t,e,!1,!0);return Mr(i,r)}function Pk(t,e){let n=e.groundingMetadata,r=n?.groundingSupports;if(!Array.isArray(r)||r.length===0)return e;let i=t.content,o=Array.isArray(i?.parts)?i.parts.length:0,a=t.groundingMetadata,u=Array.isArray(a?.groundingChunks)?a.groundingChunks.length:0;if(o===0&&u===0)return e;let c=r.map(d=>{var f;if(!d||typeof d!="object")return d;let p=Object.assign({},d);return u>0&&Array.isArray(d.groundingChunkIndices)&&d.groundingChunkIndices.length>0&&(p.groundingChunkIndices=d.groundingChunkIndices.map(h=>h+u)),o>0&&d.segment&&typeof d.segment=="object"&&(p.segment=Object.assign(Object.assign({},d.segment),{partIndex:((f=d.segment.partIndex)!==null&&f!==void 0?f:0)+o})),p});return Object.assign(Object.assign({},e),{groundingMetadata:Object.assign(Object.assign({},n),{groundingSupports:c})})}function Lr(t,e,n=!1,r=!1){n&&(e=Pk(t,e));let i={},o=new Set([...Object.keys(t),...Object.keys(e)]);for(let a of o){let u=t[a],c=e[a];if(n&&(a==="continuationToken"||a==="finishReason"||a==="finishMessage")){c!==void 0&&(i[a]=c);continue}if(!n&&!r&&a==="candidates"&&Array.isArray(u)){i[a]=Rk(u,Array.isArray(c)?c:[]);continue}if(a==="usageMetadata"){let d=b_(u,c);d!==void 0&&(i[a]=d);continue}c==null?u!==void 0&&(i[a]=u):u==null?i[a]=c:typeof u=="number"&&typeof c=="number"&&(r||a==="tokenCount"||a.endsWith("TokenCount")||a.endsWith("Count")||a.endsWith("Sum"))?i[a]=u+c:Array.isArray(u)&&Array.isArray(c)?Ag(a,u)||Ag(a,c)?i[a]=Ik(u,c):a==="safetyRatings"?i[a]=wk(u,c):i[a]=[...u,...c]:Cg(u)&&Cg(c)?i[a]=Lr(u,c,!1,a==="usageMetadata"||r):i[a]=c}return i}function kk(t){if(t.length===0)return new yt;if(t.length===1)return t[0].usageMetadata&&Mr(t[0].usageMetadata),t[0];let e=t[0];for(let r=1;r<t.length;r++)e=Lr(e,t[r],!1,!1);let n=new yt;return Object.assign(n,e),n}var nr=class t extends vt{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Fe(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=Fe(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let o=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:mo.EMBED_CONTENT});return await this.embedContentInternal(o)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:mo.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var r,i,o,a,u;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!vk(n)||yg(n.config))return fo(n.config,!0)?await this.generateContentWithContinuation(c):await this.generateContentInternal(c);let d=vg(n);if(d.length>0){let m=d.map(v=>`tools[${v}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${m}.`)}let f,p,h=Fe(c.contents),g=(o=(i=(r=c.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:_g,_=0;for(;_<g&&(f=await this.generateContentWithContinuation(c),!(!f.functionCalls||f.functionCalls.length===0));){let m=f.candidates[0].content,v=[];for(let y of(u=(a=n.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[])if(tr(y)){let C=await y.callTool(f.functionCalls);v.push(...C)}_++,p={role:"user",parts:v},c.contents=Fe(c.contents),c.contents.push(m),c.contents.push(p),Eg(c.config)&&(h.push(m),h.push(p))}return Eg(c.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var r,i,o,a,u;if(this.maybeMoveToResponseJsonSchema(n),yg(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return fo(n.config,!0)?await this.generateContentStreamWithContinuation(p):await this.generateContentStreamInternal(p)}let c=vg(n);if(c.length>0){let p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let d=(o=(i=(r=n?.config)===null||r===void 0?void 0:r.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||o===void 0?void 0:o.streamFunctionCallArguments,f=(u=(a=n?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>(t.loggedGenerateImagesWarning||(t.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(n).then(r=>{var i;let o,a=[];if(r?.generatedImages)for(let c of r.generatedImages)c&&c?.safetyAttributes&&((i=c?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?o=c?.safetyAttributes:a.push(c);let u;return o?u={generatedImages:a,positivePromptSafetyAttributes:o,sdkHttpResponse:r.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:r.sdkHttpResponse},u})),this.list=async n=>{var r;let a={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((r=a.config)===null||r===void 0)&&r.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");a.config.filter="labels.tune-type:*"}return new $t(Vt.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{t.loggedEditImageWarning||(t.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let r={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(r.referenceImages=n.referenceImages.map(i=>i.toReferenceImageAPI())),await this.editImageInternal(r)},this.upscaleImage=async n=>{let r={numberOfImages:1,mode:"upscale"};n.config&&(r=Object.assign(Object.assign({},r),n.config));let i={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:r};return await this.upscaleImageInternal(i)},this.generateVideos=async n=>{var r,i,o,a,u,c;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(n.prompt||n.image||n.video)&&(t.loggedGenerateVideosWarning||(t.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((r=n.video)===null||r===void 0)&&r.uri&&(!((i=n.video)===null||i===void 0)&&i.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(o=n.source)===null||o===void 0?void 0:o.video)===null||a===void 0)&&a.uri&&(!((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}async generateContentWithContinuation(e){let n=fo(e.config,!0),r,i=[];for(;i.length===0||n&&r;){let o=D_(e.config,r),a=o===e.config?e:Object.assign(Object.assign({},e),{config:o}),u=await this.generateContentInternal(a);i.push(u),r=Sk(u)}return kk(i)}async generateContentStreamWithContinuation(e){let n=new Ak(e.config);n.startHop();let r=await this.generateContentStreamInternal(e);return(function(i,o,a){return Bt(this,arguments,function*(){var u,c,d,f;let p=async()=>a;for(;;){let m;try{try{for(var h=!0,g=(c=void 0,Cn(yield se(p()))),_;_=yield se(g.next()),u=_.done,!u;h=!0){f=_.value,h=!1;let y=f;yield yield se(n.observe(y))}}catch(y){c={error:y}}finally{try{!h&&!u&&(d=g.return)&&(yield se(d.call(g)))}finally{if(c)throw c.error}}}catch(y){m={error:y}}if(!n.endHop(m))return yield se(void 0);let v=Object.assign(Object.assign({},o),{config:n.startHop()});p=()=>i.generateContentStreamInternal(v)}})})(this,e,r)}maybeMoveToResponseJsonSchema(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,r,i;let o=(n=e.config)===null||n===void 0?void 0:n.tools;if(!o)return e;let a=await Promise.all(o.map(async c=>tr(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(u.config.tools=a,e.config&&e.config.tools&&k_(e.config.tools)){let c=(i=(r=e.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&i!==void 0?i:{},d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),x_(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,r,i;let o=new Map;for(let a of(r=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&r!==void 0?r:[])if(tr(a)){let u=a,c=await u.tool();for(let d of(i=c.functionDeclarations)!==null&&i!==void 0?i:[]){if(!d.name)throw new Error("Function declaration name is required.");if(o.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);o.set(d.name,u)}}return o}async processAfcStream(e){var n,r,i;let o=(i=(r=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&i!==void 0?i:_g,a=!1,u=0,c=await this.initAfcToolsMap(e);return(function(d,f,p){return Bt(this,arguments,function*(){for(var h,g,_,m,v,y;u<o;){a&&(u++,a=!1);let I=yield se(d.processParamsMaybeAddMcpUsage(p)),k=yield se(d.generateContentStreamWithContinuation(I)),O=[],B=[];try{for(var E=!0,C=(g=void 0,Cn(k)),A;A=yield se(C.next()),h=A.done,!h;E=!0){m=A.value,E=!1;let D=m;if(yield yield se(D),D.candidates&&(!((v=D.candidates[0])===null||v===void 0)&&v.content)){B.push(D.candidates[0].content);for(let q of(y=D.candidates[0].content.parts)!==null&&y!==void 0?y:[])if(u<o&&q.functionCall){if(!q.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(q.functionCall.name)){let H=yield se(f.get(q.functionCall.name).callTool([q.functionCall]));O.push(...H)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, missing tool: ${q.functionCall.name}`)}}}}catch(D){g={error:D}}finally{try{!E&&!h&&(_=C.return)&&(yield se(_.call(C)))}finally{if(g)throw g.error}}if(O.length>0){a=!0;let D=new yt;D.candidates=[{content:{role:"user",parts:O}}],yield yield se(D);let q=[];q.push(...B),q.push({role:"user",parts:O});let H=Fe(p.contents).concat(q);p.contents=H}else break}})})(this,c,e)}async generateContentInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=fg(this.apiClient,e);return u=W("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=hg(f),h=new yt;return Object.assign(h,p),h})}else{let d=dg(this.apiClient,e);return u=W("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=pg(f),h=new yt;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=fg(this.apiClient,e);return u=W("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),a.then(function(p){return Bt(this,arguments,function*(){var h,g,_,m;try{for(var v=!0,y=Cn(p),E;E=yield se(y.next()),h=E.done,!h;v=!0){m=E.value,v=!1;let C=m,A=hg(yield se(C.json()),e);A.sdkHttpResponse={headers:C.headers};let I=new yt;Object.assign(I,A),yield yield se(I)}}catch(C){g={error:C}}finally{try{!v&&!h&&(_=y.return)&&(yield se(_.call(y)))}finally{if(g)throw g.error}}})})}else{let d=dg(this.apiClient,e);return u=W("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),a.then(function(p){return Bt(this,arguments,function*(){var h,g,_,m;try{for(var v=!0,y=Cn(p),E;E=yield se(y.next()),h=E.done,!h;v=!0){m=E.value,v=!1;let C=m,A=pg(yield se(C.json()),e);A.sdkHttpResponse={headers:C.headers};let I=new yt;Object.assign(I,A),yield yield se(I)}}catch(C){g={error:C}}finally{try{!v&&!h&&(_=y.return)&&(yield se(_.call(y)))}finally{if(g)throw g.error}}})})}}async embedContentInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=mR(this.apiClient,e,e),f=kS(e.model)?"{model}:embedContent":"{model}:predict";return u=W(f,d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(h=>{let g=h;return g.sdkHttpResponse={headers:p.headers},g})),a.then(p=>{let h=_R(p,e),g=new _o;return Object.assign(g,h),g})}else{let d=hR(this.apiClient,e);return u=W("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=gR(f),h=new _o;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=wR(this.apiClient,e);return o=W("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=RR(c),f=new xl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=cR(this.apiClient,e);return o=W("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=dR(c),f=new Nl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=AP(this.apiClient,e);return o=W("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=SP(c),f=new Dl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=tP(this.apiClient,e);return o=W("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=nP(c),f=new bl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=uP(this.apiClient,e);return o=W("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=cP(c),f=new Ml;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=OR(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>nu(f))}else{let d=GR(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>tu(f))}}async listInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=XR(this.apiClient,e);return u=W("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=WR(f),h=new yo;return Object.assign(h,p),h})}else{let d=$R(this.apiClient,e);return u=W("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=JR(f),h=new yo;return Object.assign(h,p),h})}}async update(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=TP(this.apiClient,e);return u=W("{model}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>nu(f))}else{let d=EP(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>tu(f))}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=sR(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=lR(f),h=new vo;return Object.assign(h,p),h})}else{let d=oR(this.apiClient,e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=aR(f),h=new vo;return Object.assign(h,p),h})}}async countTokens(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=nR(this.apiClient,e);return u=W("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=iR(f),h=new Eo;return Object.assign(h,p),h})}else{let d=tR(this.apiClient,e);return u=W("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=rR(f),h=new Eo;return Object.assign(h,p),h})}}async computeTokens(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=Kw(this.apiClient,e);return o=W("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=Yw(c),f=new Ul;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=xR(this.apiClient,e);return o=W("{model}:predictLongRunning",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=kR(c),f=new Gl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};nr.loggedGenerateImagesWarning=!1;nr.loggedEditImageWarning=!1;nr.loggedGenerateVideosWarning=!1;var uu=class extends vt{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let n=e.operation,r=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],o;r&&"httpOptions"in r&&(o=r.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let n=e.operation,r=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],o;r&&"httpOptions"in r&&(o=r.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=gS(e);return u=W("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a}else{let d=mS(e);return u=W("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=lS(e);return o=W("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function xk(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Nk(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>qk(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function Dk(t,e,n){let r={},i=s(e,["expireTime"]);n!==void 0&&i!=null&&l(n,["expireTime"],i);let o=s(e,["newSessionExpireTime"]);n!==void 0&&o!=null&&l(n,["newSessionExpireTime"],o);let a=s(e,["uses"]);n!==void 0&&a!=null&&l(n,["uses"],a);let u=s(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&l(n,["bidiGenerateContentSetup"],Lk(t,u));let c=s(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&l(n,["fieldMask"],c),r}function bk(t,e){let n={},r=s(e,["config"]);return r!=null&&l(n,["config"],Dk(t,r,n)),n}function Mk(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Uk(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],xk(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Gk(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function Ok(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],r);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],fc(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],Nk(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let q=cn(m);Array.isArray(q)&&(q=q.map(H=>Hk(un(H)))),l(e,["setup","tools"],q)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],Bk(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let A=s(t,["contextWindowCompression"]);e!==void 0&&A!=null&&l(e,["setup","contextWindowCompression"],A);let I=s(t,["proactivity"]);if(e!==void 0&&I!=null&&l(e,["setup","proactivity"],I),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let k=s(t,["avatarConfig"]);e!==void 0&&k!=null&&l(e,["setup","avatarConfig"],k);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let q=O;Array.isArray(q)&&(q=q.map(H=>Fk(H))),l(e,["setup","safetySettings"],q)}let B=s(t,["translationConfig"]);e!==void 0&&B!=null&&l(e,["setup","generationConfig","translationConfig"],B);let D=s(t,["labels"]);return e!==void 0&&D!=null&&l(e,["setup","labels"],D),n}function Lk(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],Ee(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],Ok(i,n)),n}function qk(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],Mk(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function Fk(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function Bk(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Hk(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],Uk(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],Gk(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function Vk(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(typeof r=="object"&&r!=null&&!Array.isArray(r)&&Object.keys(r).length>0){let i=Object.keys(r).map(o=>`${n}.${o}`);e.push(...i)}else e.push(n)}return e.join(",")}function $k(t,e){let n=null,r=t.bidiGenerateContentSetup;if(typeof r=="object"&&r!==null&&"setup"in r){let o=r.setup;typeof o=="object"&&o!==null?(t.bidiGenerateContentSetup=o,n=o):delete t.bidiGenerateContentSetup}else r!==void 0&&delete t.bidiGenerateContentSetup;let i=t.fieldMask;if(n){let o=Vk(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)o?t.fieldMask=o:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],u=[];i.length>0&&(u=i.map(d=>a.includes(d)?`generationConfig.${d}`:d));let c=[];o&&c.push(o),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?t.fieldMask=i.join(","):delete t.fieldMask;return t}var cu=class extends vt{constructor(e){super(),this.apiClient=e}async create(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let u=bk(this.apiClient,e);o=W("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;let c=$k(u,e.config);return i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(d=>d.json()),i.then(d=>d)}}};function Xk(t,e){let n={},r=s(t,["force"]);return e!==void 0&&r!=null&&l(e,["_query","force"],r),n}function Jk(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let r=s(t,["config"]);return r!=null&&Xk(r,e),e}function Wk(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function Kk(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function Yk(t){let e={},n=s(t,["parent"]);n!=null&&l(e,["_url","parent"],n);let r=s(t,["config"]);return r!=null&&Kk(r,e),e}function zk(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["documents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["documents"],o)}return e}var du=class extends vt{constructor(e){super(),this.apiClient=e,this.list=async n=>new $t(Vt.PAGED_ITEM_DOCUMENTS,r=>this.listInternal({parent:n.parent,config:r.config}),await this.listInternal(n),n)}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Wk(e);return o=W("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Jk(e);i=W("{name}",a._url),o=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Yk(e);return o=W("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=zk(c),f=new ql;return Object.assign(f,d),f})}}};var fu=class extends vt{constructor(e,n=new du(e)){super(),this.apiClient=e,this.documents=n,this.list=async(r={})=>new $t(Vt.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(r),r)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let r=new URL(e,"http://dummy.com"),i=r.pathname;if(i.startsWith("/")&&(i=i.slice(1)),!i.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);let o={};r.searchParams.forEach((c,d)=>{o[d]=c}),o.alt="media";let a=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:o,httpOptions:a});if(u instanceof Ht){let c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=kP(this.apiClient,e);return o=W("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=DP(e);return o=W("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=NP(e);i=W("{name}",a._url),o=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=LP(e);return o=W("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=qP(c),f=new Fl;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=FP(e);return o=W("upload/{api_version}/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=BP(c),f=new Bl;return Object.assign(f,d),f})}}async importFile(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=UP(e);return o=W("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=MP(c),f=new Hl;return Object.assign(f,d),f})}}};var Qk=3,Zk="automatic_continuation: false cannot be used with background: true.",jk="Interaction stopped before completion (status='requires_continuation') with a continuation_token because the per-request decode token limit was reached. To resume decoding automatically, pass automatic_continuation: true (note: each continuation hop re-prefills and bills input tokens), or use background: true (the most cost-efficient option for server-managed continuation), or resume manually by passing continuation_token to interactions.create() (with previous_interaction_id set to this interaction's id and no input, or with the original input when store: false).",ex=new Set([void 0,"in_progress","requires_continuation"]),tx=new Set(["interaction.created","interaction.status_update"]),Sg={cached_tokens_by_modality:["modality","tokens"],input_tokens_by_modality:["modality","tokens"],output_tokens_by_modality:["modality","tokens"],tool_use_tokens_by_modality:["modality","tokens"],grounding_tool_count:["type","count"]},Ig=!1;function Ho(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ae(t,e){return Ho(t)?t[e]:void 0}function Ke(t){return typeof t=="string"&&t?t:void 0}function pu(t){return typeof t=="number"&&Number.isInteger(t)}function Ur(t){return t==null}var rr=class t extends Error{constructor(e){super(e),this.name="ContinuationTimeoutError",Object.setPrototypeOf(this,t.prototype)}},qr=class{constructor(e,n={}){var r,i;this.timeoutMs=e,this.now=(r=n.now)!==null&&r!==void 0?r:Date.now,(!((i=n.enabled)!==null&&i!==void 0)||i)&&typeof e=="number"&&Number.isFinite(e)&&(this.deadlineMs=this.now()+e)}get bounded(){return this.deadlineMs!==void 0}remainingMs(){if(this.deadlineMs!==void 0)return this.deadlineMs-this.now()}expired(){let e=this.remainingMs();return e!==void 0&&e<=0}hopTimeoutMs(){let e=this.remainingMs();return e===void 0?this.timeoutMs:Math.max(1,Math.ceil(e))}check(){if(this.expired())throw new rr(`interactions.create() timed out after ${this.timeoutMs} ms before automatic continuation finished. Increase the timeout (it bounds the whole call, across continuation hops) or resume from the continuation_token.`)}};function nx(t){return!Ur(Ae(t,"agent"))||!Ur(Ae(t,"agent_config"))}function rx(t,e,n){if(!(!!n&&t.store!==!1))return Object.assign(Object.assign({},t),{continuation_token:e});let{input:i}=t,o=Ie(t,["input"]);return Object.assign(Object.assign({},o),{continuation_token:e,previous_interaction_id:n})}function ix(t,e){let n=t.background===!0,r=t.stream===!0;if(n&&e===!1)throw new Error(Zk);let i=(e??!0)!==!1&&!n&&!nx(t);return{body:t,stream:r,callerToken:Ke(t.continuation_token),enableContinuation:i}}function wg(t,e,n){return e===void 0?t.body:rx(t.body,e,n)}function M_(){Ig||(Ig=!0,console.warn(jk))}function ox(t){O_(t)&&M_()}function sx(t){return Bt(this,arguments,function*(){var n,r,i,o;let a,u;try{for(var c=!0,d=Cn(t),f;f=yield se(d.next()),n=f.done,!n;c=!0){o=f.value,c=!1;let p=o;[a,u]=U_(p,a,u),yield yield se(p)}}catch(p){r={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield se(i.call(d)))}finally{if(r)throw r.error}}a==="requires_continuation"&&u&&M_()})}function U_(t,e,n){let r=Ae(t,"event_type");if(r==="error")return["error",void 0];let i=Ae(t,"interaction");if(i!=null){let u=Ke(Ae(i,"status"));u&&(e=u);let c=Ke(Ae(i,"continuation_token"));(r==="interaction.completed"||c)&&(n=c)}let o=Ke(Ae(t,"status"));o&&(e=o);let a=Ke(Ae(t,"continuation_token"));return a&&(n=a),[e,n]}function ax(t,e){let n=Ae(t,"event_type");return n==="interaction.status_update"?Ke(Ae(t,"continuation_token"))?!1:e:n==="interaction.completed"?!1:typeof n=="string"&&tx.has(n)?e:!0}function lx(t){var e;return(e=Ke(Ae(t,"interaction_id")))!==null&&e!==void 0?e:Ke(Ae(Ae(t,"interaction"),"id"))}function Rg(t,e){return!!e&&ex.has(t)}function ux(t,e,n,r){return e==="requires_continuation"||r!==n?0:t+1}var hu=class{constructor(e){this.options=e,this.hopIds=[],this.noProgressReconnects=0,this.nextToken=e.initialContinuationToken,this.initialToken=e.initialContinuationToken,this.hop={startToken:this.nextToken,startTokenOwnerId:void 0,token:this.nextToken,tokenOwnerId:void 0,interactionId:void 0,status:void 0,streamOpened:!1,contentSinceCheckpoint:!1}}startHop(e=!1){return this.hop={startToken:this.nextToken,startTokenOwnerId:this.nextTokenOwnerId,token:this.nextToken,tokenOwnerId:this.nextTokenOwnerId,interactionId:void 0,status:void 0,streamOpened:e,contentSinceCheckpoint:!1},[this.nextToken,this.nextTokenOwnerId]}markStreamOpened(){this.hop.streamOpened=!0}observe(e){let n=this.hop;n.streamOpened=!0;let r=lx(e);r&&(n.interactionId=r,this.hopIds.includes(r)||this.hopIds.push(r));let i=n.token;return[n.status,n.token]=U_(e,n.status,n.token),n.token&&n.token!==i&&(n.tokenOwnerId=n.interactionId),n.contentSinceCheckpoint=ax(e,n.contentSinceCheckpoint),e}canResumeHop(){let e=this.hop;return!e.contentSinceCheckpoint&&Rg(e.status,e.token)}fail(e){let n=this.hop,r=Rg(n.status,n.token)?n.token:void 0;return!r||r===this.initialToken?e.error:new Ro({message:`Automatic continuation of the stream was interrupted: ${G_(e.error)}. The continuationToken can be used to resume (output yielded after a mid-hop checkpoint is re-generated).`,cause:e.error,partialInteraction:void 0,continuationToken:r,interactionId:this.options.store!==!1?n.tokenOwnerId:void 0,continuationIds:[...this.hopIds]})}endHop(e){var n,r;let i=this.hop;if(e&&(e.error instanceof rr||!((r=(n=this.options).isFatalError)===null||r===void 0)&&r.call(n,e.error)))throw this.fail(e);if(e&&!i.streamOpened&&!this.options.isConnectionError(e.error))throw this.fail(e);if(!this.canResumeHop()){if(e)throw this.fail(e);return!1}if(i.status==="requires_continuation"&&i.token===i.startToken){if(e)throw this.fail(e);return!1}if(this.noProgressReconnects=ux(this.noProgressReconnects,i.status,i.startToken,i.token),this.noProgressReconnects===0&&(this.lastError=void 0),e&&(this.lastError=e),this.noProgressReconnects>Qk){if(this.lastError)throw this.fail(this.lastError);return!1}return this.nextToken=i.token,this.nextTokenOwnerId=i.tokenOwnerId,!0}};function G_(t){return t instanceof Error?t.message||t.name:String(t)}async function Pg(t){if(t?.return)try{await t.return()}catch{}}function cx(t,e,n){return Bt(this,arguments,function*(){var i,o;let a=(i=n.deadline)!==null&&i!==void 0?i:new qr(void 0),u=(o=n.wrapIterationError)!==null&&o!==void 0?o:(p=>p),c=new hu({initialContinuationToken:n.initialContinuationToken,isConnectionError:n.isConnectionError,isFatalError:n.isFatalError,store:n.store}),d,f=!0;try{for(;;){let[p,h]=c.startHop(f),g;if(f)f=!1,d=t[Symbol.asyncIterator]();else{yield se(Pg(d)),d=void 0;try{a.check();let _=yield se(e(p,h));c.markStreamOpened(),d=_[Symbol.asyncIterator]()}catch(_){g={error:_}}}if(!g&&d)for(;;){let _;try{a.check(),_=yield se(d.next())}catch(m){g={error:m instanceof rr?m:u(m)};break}if(_.done)break;yield yield se(c.observe(_.value))}if(!c.endHop(g))break}}finally{yield se(Pg(d))}})}function O_(t){if(Ae(t,"status")==="requires_continuation")return Ke(Ae(t,"continuation_token"))}function dx(t,e){let n=O_(t);if(n!==e)return n}function fx(t){return Ho(t)&&Array.isArray(t.steps)?t:void 0}function px(t,e,n,r){let i=q_(e,r),o=r.store!==!1&&Ae(e[0],"store")!==!1;return new Ro({message:`Automatic continuation was interrupted after ${e.length} completed hop(s): ${G_(t)}. The partial interaction (status 'requires_continuation') and its continuationToken can be used to resume.`,cause:t,partialInteraction:i,continuationToken:n,interactionId:o?Ke(Ae(e[e.length-1],"id")):void 0,continuationIds:L_(e)})}async function hx(t,e,n={}){var r;let i=(r=n.deadline)!==null&&r!==void 0?r:new qr(void 0),o=[t],a=n.initialContinuationToken;for(;;){let u=dx(o[o.length-1],a);if(!u)return q_(o,n);let c;try{i.check(),c=await e(u,Ke(Ae(o[o.length-1],"id")))}catch(d){throw px(d,o,u,n)}o.push(c),a=u}}function mx(t){let e=0;for(;e<t.length&&Ae(t[e],"type")==="user_input";)e++;return t.slice(e)}function L_(t){let e=[];for(let n of t){let r=Ae(n,"continuation_ids");if(Array.isArray(r))for(let o of r)Ke(o)&&e.push(o);let i=Ke(Ae(n,"id"));i&&e.push(i)}return Array.from(new Set(e))}function q_(t,e={}){var n,r;let i=(n=e.normalizeInteraction)!==null&&n!==void 0?n:fx,o=(r=e.finalizeInteraction)!==null&&r!==void 0?r:(p=>p),a=t[t.length-1],u=i(a);if(!u)return a;let c=[];t.forEach((p,h)=>{let g=Ae(p,"steps");Array.isArray(g)&&(h>0&&(g=mx(g)),c.push(...g))});let d=Object.assign(Object.assign({},u),{steps:c,continuation_ids:L_(t)});if(t.length>1)for(let p of["previous_interaction_id","created","input"]){let h=Ae(t[0],p);h===void 0?delete d[p]:d[p]=h}let f=_x(t.map(p=>Ae(p,"usage")).filter(Ho));return f!==void 0&&(d.usage=f),o(d)}function gx(t,e,n){let r=new Map;for(let i of t)for(let o of i){let a=Ae(o,e),u=Ae(o,n),c=r.get(a);if(c===void 0){r.set(a,o);continue}let d=Ae(c,n);pu(d)&&pu(u)&&Ho(c)&&r.set(a,Object.assign(Object.assign({},c),{[n]:d+u}))}return Array.from(r.values())}function _x(t){if(t.length===0)return;let e=t[0],n=t[t.length-1],r=[];for(let u of t)for(let c of Object.keys(u))r.includes(c)||r.push(c);let i={};for(let u of r){if(u==="initial_input_tokens")continue;let c=t.map(d=>d[u]).filter(d=>!Ur(d));if(c.length!==0){if(c.every(pu))i[u]=c.reduce((d,f)=>d+f,0);else if(u in Sg&&c.every(d=>Array.isArray(d))){let[d,f]=Sg[u];i[u]=gx(c,d,f)}}}let o=Ur(e.initial_input_tokens)?e.total_input_tokens:e.initial_input_tokens,a=Object.assign(Object.assign({},n),i);return Ur(o)?delete a.initial_input_tokens:a.initial_input_tokens=o,a}var yx=Object.prototype.hasOwnProperty;function ae(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(i={}){return t.replace(n,function(o,a){if(!yx.call(i,a))throw new Error(`Parameter '${a}' is required`);let u=i[a];if(typeof u!="string"&&typeof u!="number")throw new Error(`Parameter '${a}' must be a string or number`);return`${u}`}).replace(/^\/+/,"")}}var kg=["https://generativelanguage.googleapis.com"];function vx(t){var e;let n=t.server_url,r={};if(!n){let o=(e=t.server_idx)!==null&&e!==void 0?e:0;if(o<0||o>=kg.length)throw new Error(`Invalid server index ${o}`);n=kg[o]||""}let i=ae(n)(r);return new URL(i)}var F_={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function Ex(){return"Deno"in globalThis}var so;function Fr(){var t,e,n,r,i,o;if(so)return so;let a=globalThis,u={};return Ex()?u=(r=(n=(e=(t=a.Deno)===null||t===void 0?void 0:t.env)===null||e===void 0?void 0:e.toObject)===null||n===void 0?void 0:n.call(e))!==null&&r!==void 0?r:{}:u=(o=(i=a.process)===null||i===void 0?void 0:i.env)!==null&&o!==void 0?o:{},so=u,so}function Tx(t){var e,n;let r=Object.assign({},t),i=Fr();return typeof i.GOOGLE_GENAI_API_VERSION<"u"&&((e=r.api_version)!==null&&e!==void 0||(r.api_version=i.GOOGLE_GENAI_API_VERSION)),typeof i.GOOGLE_GENAI_USER_PROJECT<"u"&&((n=r.user_project)!==null&&n!==void 0||(r.user_project=i.GOOGLE_GENAI_USER_PROJECT)),r}var Cx=Symbol.for("undici.globalDispatcher.1"),mu=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return wx(await this.options.getAuthHeaders(e))}},gu=class{beforeCreateRequest(e,n){var r;let i=Object.assign({},(r=n.options)!==null&&r!==void 0?r:{});return Nx()&&!Dx(e.options.http_client)&&!("dispatcher"in i)&&(i.dispatcher=bx()),Object.assign(Object.assign({},n),{url:Ax(n.url),options:i})}async beforeRequest(e,n){if(Ng(n.headers,Ix(e.security_source)),Rx(e,n.headers),kx(n.headers))return n;let r=await Sx(e.security_source,n.url);return Ng(n.headers,r?.default_headers),Px(n.headers,r),n}};function Ax(t){let[,e,...n]=t.pathname.split("/");if(!e)return t;let r=decodeURIComponent(e);if(!r.includes("/"))return t;let i=new URL(t);return i.pathname=`/${r}/${n.join("/")}`,i}async function Sx(t,e){if(H_(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return B_(n)?xg(n):xg(void 0)}function Ix(t){var e,n;if(H_(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(B_(t))return t.default_headers}function xg(t){var e,n;let r=Fr(),i=Object.assign(Object.assign({},t),{api_key:(e=t?.api_key)!==null&&e!==void 0?e:r.GOOGLE_GENAI_API_KEY,access_token:(n=t?.access_token)!==null&&n!==void 0?n:r.GOOGLE_GENAI_ACCESS_TOKEN});return V_(i)?i:void 0}function wx(t){var e,n;let r={};for(let[o,a]of t){let u=o.toLowerCase();u!=="authorization"&&u!=="x-goog-api-key"&&(r[o]=a)}let i={access_token:(e=t.get("authorization"))!==null&&e!==void 0?e:void 0,api_key:(n=t.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(r).length?r:void 0};return V_(i)?i:void 0}function Ng(t,e){if(e)for(let[n,r]of new Headers(e)){let i=t.get(n);(i===null||n.toLowerCase()==="user-agent"&&i===F_.userAgent)&&t.set(n,r)}}function Rx(t,e){t.options.user_project!==void 0&&e.get("x-goog-user-project")===null&&e.set("x-goog-user-project",t.options.user_project)}function Px(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",xx(e.access_token))}}function kx(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function xx(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function B_(t){return typeof t=="object"&&t!==null}function H_(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function V_(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}function Nx(){var t,e;return typeof((e=(t=globalThis.process)===null||t===void 0?void 0:t.versions)===null||e===void 0?void 0:e.node)=="string"}function Dx(t){if(!t||typeof t!="object")return!1;if("options"in t){let e=t.options;return!!e?.fetcher}return!0}function bx(){return{dispatch(t,e){let n=globalThis[Cx];if(!n||typeof n.dispatch!="function")throw new TypeError("Undici globalDispatcher is not available in this Node.js runtime.");return n.dispatch(Object.assign(Object.assign({},t),{headersTimeout:0,bodyTimeout:0}),e)}}}var rn=class extends Error{constructor(e,n){let r=e;n?.cause&&(r+=`: ${n.cause}`),super(r,n),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=n?.cause)}},ko=class extends rn{constructor(){super(...arguments),this.name="UnexpectedClientError"}},jn=class extends rn{constructor(){super(...arguments),this.name="InvalidRequestError"}},xo=class extends rn{constructor(){super(...arguments),this.name="RequestAbortedError"}},No=class extends rn{constructor(){super(...arguments),this.name="RequestTimeoutError"}},Do=class extends rn{constructor(){super(...arguments),this.name="ConnectionError"}};var at=class extends Error{constructor(e,n){var r,i,o,a;super(e),this.statusCode=(r=n?.response)===null||r===void 0?void 0:r.status,this.body=(i=n?.body)!==null&&i!==void 0?i:"",this.headers=(o=n?.response)===null||o===void 0?void 0:o.headers,this.contentType=((a=n?.response)===null||a===void 0?void 0:a.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError",Object.setPrototypeOf(this,new.target.prototype)}};var _u=class extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},qe=class t extends _u{constructor(e,n,r,i){super(t.makeMessage(e,n,r)),this.status=e,this.headers=i,this.error=n,this.statusCode=e,this.body=bg(n),this.contentType=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,n,r){var i;let o=n&&Fx(n)&&typeof n.message=="string"?n.message:void 0,a=bg(n),u=(i=o??r)!==null&&i!==void 0?i:a||"An error occurred";return`${e?`${e} `:""}${u}`}static generate(e,n,r,i){return!e||!i?new on({message:r,cause:n instanceof Error?n:void 0}):e===400?new vu(e,n,r,i):e===401?new Eu(e,n,r,i):e===403?new Tu(e,n,r,i):e===404?new Cu(e,n,r,i):e===409?new Au(e,n,r,i):e===422?new Su(e,n,r,i):e===429?new Iu(e,n,r,i):e>=500?new wu(e,n,r,i):new t(e,n,r,i)}},ir=class extends qe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},on=class extends qe{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},yu=class extends on{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."})}},vu=class extends qe{},Eu=class extends qe{},Tu=class extends qe{},Cu=class extends qe{},Au=class extends qe{},Su=class extends qe{},Iu=class extends qe{},wu=class extends qe{};function tn(t){return Bx(t)?t:Mx(t)?Ux(t):Ox(t)?Lx(t):t}function Mx(t){return t instanceof at?!0:t instanceof Error&&typeof t.statusCode=="number"&&typeof t.body=="string"}function Ux(t){let e=qx(t),n=qe.generate(t.statusCode,e,t.message,t.headers);return Dr(n,"body",t.body),Dr(n,"contentType",t.contentType),Dr(n,"rawResponse",t.rawResponse),Dr(n,"statusCode",t.statusCode),Dr(n,"cause",t),n}var Gx=new Set(["HTTPClientError","UnexpectedClientError","InvalidRequestError","RequestAbortedError","RequestTimeoutError","ConnectionError"]);function Ox(t){return t instanceof rn?!0:t instanceof Error&&Gx.has(t.name)}function Lx(t){return t instanceof No||t.name==="RequestTimeoutError"?new yu({message:t.message}):t instanceof xo||t.name==="RequestAbortedError"?new ir({message:t.message}):t instanceof Do||t.name==="ConnectionError"?new on({message:t.message,cause:t}):new on({message:t.message,cause:t})}function qx(t){let e=Dg(t,"data$");if(e&&typeof e=="object")return e;try{let r=JSON.parse(t.body);if(r&&typeof r=="object")return r}catch{}let n=Dg(t,"error");return n&&typeof n=="object"?n:void 0}function Dg(t,e){return t&&typeof t=="object"?t[e]:void 0}function bg(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Fx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bx(t){return typeof t=="object"&&t!==null?qe.prototype.isPrototypeOf(t):!1}function Dr(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function Mg(t){try{return JSON.parse(t)}catch{return t}}function Hx(t,e={}){var n,r;let i=e.flattened===!0,o=(n=e.sentinel)!==null&&n!==void 0?n:"";return new bo(t,a=>o!==""&&a.data===o?{done:!0,value:void 0}:i?{done:!1,value:a.data==null?void 0:Mg(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:a.data==null?a.data:Mg(a.data)})},{dataRequired:(r=e.dataRequired)!==null&&r!==void 0?r:!0})}var $_=function(t,e){let n=new ReadableStream(t,e);return Object.setPrototypeOf(n,Object.getPrototypeOf(this)),n};$_.prototype=ReadableStream.prototype;var bo=class extends $_{constructor(e,n,r){var i;let o=e.getReader(),a=new Uint8Array(4096),u=0,c=0,d={eventId:void 0},f=(i=r?.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(p){try{for(;;){let h=$x(a,u,c);if(!h){c=Math.max(0,u-Vx+1);let m=await o.read();if(m.done)return p.close();if(u+m.value.length>a.length){let v=new Uint8Array(Math.max(a.length*2,u+m.value.length));v.set(a.subarray(0,u)),a=v}a.set(m.value,u),u+=m.value.length;continue}let g=a.slice(0,h.index);if(a.copyWithin(0,h.index+h.length,u),u-=h.index+h.length,a.length>4096&&u<=a.length>>2){let m=new Uint8Array(Math.max(4096,u*2));m.set(a.subarray(0,u)),a=m}c=0;let _=Xx(g,n,d,f);if(_&&!_.done)return p.enqueue(_.value);if(_?.done)return await o.cancel("done"),p.close()}}catch(h){p.error(h),await o.cancel(h)}},cancel:p=>o.cancel(p)})}[Symbol.asyncIterator](e){let n=ReadableStream.prototype[Symbol.asyncIterator];if(typeof n=="function")return n.call(this,e);let r=this.getReader(),i={next:async()=>{let a=await r.read();return a.done?(r.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await r.cancel(a),r.releaseLock(),{done:!0,value:void 0}),return:async()=>(await r.cancel("done"),r.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},o=Symbol.asyncDispose;return o&&(i[o]=async()=>{var a;await((a=i.return)===null||a===void 0?void 0:a.call(i))}),i}values(e){return this[Symbol.asyncIterator](e)}},ot=13,st=10,X_=[[ot,st,ot,st],[ot,st,ot],[ot,st,st],[ot,ot,st],[st,ot,st],[ot,ot],[st,ot],[st,st]],Vx=X_.reduce((t,e)=>Math.max(t,e.length),0);function $x(t,e,n){for(let r=n;r<e;r++)if(!(t[r]!==ot&&t[r]!==st))for(let i of X_){if(r+i.length>e)continue;let o=!0;for(let a=0;a<i.length;a++)if(t[r+a]!==i[a]){o=!1;break}if(o)return{index:r,length:i.length}}return null}function Xx(t,e,n,r){let o=new TextDecoder().decode(t).split(/\r\n|\r|\n/),a=[],u={},c=!0;for(let d of o){if(!d||d.startsWith(":"))continue;c=!1;let f=d.indexOf(":"),p=d,h="";f>0&&(p=d.slice(0,f),h=d[f+1]===" "?d.slice(f+2):d.slice(f+1)),p==="data"?a.push(h):p==="event"?u.event=h:p==="id"&&!h.includes("\0")?n.eventId=h:p==="retry"&&/^\d+$/.test(h)&&(u.retry=Number(h))}if(!c){if(u.id=n.eventId,a.length)u.data=a.join(`
|
|
41
|
+
`);else if(r)return;return e(u)}}var Jx=(t,e)=>e==null?fetch(t):fetch(t,e),Mo=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||Jx}async request(e){let n=e;for(let r of this.requestHooks){let i=await r(n);i&&(n=i)}try{let r=await this.fetcher(n);for(let i of this.responseHooks)await i(r,n);return r}catch(r){for(let i of this.requestErrorHooks)await i(r,n);throw r}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw new Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let n;if(e[0]==="beforeRequest")n=this.requestHooks;else if(e[0]==="requestError")n=this.requestErrorHooks;else if(e[0]==="response")n=this.responseHooks;else throw new Error(`Invalid hook type: ${e[0]}`);let r=n.findIndex(i=>i===e[1]);return r>=0&&n.splice(r,1),this}clone(){let e=new t(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}},Ug=/\s*;\s*/g;function Qn(t,e){var n;if(e==="*")return!0;let r=((n=t.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";r=r.toLowerCase();let i=e.toLowerCase().trim().split(Ug),[o="",...a]=i;if(o.split("/").length!==2)return!1;let u=r.split(Ug),[c="",...d]=u,[f="",p=""]=c.split("/");if(!f||!p||o!=="*/*"&&c!==o&&`${f}/*`!==o&&`*/${p}`!==o||d.length<a.length)return!1;let h=new Set(d);for(let g of a)if(!h.has(g))return!1;return!0}var Wx=new RegExp("^[0-9]xx$","i");function oe(t,e){let n=`${t.status}`,r=Array.isArray(e)?e:[e];return r.length?r.some(i=>{let o=`${i}`;if(o==="default")return!0;if(!Wx.test(`${o}`))return o===n;let a=o.charAt(0);if(!a)throw new Error("Invalid status code range");let u=n.charAt(0);if(!u)throw new Error(`Invalid response status code: ${n}`);return u===a}):!1}function Kx(t,e,n){return oe(t,e)&&Qn(t,n)}function J_(t){if(typeof t!="object"||t==null)return!1;let e=t instanceof TypeError&&t.message.toLowerCase().startsWith("failed to fetch"),n=t instanceof TypeError&&t.message.toLowerCase().startsWith("fetch failed"),r="name"in t&&t.name==="ConnectionError",i="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnreset";return e||n||i||r}function W_(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="TimeoutError",n="code"in t&&t.code===23,r="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||r}function Yx(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="AbortError",n="code"in t&&t.code===20,r="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||r}function zx(t){let e=new gu;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}var Uo=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let n of e)"sdkInit"in n&&this.registerSDKInitHook(n),"beforeCreateRequest"in n&&this.registerBeforeCreateRequestHook(n),"beforeRequest"in n&&this.registerBeforeRequestHook(n),"afterSuccess"in n&&this.registerAfterSuccessHook(n),"afterError"in n&&this.registerAfterErrorHook(n);zx(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((n,r)=>r.sdkInit(n),e)}beforeCreateRequest(e,n){let r=n;for(let i of this.beforeCreateRequestHooks)r=i.beforeCreateRequest(e,r);return r}async beforeRequest(e,n){let r=n;for(let i of this.beforeRequestHooks)r=await i.beforeRequest(e,r);return r}async afterSuccess(e,n){let r=n;for(let i of this.afterSuccessHooks)r=await i.afterSuccess(e,r);return r}async afterError(e,n,r){let i=n,o=r;for(let a of this.afterErrorHooks){let u=await a.afterError(e,i,o);i=u.response,o=u.error}return{response:i,error:o}}};function Gg(t){return{ok:!0,value:t}}function qt(t){return{ok:!1,error:t}}function mc(t){return btoa(String.fromCodePoint(...t))}function Qx(t){return new TextEncoder().encode(t)}function Zx(t){return mc(Qx(t))}function jx(...t){let e=[];for(let n of t)n&&e.push(n);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):eN(e)}}function eN(t){let e=new AbortController,n=e.signal;if(!t.length)return e.signal;if(t.length===1)return t[0]||e.signal;for(let a of t)if(a.aborted)return a;function r(){e.abort(this.reason),o()}let i=[];function o(){for(let a of i){let u=a.deref();u&&u.removeEventListener("abort",r)}}for(let a of t)i.push(new WeakRef(a)),a.addEventListener("abort",r);return n}function ue(t){let e={};for(let[n,r]of Object.entries(t))typeof r<"u"&&(e[n]=r);return e}function sn(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}var tN=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function K_(t,e){return Vo(t,e==="percentExceptReserved"?"percent":e)}function Vo(t,e){switch(e){case"percent":return encodeURIComponent(t);case"percentExceptReserved":return encodeURIComponent(t).replace(tN,n=>decodeURIComponent(n));default:return t}}function nN(t){return(e,n,r)=>{let i="",o=r?.explode?z_(e,n):[[e,n]];if(o.every(([d,f])=>f==null))return;let a=d=>Vo(d,r?.charEncoding),u=d=>a(Q_(d)),c=a(t);return o.forEach(([d,f])=>{var p,h;let g="",_=null;f!=null&&(Array.isArray(f)?_=(p=j_(f,m=>`${u(m)}`))===null||p===void 0?void 0:p.join(c):sn(f)?_=(h=ey(Object.entries(f),([m,v])=>`${a(m)}${c}${u(v)}`))===null||h===void 0?void 0:h.join(c):_=`${u(f)}`,_!=null&&(g=`${K_(d,r?.charEncoding)}=${_}`,!(!g||g==="=")&&(i+=`&${g}`)))}),i.slice(1)}}var Y_=nN(",");function ut(t,e,n){if(typeof e>"u")return;let i=(o=>Vo(o,n?.charEncoding))(JSON.stringify(e,Z_));return n?.explode?i:`${K_(t,n?.charEncoding)}=${i}`}var z=(t,e,n)=>{let r="",i=n?.explode?z_(t,e):[[t,e]];if(i.every(([u,c])=>c==null))return;let o=u=>Vo(u,n?.charEncoding),a=u=>o(Q_(u));return i.forEach(([u,c])=>{var d;let f="";if(c!=null){if(Array.isArray(c))f=(d=j_(c,p=>`${a(p)}`))===null||d===void 0?void 0:d.join(",");else if(sn(c)){let p=ey(Object.entries(c),([h,g])=>`,${o(h)},${a(g)}`);f=p?.join("").slice(1)}else f=`${n?.explode&&sn(e)?`${u}=`:""}${a(c)}`;r+=f?`,${f}`:""}}),r.slice(1)};function z_(t,e){return Array.isArray(e)?e.map(n=>[t,n]):sn(e)?Object.entries(e??{}).map(([r,i])=>[r,i]):[[t,e]]}function Q_(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?mc(t):typeof t=="object"?JSON.stringify(t,Z_):`${t}`}function Z_(t,e){return e instanceof Uint8Array?mc(e):e}function j_(t,e){let n=t.reduce((r,i)=>{if(i==null)return r;let o=e(i);return o==null||r.push(o),r},[]);return n.length?n:null}function ey(t,e){let n=[];for(let[r,i]of t){if(i==null)continue;let o=e([r,i]);o!=null&&n.push(o)}return n.length?n:null}function rN(...t){return t.filter(Boolean).join("&")}function iN(t){return function(n,r){var i,o,a;let u=Object.assign(Object.assign({},r),{explode:(i=r?.explode)!==null&&i!==void 0?i:!0,charEncoding:(o=r?.charEncoding)!==null&&o!==void 0?o:"percent"}),c=new Set((a=r?.allowEmptyValue)!==null&&a!==void 0?a:[]),d=Object.entries(n).map(([f,p])=>c.has(f)&&(p==null||p===""||Array.isArray(p)&&p.length===0)?`${encodeURIComponent(f)}=`:t(f,p,u));return rN(...d)}}var ct=iN(Y_);var Og={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},Br=class t extends Error{constructor(e,n){let r=e;n?.cause&&(r+=`: ${n.cause}`),super(r,n),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=n?.cause),Object.setPrototypeOf(this,t.prototype)}},an=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};async function oN(t,e){var n;switch(e.config.strategy){case"backoff":return lN(Lg(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:Og);case"attempt-count-backoff":return uN(Lg(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},Og),e.config.backoff),e.config);default:return await t(0)}}function Lg(t,e){return async n=>{try{let r=await t(n);if(aN(r,e.statusCodes))throw new an("Response failed with retryable status code",r);return r}catch(r){throw r instanceof an||e.retryConnectionErrors&&(W_(r)||J_(r))?r:new Br("Permanent error",{cause:r})}}}var sN=new RegExp("^[0-9]xx$","i");function aN(t,e){let n=`${t.status}`;return e.some(r=>{if(!sN.test(r))return r===n;let i=r.charAt(0);if(!i)throw new Error("Invalid status code range");let o=n.charAt(0);if(!o)throw new Error(`Invalid response status code: ${n}`);return o===i})}async function lN(t,e){let{maxElapsedTime:n,initialInterval:r,exponent:i,maxInterval:o}=e,a=Date.now(),u=0;for(;;)try{return await t(u)}catch(c){if(c instanceof Br)throw c.cause;if(Date.now()-a>n){if(c instanceof an)return c.response;throw c}let f=0;c instanceof an&&(f=ty(c.response)),f<=0&&(f=r*Math.pow(u,i)+Math.random()*1e3);let p=Math.min(f,o);await ny(p),u++}}async function uN(t,e,n){let r=0;for(;;)try{return await t(r)}catch(i){if(i instanceof Br)throw i.cause;if(r>=n.maxRetries){if(i instanceof an)return i.response;throw i}let o=0;i instanceof an&&(o=ty(i.response)),o<=0&&(o=e.initialInterval*Math.pow(e.exponent,r)*(1-Math.random()*.25));let a=Math.min(o,e.maxInterval);await ny(a),r++}}function ty(t){let e=t.headers.get("retry-after-ms");if(e){let o=Number(e);if(Number.isFinite(o)&&o>=0)return o}let n=t.headers.get("retry-after")||"";if(!n)return 0;let r=Number(n);if(Number.isInteger(r))return r*1e3;let i=Date.parse(n);if(Number.isInteger(i)){let o=i-Date.now();return o>0?Math.ceil(o):0}return 0}async function ny(t){return new Promise(e=>setTimeout(e,t))}var ao=typeof globalThis>"u"?null:globalThis,cN=typeof ao=="object"&&ao!=null&&"importScripts"in ao&&typeof ao.importScripts=="function",dN=cN||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",lt=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof Uo?this._hooks=n.hooks:this._hooks=new Uo;let r=new Mo;e.http_client=e.http_client||r,e=this._hooks.sdkInit(e);let i=vx(e);i&&(i.pathname=i.pathname.replace(/\/+$/,"")+"/"),this._baseURL=i,this._httpClient=e.http_client||r,this._options=Object.assign(Object.assign({},Tx(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Fr().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,r){var i,o,a,u,c;let{method:d,path:f,query:p,headers:h,security:g}=n,_=(i=n.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!_)return qt(new jn("No base URL provided for operation"));let m=new URL(_),v;f?(m.pathname=m.pathname.replace(/\/+$/,"")+"/",v=new URL(f,m),!v.search&&m.search&&(v.search=m.search)):v=m,v.hash="";let y=(L,X)=>{if(!X)return L;let Z=new Set(X.split("&").filter(_e=>_e!=="").map(_e=>{var pe;return(pe=_e.split("=")[0])!==null&&pe!==void 0?pe:""}));return[...L.split("&").filter(_e=>{var pe;return _e!==""&&!Z.has((pe=_e.split("=")[0])!==null&&pe!==void 0?pe:"")}),X].join("&")},E=L=>Object.entries(L).map(([X,Z])=>{if(Z==null)return;let ge=sn(Z)?JSON.stringify(Z):Z;return Y_(X,ge,{explode:Array.isArray(ge),charEncoding:"percent"})}).filter(X=>typeof X<"u").join("&"),C=[p||"",E(r?.extra_query||{}),E(g?.queryParams||{})].reduce(y,v.search.slice(1));C&&(v.search=`?${C}`);let A=new Headers(h),I=g?.basic.username,k=g?.basic.password;if(I!=null||k!=null){let L=Zx([I||"",k||""].join(":"));A.set("Authorization",`Basic ${L}`)}let O=new Headers(g?.headers||{});for(let[L,X]of O)A.set(L,X);let B=A.get("cookie")||"";for(let[L,X]of Object.entries(g?.cookies||{}))B+=`; ${L}=${X}`;B=B.startsWith("; ")?B.slice(2):B,A.set("cookie",B);let D=new Headers((o=r?.headers)!==null&&o!==void 0?o:(a=r?.fetch_options)===null||a===void 0?void 0:a.headers);for(let[L,X]of D)A.set(L,X);dN||A.set((u=n.uaHeader)!==null&&u!==void 0?u:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:F_.userAgent);let q=n.body,H=Object.fromEntries(Object.entries(r?.extra_body||{}).filter(([,L])=>typeof L<"u"));if(Object.keys(H).length>0){let L=new Headers(h).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(L)||typeof q!="string"&&q!=null)return qt(new jn("extra_body can only be merged into JSON object request bodies"));let Z;try{Z=q?JSON.parse(q):{}}catch(ge){return qt(new jn("extra_body can only be merged into JSON object request bodies",{cause:ge}))}if(!sn(Z))return qt(new jn("extra_body can only be merged into JSON object request bodies"));q=JSON.stringify(Object.assign(Object.assign({},Z),H)),A.delete("content-length")}let J=Object.assign(Object.assign({},r?.fetch_options),r);!J?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign(J,{duplex:"half"});let ne;try{ne=this._hooks.beforeCreateRequest(e,{url:v,options:Object.assign(Object.assign({},J),{body:q??null,headers:A,method:d})})}catch(L){return qt(new ko("Create request hook failed to execute",{cause:L}))}return Gg(new Request(ne.url,ne.options))}async _do(e,n){let{context:r,isErrorStatusCode:i}=n,o=r.timeout_ms;return oN(async()=>{var a;let u=e.clone(),c=u;if(o!=null&&o>0){let p=AbortSignal.timeout(o),h=(a=jx(u.signal,p))!==null&&a!==void 0?a:p;c=new Request(u,{signal:h})}let d=await this._hooks.beforeRequest(r,c);await fN(this._logger,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log request:",p)});let f=await this._httpClient.request(d);try{if(i(f.status)){let p=await this._hooks.afterError(r,f,null);if(p.error)throw p.error;f=p.response||f}else f=await this._hooks.afterSuccess(r,f)}finally{await pN(this._logger,f,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log response:",p)})}return f},{config:n.retryConfig,statusCodes:n.retryCodes}).then(a=>Gg(a),a=>{switch(!0){case Yx(a):return qt(new xo("Request aborted by client",{cause:a}));case W_(a):return qt(new No("Request timed out",{cause:a}));case J_(a):return qt(new Do("Unable to make request",{cause:a}));default:return qt(new ko("Unexpected HTTP client error",{cause:a}))}})}},ry=/^(application|text)\/([^+]+\+)*json.*/,qg=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function fN(t,e){if(!t)return;let n=e.headers.get("content-type"),r=n?.split(";")[0]||"";t.group(`> Request: ${e.method} ${e.url}`),t.group("Headers:");for(let[i,o]of e.headers.entries())t.log(`${i}: ${o}`);switch(t.groupEnd(),t.group("Body:"),!0){case ry.test(r):t.log(await e.clone().json());break;case r.startsWith("text/"):t.log(await e.clone().text());break;case r==="multipart/form-data":{let i=await e.clone().formData();for(let[o,a]of i){let u=a instanceof Blob?"<Blob>":a;t.log(`${o}: ${u}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function pN(t,e,n){if(!t)return;let r=e.headers.get("content-type"),i=r?.split(";")[0]||"";t.group(`< Response: ${n.method} ${n.url}`),t.log("Status Code:",e.status,e.statusText),t.group("Headers:");for(let[o,a]of e.headers.entries())t.log(`${o}: ${a}`);switch(t.groupEnd(),t.group("Body:"),!0){case(Qn(e,"application/json")||ry.test(i)&&!qg.test(i)):t.log(await e.clone().json());break;case(Qn(e,"application/jsonl")||qg.test(i)):case Qn(e,"text/event-stream"):t.log(`<${r}>`);break;case Qn(e,"text/*"):t.log(await e.clone().text());break;case Qn(e,"multipart/form-data"):{let o=await e.clone().formData();for(let[a,u]of o){let c=u instanceof Blob?"<Blob>":u;t.log(`${a}: ${c}`)}break}default:t.log(`<${r}>`);break}t.groupEnd(),t.groupEnd()}var Go=class extends at{constructor(e,n){e&&(e+=": "),e+=`Status ${n.response.status}`;let r=n.response.headers.get("content-type")||'""';r!=="application/json"&&(e+=` Content-Type ${r.includes(" ")?`"${r}"`:r}`);let i=n.body||'""';e+=i.length>100?`
|
|
42
|
+
`:". ";let o=i;if(i.length>1e4){let a=i.substring(0,1e4),u=i.length-1e4;o=`${a}...and ${u} more chars`}e+=`Body: ${o}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError",Object.setPrototypeOf(this,new.target.prototype)}};var hN={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function ln(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function me(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function iy(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function oy(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function Q(t){return{enc:"fail",codes:t}}function ce(...t){return async function(n,r,i){let o,a;for(let h of t){let{codes:g}=h,_="ctype"in h?h.ctype:hN[h.enc];if(_&&Kx(n,g,_)){a=h;break}else if(!_&&oe(n,g)){a=h;break}}if(!a)return[{ok:!1,error:new Go("Unexpected Status or Content-Type",{response:n,request:r,body:await n.text().catch(()=>"")})},o];let u=a.enc,c="";switch(u){case"json":c=await n.text();try{o=JSON.parse(c)}catch(h){if(!("err"in a))throw h;o=c}break;case"jsonl":o=n.body;break;case"bytes":o=new Uint8Array(await n.arrayBuffer());break;case"stream":o=n.body;break;case"text":c=await n.text(),o=c;break;case"sse":if(n.body){let h="sse"in a&&a.sse||{};o=Hx(n.body,h)}else o=null;break;case"nil":c=await n.text(),o=void 0;break;case"fail":c=await n.text(),o=c;break;default:throw new Error(`Unsupported response type: ${u}`)}if(a.enc==="fail")return[{ok:!1,error:new Go("API error occurred",{request:r,response:n,body:c})},o];let d=a.key||i?.resultKey,f,p=a.hdrs?{headers:gN(n.headers)}:null;return"err"in a?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),sn(o)?o:null):d?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),{[d]:o}):a.hdrs?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),sn(o)?o:null):f=o,"err"in a?[{ok:!1,error:a.errorClass?new a.errorClass(f,{request:r,response:n,body:c}):f},o]:[{ok:!0,value:f},o]}}var mN=/, */;function gN(t){let e={};for(let[n,r]of t.entries())e[n]=r.split(mN);return e}var Fg={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},Ru=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(Fg.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(Fg.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};function _N(...t){let e={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=t.find(r=>r.every(i=>{if(i.value==null)return!1;if(i.type==="http:basic")return i.value.username!=null||i.value.password!=null;if(i.type==="http:custom")return null;if(i.type==="oauth2:password")return typeof i.value=="string"&&!!i.value;if(i.type==="oauth2:client_credentials")return typeof i.value=="string"?!!i.value:i.value.client_id!=null||i.value.client_secret!=null;if(typeof i.value=="string")return!!i.value;throw new Error(`Unrecognized security type: ${i.type} (value type: ${typeof i.value})`)}));return n==null?null:(n.forEach(r=>{if(r.value==null)return;let{type:i}=r;switch(i){case"apiKey:header":e.headers[r.fieldName]=r.value;break;case"apiKey:query":e.queryParams[r.fieldName]=r.value;break;case"apiKey:cookie":e.cookies[r.fieldName]=r.value;break;case"http:basic":yN(e,r);break;case"http:custom":break;case"http:bearer":lo(e,r);break;case"oauth2":lo(e,r);break;case"oauth2:password":lo(e,r);break;case"oauth2:client_credentials":break;case"openIdConnect":lo(e,r);break;default:throw Ru.unrecognizedType(i)}}),e)}function yN(t,e){e.value!=null&&(t.basic=e.value)}function lo(t,e){if(typeof e.value!="string"||!e.value)return;let n=e.value;n.slice(0,7).toLowerCase()!=="bearer "&&(n=`Bearer ${n}`),e.fieldName!==void 0&&(t.headers[e.fieldName]=n)}function de(t,e){var n,r;let i=[[{fieldName:"accessToken",type:"http:custom",value:(n=t?.access_token)!==null&&n!==void 0?n:Fr().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(r=t?.api_key)!==null&&r!==void 0?r:Fr().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return _N(...i)}async function fe(t){if(t!=null)return typeof t=="function"?t():t}var sy,re=class t{constructor(e,n){this[sy]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=n??null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([n])=>n)}then(e,n){return this._promise.then(e?([r])=>e(r):void 0,n)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,r])=>r)).then(r=>{if(!r.response)throw new Error("APIPromise.asResponse: response unavailable");return r.response})}async withResponse(){let[[e],n]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:n}}_thenUnwrap(e){var n;let r=this._promise.then(([i,o])=>[e(i),o]);return r.catch(()=>{}),new t(r,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};sy=Symbol.toStringTag;function le(t){let e=t.$inspect(),n=e.then(([i,o])=>{if(!i.ok)throw i.error;return[i.value,o]}),r=e.then(([i,o])=>{var a;if(!i.ok&&!(!((a=o.response)===null||a===void 0)&&a.ok))throw i.error;return o});return n.catch(()=>{}),r.catch(()=>{}),new re(n,r)}function ay(t,e,n,r){return new re(vN(t,e,n,r))}async function vN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/agents")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function ly(t,e,n,r){return new re(EN(t,e,n,r))}async function EN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:z("agentsId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/agents/{agentsId}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function uy(t,e,n,r){return new re(TN(t,e,n,r))}async function TN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:z("agentsId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/agents/{agentsId}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function cy(t,e,n,r,i,o){return new re(CN(t,e,n,r,i,o))}async function CN(t,e,n,r,i,o){var a,u,c;let f={api_version:e,page_size:n,page_token:r,parent:i},p=null,h={api_version:z("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},g=ae("/{api_version}/agents")(h),_=ct({page_size:f?.page_size,page_token:f?.page_token,parent:f?.parent}),m=new Headers(ue({Accept:"application/json"})),v=await fe(t._options.security),y=de(v),E={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(E,{security:y,method:"GET",baseURL:o?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:E,isErrorStatusCode:B=>oe({status:B},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let k=I.value,[O]=await ce(Q("4XX"),Q("5XX"),me("default"))(k,A);return O.ok?[O,{status:"complete",request:A,response:k}]:[O,{status:"complete",request:A,response:k}]}var Pu=class extends lt{list(e,n){return le(cy(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return le(ay(this,i,r,n))}delete(e,n,r){return le(ly(this,e,n?.api_version,r))}get(e,n,r){return le(uy(this,e,n?.api_version,r))}};function dy(t,e,n,r){return new re(AN(t,e,n,r))}async function AN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/credentials")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function fy(t,e,n,r){return new re(SN(t,e,n,r))}async function SN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/credentials/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function py(t,e,n,r){return new re(IN(t,e,n,r))}async function IN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/credentials/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function hy(t,e,n,r,i){return new re(wN(t,e,n,r,i))}async function wN(t,e,n,r,i){var o,a,u;let d={api_version:e,page_size:n,page_token:r},f=null,p={api_version:z("api_version",(o=d?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/credentials")(p),g=ct({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(ue({Accept:"application/json"})),m=await fe(t._options.security),v=de(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let C=E.value,A=await t._do(C,{context:y,isErrorStatusCode:O=>oe({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[k]=await ce(Q("4XX"),Q("5XX"),me("default"))(I,C);return k.ok?[k,{status:"complete",request:C,response:I}]:[k,{status:"complete",request:C,response:I}]}function my(t,e,n,r,i,o){return new re(RN(t,e,n,r,i,o))}async function RN(t,e,n,r,i,o){var a,u,c;let f={id:e,body:n,api_version:r,update_mask:i},p=ut("body",f.body,{explode:!0}),h={api_version:z("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",f.id,{explode:!1,charEncoding:"percent"})},g=ae("/{api_version}/credentials/{id}")(h),_=ct({update_mask:f.update_mask}),m=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),v=await fe(t._options.security),y=de(v),E={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(E,{security:y,method:"PATCH",baseURL:o?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:E,isErrorStatusCode:B=>oe({status:B},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let k=I.value,[O]=await ce(Q("4XX"),Q("5XX"),me("default"))(k,A);return O.ok?[O,{status:"complete",request:A,response:k}]:[O,{status:"complete",request:A,response:k}]}var ku=class extends lt{list(e,n){return le(hy(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return le(dy(this,i,r,n))}delete(e,n,r){return le(fy(this,e,n?.api_version,r))}get(e,n,r){return le(py(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i,update_mask:o}=n,a=Ie(n,["api_version","update_mask"]);return le(my(this,e,a,i,o,r))}};function gy(t,e,n,r){return new re(PN(t,e,n,r))}async function PN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/environments")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function _y(t,e,n,r){return new re(kN(t,e,n,r))}async function kN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/environments/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function yy(t,e,n,r){return new re(xN(t,e,n,r))}async function xN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/environments/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function vy(t,e,n,r,i){return new re(NN(t,e,n,r,i))}async function NN(t,e,n,r,i){var o,a,u;let d={api_version:e,page_size:n,page_token:r},f=null,p={api_version:z("api_version",(o=d?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/environments")(p),g=ct({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(ue({Accept:"application/json"})),m=await fe(t._options.security),v=de(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let C=E.value,A=await t._do(C,{context:y,isErrorStatusCode:O=>oe({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[k]=await ce(Q("4XX"),Q("5XX"),me("default"))(I,C);return k.ok?[k,{status:"complete",request:C,response:I}]:[k,{status:"complete",request:C,response:I}]}function Ey(t,e,n,r,i,o,a,u){return new re(DN(t,e,n,r,i,o,a,u))}async function DN(t,e,n,r,i,o,a,u){var c,d,f;let h={environment:e,path:n,api_version:r,page_size:i,page_token:o,recursive:a},g=null,_={api_version:z("api_version",(c=h.api_version)!==null&&c!==void 0?c:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:z("environment",h.environment,{explode:!1,charEncoding:"percent"}),path:z("path",h.path,{explode:!1,charEncoding:"percentExceptReserved"})},m=ae("/{api_version}/environments/{environment}/files/{path}")(_),v=ct({page_size:h.page_size,page_token:h.page_token,recursive:h.recursive}),y=new Headers(ue({Accept:"application/json"})),E=await fe(t._options.security),C=de(E),A={options:t._options,base_url:(f=(d=u?.server_url)!==null&&d!==void 0?d:t._baseURL)!==null&&f!==void 0?f:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:C,security_source:t._options.security,retry_config:u?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:u?.retry_codes||["408","409","429","5XX"]},I=t._createRequest(A,{security:C,method:"GET",baseURL:u?.server_url,path:m,headers:y,query:v,body:g,userAgent:t._options.user_agent,timeout_ms:u?.timeout_ms||t._options.timeout_ms||-1},u);if(!I.ok)return[I,{status:"invalid"}];let k=I.value,O=await t._do(k,{context:A,isErrorStatusCode:q=>oe({status:q},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!O.ok)return[O,{status:"request-error",request:k}];let B=O.value,[D]=await ce(me(200),Q("4XX"),Q("5XX"))(B,k);return D.ok?[D,{status:"complete",request:k,response:B}]:[D,{status:"complete",request:k,response:B}]}var xu=class extends lt{list(e,n,r,i){return le(Ey(this,e,n,r?.api_version,r?.page_size,r?.page_token,r?.recursive,i))}};function Ty(t,e,n,r,i,o,a,u,c,d,f){return new re(bN(t,e,n,r,i,o,a,u,c,d,f))}async function bN(t,e,n,r,i,o,a,u,c,d,f){var p,h,g;let m={environment:e,path:n,"X-Goog-Upload-Command":r,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":o,"X-Goog-Upload-Protocol":a,api_version:u,extract:c,overwrite:d},v=null,y={api_version:z("api_version",(p=m.api_version)!==null&&p!==void 0?p:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:z("environment",m.environment,{explode:!1,charEncoding:"percent"}),path:z("path",m.path,{explode:!1,charEncoding:"percentExceptReserved"})},E=ae("/upload/{api_version}/environments/{environment}/files/{path}")(y),C=ct({extract:m.extract,overwrite:m.overwrite}),A=new Headers(ue({Accept:"*/*","X-Goog-Upload-Command":z("X-Goog-Upload-Command",m["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":z("X-Goog-Upload-Header-Content-Length",m["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":z("X-Goog-Upload-Header-Content-Type",m["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":z("X-Goog-Upload-Protocol",m["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),I=await fe(t._options.security),k=de(I),O={options:t._options,base_url:(g=(h=f?.server_url)!==null&&h!==void 0?h:t._baseURL)!==null&&g!==void 0?g:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:k,security_source:t._options.security,retry_config:f?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:f?.retry_codes||["408","409","429","5XX"]},B=t._createRequest(O,{security:k,method:"PUT",baseURL:f?.server_url,path:E,headers:A,query:C,body:v,userAgent:t._options.user_agent,timeout_ms:f?.timeout_ms||t._options.timeout_ms||-1},f);if(!B.ok)return[B,{status:"invalid"}];let D=B.value,q=await t._do(D,{context:O,isErrorStatusCode:L=>oe({status:L},["4XX","5XX"]),retryConfig:O.retry_config,retryCodes:O.retry_codes});if(!q.ok)return[q,{status:"request-error",request:D}];let H=q.value,J={httpMeta:{response:H,request:D}},[ne]=await ce(oy(200,{hdrs:!0}),Q("4XX"),Q("5XX"))(H,D,{extraFields:J});return ne.ok?[ne,{status:"complete",request:D,response:H}]:[ne,{status:"complete",request:D,response:H}]}var Nu=class extends lt{startUpload(e,n,r,i){return le(Ty(this,e,n,r["X-Goog-Upload-Command"],r["X-Goog-Upload-Header-Content-Length"],r["X-Goog-Upload-Header-Content-Type"],r["X-Goog-Upload-Protocol"],r.api_version,r.extract,r.overwrite,i))}};var Du=class extends lt{get internal(){var e;return(e=this._internal)!==null&&e!==void 0?e:this._internal=new Nu(this._options)}get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new xu(this._options)}listEnvironments(e,n){return le(vy(this,e?.api_version,e?.page_size,e?.page_token,n))}createEnvironment(e,n,r){return le(gy(this,e,n,r))}deleteEnvironment(e,n,r){return le(_y(this,e,n?.api_version,r))}getEnvironment(e,n,r){return le(yy(this,e,n?.api_version,r))}};var bu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},Mu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}};var Uu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},Gu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}};var Ou=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},Lu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}};var qu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},Fu=class extends at{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function Cy(t,e,n,r){return new re(MN(t,e,n,r))}async function MN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:z("interactionsId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/interactions/{interactionsId}/cancel")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:k=>oe({status:k},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,A={httpMeta:{response:C,request:y}},[I]=await ce(me(200),ln("4XX",Mu),ln("5XX",bu))(C,y,{extraFields:A});return I.ok?[I,{status:"complete",request:y,response:C}]:[I,{status:"complete",request:y,response:C}]}function Ay(t,e,n,r){return new re(UN(t,e,n,r))}async function UN(t,e,n,r){var i,o,a,u;let c={body:e,api_version:n},d=c,f=ut("body",d.body,{explode:!0}),p={api_version:z("api_version",(i=d.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/interactions")(p),g=new Headers(ue({"Content-Type":"application/json",Accept:!((o=c?.body)===null||o===void 0)&&o.stream?"text/event-stream":"application/json"})),_=await fe(t._options.security),m=de(_),v={options:t._options,base_url:(u=(a=r?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:r?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,C=await t._do(E,{context:v,isErrorStatusCode:O=>oe({status:O},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:E}];let A=C.value,I={httpMeta:{response:A,request:E}},[k]=await ce(me(200),iy(200,{sentinel:"[DONE]",flattened:!0}),ln("4XX",Gu),ln("5XX",Uu))(A,E,{extraFields:I});return k.ok?[k,{status:"complete",request:E,response:A}]:[k,{status:"complete",request:E,response:A}]}function GN(t,e,n,r){return new re(ON(t,e,n,r))}async function ON(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:z("interactionsId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/interactions/{interactionsId}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:k=>oe({status:k},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,A={httpMeta:{response:C,request:y}},[I]=await ce(oy(200),ln("4XX",Lu),ln("5XX",Ou))(C,y,{extraFields:A});return I.ok?[I,{status:"complete",request:y,response:C}]:[I,{status:"complete",request:y,response:C}]}function Sy(t,e,n,r,i,o,a){return new re(LN(t,e,n,r,i,o,a))}async function LN(t,e,n,r,i,o,a){var u,c,d;let f={id:e,api_version:n,include_input:r,last_event_id:i,stream:o},p=f,h=null,g={api_version:z("api_version",(u=p.api_version)!==null&&u!==void 0?u:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:z("interactionsId",p.id,{explode:!1,charEncoding:"percent"})},_=ae("/{api_version}/interactions/{interactionsId}")(g),m=ct({include_input:p.include_input,last_event_id:p.last_event_id,stream:p.stream}),v=new Headers(ue({Accept:f?.stream?"text/event-stream":"application/json"})),y=await fe(t._options.security),E=de(y),C={options:t._options,base_url:(d=(c=a?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&d!==void 0?d:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:E,security_source:t._options.security,retry_config:a?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(C,{security:E,method:"GET",baseURL:a?.server_url,path:_,headers:v,query:m,body:h,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!A.ok)return[A,{status:"invalid"}];let I=A.value,k=await t._do(I,{context:C,isErrorStatusCode:q=>oe({status:q},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!k.ok)return[k,{status:"request-error",request:I}];let O=k.value,B={httpMeta:{response:O,request:I}},[D]=await ce(me(200),iy(200,{sentinel:"[DONE]",flattened:!0}),ln("4XX",Fu),ln("5XX",qu))(O,I,{extraFields:B});return D.ok?[D,{status:"complete",request:I,response:O}]:[D,{status:"complete",request:I,response:O}]}var Bu=class extends lt{create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return le(Ay(this,i,r,n))}delete(e,n,r){return le(GN(this,e,n?.api_version,r))}get(e,n,r){return le(Sy(this,e,n?.api_version,n?.include_input,n?.last_event_id,n?.stream,r))}cancel(e,n,r){return le(Cy(this,e,n?.api_version,r))}};function Iy(t,e,n,r){return new re(qN(t,e,n,r))}async function qN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/triggers")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function wy(t,e,n,r){return new re(FN(t,e,n,r))}async function FN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/triggers/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Ry(t,e,n,r){return new re(BN(t,e,n,r))}async function BN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/triggers/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Py(t,e,n,r,i,o){return new re(HN(t,e,n,r,i,o))}async function HN(t,e,n,r,i,o){var a,u,c;let f={trigger_id:e,api_version:n,page_size:r,page_token:i},p=null,h={api_version:z("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:z("triggerId",f.trigger_id,{explode:!1,charEncoding:"percent"})},g=ae("/{api_version}/triggers/{triggerId}/executions")(h),_=ct({page_size:f.page_size,page_token:f.page_token}),m=new Headers(ue({Accept:"application/json"})),v=await fe(t._options.security),y=de(v),E={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(E,{security:y,method:"GET",baseURL:o?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:E,isErrorStatusCode:B=>oe({status:B},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let k=I.value,[O]=await ce(Q("4XX"),Q("5XX"),me("default"))(k,A);return O.ok?[O,{status:"complete",request:A,response:k}]:[O,{status:"complete",request:A,response:k}]}function ky(t,e,n,r,i,o){return new re(VN(t,e,n,r,i,o))}async function VN(t,e,n,r,i,o){var a,u,c;let f={api_version:e,filter:n,page_size:r,page_token:i},p=null,h={api_version:z("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},g=ae("/{api_version}/triggers")(h),_=ct({filter:f?.filter,page_size:f?.page_size,page_token:f?.page_token}),m=new Headers(ue({Accept:"application/json"})),v=await fe(t._options.security),y=de(v),E={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(E,{security:y,method:"GET",baseURL:o?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:E,isErrorStatusCode:B=>oe({status:B},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let k=I.value,[O]=await ce(Q("4XX"),Q("5XX"),me("default"))(k,A);return O.ok?[O,{status:"complete",request:A,response:k}]:[O,{status:"complete",request:A,response:k}]}function xy(t,e,n,r){return new re($N(t,e,n,r))}async function $N(t,e,n,r){var i,o,a;let c={trigger_id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:z("triggerId",c.trigger_id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/triggers/{triggerId}/executions")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Ny(t,e,n,r,i){return new re(XN(t,e,n,r,i))}async function XN(t,e,n,r,i){var o,a,u;let d={id:e,body:n,api_version:r},f=ut("body",d.body,{explode:!0}),p={api_version:z("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",d.id,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/triggers/{id}")(p),g=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),_=await fe(t._options.security),m=de(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"PATCH",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,C=await t._do(E,{context:v,isErrorStatusCode:k=>oe({status:k},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:E}];let A=C.value,[I]=await ce(Q("4XX"),Q("5XX"),me("default"))(A,E);return I.ok?[I,{status:"complete",request:E,response:A}]:[I,{status:"complete",request:E,response:A}]}var Hu=class extends lt{list(e,n){return le(ky(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return le(Iy(this,i,r,n))}delete(e,n,r){return le(wy(this,e,n?.api_version,r))}get(e,n,r){return le(Ry(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i}=n,o=Ie(n,["api_version"]);return le(Ny(this,e,o,i,r))}listExecutions(e,n,r){return le(Py(this,e,n?.api_version,n?.page_size,n?.page_token,r))}run(e,n,r){return le(xy(this,e,n?.api_version,r))}};function Dy(t,e,n,r){return new re(JN(t,e,n,r))}async function JN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/voices")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function by(t,e,n,r){return new re(WN(t,e,n,r))}async function WN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:z("voicesId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/voices/{voicesId}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function My(t,e,n,r){return new re(KN(t,e,n,r))}async function KN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:z("voicesId",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/voices/{voicesId}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Uy(t,e,n,r,i,o,a,u,c,d,f,p,h,g){return new re(YN(t,e,n,r,i,o,a,u,c,d,f,p,h,g))}async function YN(t,e,n,r,i,o,a,u,c,d,f,p,h,g){var _,m,v;let E={api_version:e,accent:n,contexts:r,gender:i,language_code:o,page_size:a,page_token:u,persona:c,pitch:d,region_code:f,search:p,type:h},C=null,A={api_version:z("api_version",(_=E?.api_version)!==null&&_!==void 0?_:t._options.api_version,{explode:!1,charEncoding:"percent"})},I=ae("/{api_version}/voices")(A),k=ct({accent:E?.accent,context:E?.contexts,gender:E?.gender,language_code:E?.language_code,page_size:E?.page_size,page_token:E?.page_token,persona:E?.persona,pitch:E?.pitch,region_code:E?.region_code,search:E?.search,type:E?.type}),O=new Headers(ue({Accept:"application/json"})),B=await fe(t._options.security),D=de(B),q={options:t._options,base_url:(v=(m=g?.server_url)!==null&&m!==void 0?m:t._baseURL)!==null&&v!==void 0?v:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:D,security_source:t._options.security,retry_config:g?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:g?.retry_codes||["408","409","429","5XX"]},H=t._createRequest(q,{security:D,method:"GET",baseURL:g?.server_url,path:I,headers:O,query:k,body:C,userAgent:t._options.user_agent,timeout_ms:g?.timeout_ms||t._options.timeout_ms||-1},g);if(!H.ok)return[H,{status:"invalid"}];let J=H.value,ne=await t._do(J,{context:q,isErrorStatusCode:Z=>oe({status:Z},["4XX","5XX"]),retryConfig:q.retry_config,retryCodes:q.retry_codes});if(!ne.ok)return[ne,{status:"request-error",request:J}];let L=ne.value,[X]=await ce(Q("4XX"),Q("5XX"),me("default"))(L,J);return X.ok?[X,{status:"complete",request:J,response:L}]:[X,{status:"complete",request:J,response:L}]}var Vu=class extends lt{list(e,n){return le(Uy(this,e?.api_version,e?.accent,e?.contexts,e?.gender,e?.language_code,e?.page_size,e?.page_token,e?.persona,e?.pitch,e?.region_code,e?.search,e?.type,n))}create(e,n,r){return le(Dy(this,e,n,r))}delete(e,n,r){return le(by(this,e,n?.api_version,r))}get(e,n,r){return le(My(this,e,n?.api_version,r))}};function Gy(t,e,n,r){return new re(zN(t,e,n,r))}async function zN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=ut("body",c.body,{explode:!0}),f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/webhooks")(f),h=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Oy(t,e,n,r){return new re(QN(t,e,n,r))}async function QN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/webhooks/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function Ly(t,e,n,r){return new re(ZN(t,e,n,r))}async function ZN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:z("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",c.id,{explode:!1,charEncoding:"percent"})},p=ae("/{api_version}/webhooks/{id}")(f),h=new Headers(ue({Accept:"application/json"})),g=await fe(t._options.security),_=de(g),m={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:I=>oe({status:I},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let C=E.value,[A]=await ce(Q("4XX"),Q("5XX"),me("default"))(C,y);return A.ok?[A,{status:"complete",request:y,response:C}]:[A,{status:"complete",request:y,response:C}]}function qy(t,e,n,r,i){return new re(jN(t,e,n,r,i))}async function jN(t,e,n,r,i){var o,a,u;let d={api_version:e,page_size:n,page_token:r},f=null,p={api_version:z("api_version",(o=d?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/webhooks")(p),g=ct({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(ue({Accept:"application/json"})),m=await fe(t._options.security),v=de(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let C=E.value,A=await t._do(C,{context:y,isErrorStatusCode:O=>oe({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[k]=await ce(Q("4XX"),Q("5XX"),me("default"))(I,C);return k.ok?[k,{status:"complete",request:C,response:I}]:[k,{status:"complete",request:C,response:I}]}function Fy(t,e,n,r,i){return new re(eD(t,e,n,r,i))}async function eD(t,e,n,r,i){var o,a,u;let d={id:e,api_version:n,body:r},f=ut("body",d.body,{explode:!0}),p={api_version:z("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",d.id,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/webhooks/{id}:ping")(p),g=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),_=await fe(t._options.security),m=de(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,C=await t._do(E,{context:v,isErrorStatusCode:k=>oe({status:k},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:E}];let A=C.value,[I]=await ce(Q("4XX"),Q("5XX"),me("default"))(A,E);return I.ok?[I,{status:"complete",request:E,response:A}]:[I,{status:"complete",request:E,response:A}]}function By(t,e,n,r,i){return new re(tD(t,e,n,r,i))}async function tD(t,e,n,r,i){var o,a,u;let d={id:e,body:n,api_version:r},f=ut("body",d.body,{explode:!0}),p={api_version:z("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",d.id,{explode:!1,charEncoding:"percent"})},h=ae("/{api_version}/webhooks/{id}:rotateSigningSecret")(p),g=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),_=await fe(t._options.security),m=de(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,C=await t._do(E,{context:v,isErrorStatusCode:k=>oe({status:k},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:E}];let A=C.value,[I]=await ce(Q("4XX"),Q("5XX"),me("default"))(A,E);return I.ok?[I,{status:"complete",request:E,response:A}]:[I,{status:"complete",request:E,response:A}]}function Hy(t,e,n,r,i,o){return new re(nD(t,e,n,r,i,o))}async function nD(t,e,n,r,i,o){var a,u,c;let f={id:e,body:n,api_version:r,update_mask:i},p=ut("body",f.body,{explode:!0}),h={api_version:z("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:z("id",f.id,{explode:!1,charEncoding:"percent"})},g=ae("/{api_version}/webhooks/{id}")(h),_=ct({update_mask:f.update_mask}),m=new Headers(ue({"Content-Type":"application/json",Accept:"application/json"})),v=await fe(t._options.security),y=de(v),E={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(E,{security:y,method:"PATCH",baseURL:o?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:E,isErrorStatusCode:B=>oe({status:B},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let k=I.value,[O]=await ce(Q("4XX"),Q("5XX"),me("default"))(k,A);return O.ok?[O,{status:"complete",request:A,response:k}]:[O,{status:"complete",request:A,response:k}]}var $u=class extends lt{list(e,n){return le(qy(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return le(Gy(this,i,r,n))}delete(e,n,r){return le(Oy(this,e,n?.api_version,r))}get(e,n,r){return le(Ly(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i,update_mask:o}=n,a=Ie(n,["api_version","update_mask"]);return le(Hy(this,e,a,i,o,r))}ping(e,n,r,i){return le(Fy(this,e,n,r,i))}rotateSigningSecret(e,n,r,i){return le(By(this,e,n,r,i))}};var rD=class extends lt{get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new Du(this._options)}get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new Pu(this._options)}get credentials(){var e;return(e=this._credentials)!==null&&e!==void 0?e:this._credentials=new ku(this._options)}get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new Bu(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new Hu(this._options)}get voices(){var e;return(e=this._voices)!==null&&e!==void 0?e:this._voices=new Vu(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new $u(this._options)}};var iD=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function oD(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function sD(t){let e=aD(t.getApiVersion()),n=t.getProject(),r=t.getLocation();return t.isVertexAI()&&e&&n&&r?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(r)}`:e}function Be(t,e={}){var n,r,i,o,a,u,c,d,f,p;let{timeout:h}=e,g=Ie(e,["timeout"]),_=g.http_client||(n=t.getFetch)===null||n===void 0?void 0:n.call(t),m=(r=g.http_client)!==null&&r!==void 0?r:_?new Mo({fetcher:_}):void 0,v=(o=(i=g.timeout_ms)!==null&&i!==void 0?i:h)!==null&&o!==void 0?o:(a=t.getTimeout)===null||a===void 0?void 0:a.call(t);return new rD(Object.assign(Object.assign({},g),{http_client:m,api_version:(u=g.api_version)!==null&&u!==void 0?u:sD(t),security:(c=g.security)!==null&&c!==void 0?c:new mu({defaultHeaders:Object.assign(Object.assign({},(d=t.getDefaultHeaders)===null||d===void 0?void 0:d.call(t)),(f=t.getHeaders)===null||f===void 0?void 0:f.call(t)),getAuthHeaders:E=>t.getAuthHeaders(E)}),server_url:(p=g.server_url)!==null&&p!==void 0?p:oD(t),timeout_ms:v}))}var Xu=class{constructor(e,n){this.parentClient=e}async create(e,n){var r;let{api_version:i,automatic_continuation:o}=e,a=Ie(e,["api_version","automatic_continuation"]),u=ix(a,o),c=new qr((r=n?.timeout_ms)!==null&&r!==void 0?r:n?.timeout,{enabled:u.enableContinuation}),d=()=>{if(!c.bounded)return n;let _=n??{},{timeout:m}=_,v=Ie(_,["timeout"]);return Object.assign(Object.assign({},v),{timeout_ms:c.hopTimeoutMs()})},f=this.getClient(i);if(u.stream){let _=async(v,y)=>{let E=await Sl(()=>f.interactions.create(Object.assign(Object.assign({},wg(u,v,y)),{stream:!0,api_version:i}),ie(d(),!0)));return Hg(E)},m=await _();return u.enableContinuation?Vg(cx(m,_,{initialContinuationToken:u.callerToken,isConnectionError:v=>v instanceof on&&!(v instanceof ir),isFatalError:v=>v instanceof ir,wrapIterationError:lD,deadline:c,store:u.body.store!==!1})):u.callerToken?m:Vg(sx(m))}let p=async(_,m)=>he(Ay(f,wg(u,_,m),i,ie(d()))),h=await p();if(u.enableContinuation)return await hx(h,p,{initialContinuationToken:u.callerToken,normalizeInteraction:Vy,finalizeInteraction:$y,deadline:c,store:u.body.store!==!1});let g=Il(h);return u.callerToken||ox(g),g}async get(e,n={},r){let{api_version:i,stream:o=!1,last_event_id:a,include_input:u}=n??{};if(o===!0){let d=await Sl(()=>this.getClient(i).interactions.get(e,{stream:o,last_event_id:a,include_input:u,api_version:i},ie(r,!0)));return Hg(d)}let c=await he(Sy(this.getClient(i),e,i,u,a,o,ie(r)));return Il(c)}async delete(e,n={},r){return Sl(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},ie(r)))}async cancel(e,n={},r){return Il(await he(Cy(this.getClient(n?.api_version),e,n?.api_version,ie(r))))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}},Ju=class{constructor(e){this.parentClient=e}async create(e={},n){let r=e??{},{api_version:i}=r,o=Ie(r,["api_version"]);return he(ay(this.getClient(i),o,i,ie(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o,parent:a}=e??{};return he(cy(this.getClient(r),r,i,o,a,ie(n)))}async get(e,n={},r){return he(uy(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async delete(e,n={},r){return he(ly(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}},Wu=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return he(Gy(this.getClient(),i,r,ie(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o}=e??{};return he(qy(this.getClient(),r,i,o,ie(n)))}async get(e,n={},r){return he(Ly(this.getClient(),e,n?.api_version,ie(r)))}async update(e,n={},r){let i=n??{},{api_version:o,update_mask:a}=i,u=Ie(i,["api_version","update_mask"]);return he(Hy(this.getClient(),e,u,o,a,ie(r)))}async delete(e,n={},r){return he(Oy(this.getClient(),e,n?.api_version,ie(r)))}async rotateSigningSecret(e,n={},r){let i=n??{},{api_version:o}=i,a=Ie(i,["api_version"]);return he(By(this.getClient(),e,a,o,ie(r)))}async ping(e,n=void 0,r){let{api_version:i,body:o}=n??{};return he(Fy(this.getClient(),e,i,o,ie(r)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=Be(this.parentClient)),this.sdk}},Ku=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return he(Iy(this.getClient(r),i,r,ie(n)))}async list(e={},n){let{api_version:r,filter:i,page_size:o,page_token:a}=e??{};return he(ky(this.getClient(r),r,i,o,a,ie(n)))}async get(e,n={},r){return he(Ry(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async update(e,n,r){let{api_version:i}=n,o=Ie(n,["api_version"]);return he(Ny(this.getClient(i),e,o,i,ie(r)))}async delete(e,n={},r){return he(wy(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async run(e,n={},r){return he(xy(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async listExecutions(e,n={},r){let{api_version:i,page_size:o,page_token:a}=n??{};return he(Py(this.getClient(i),e,i,o,a,ie(r)))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}};function aD(t){return t.replace(/^\/+|\/+$/g,"")}function ie(t,e=!1){var n,r,i,o;if(!t&&!e)return;let a=t??{},{timeout:u,maxRetries:c,defaultBaseURL:d,query:f,body:p,fetchOptions:h}=a,g=Ie(a,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),_=Object.assign({},g);Oo(f)?_.extra_query=f:Bg("query",f),Oo(p)?_.extra_body=p:Bg("body",p);let m=(n=g.fetch_options)!==null&&n!==void 0?n:h;m&&(_.fetch_options=m);let v=(r=g.server_url)!==null&&r!==void 0?r:d;v&&(_.server_url=v);let y=(i=g.timeout_ms)!==null&&i!==void 0?i:u;if(y!==void 0&&(_.timeout_ms=y),c!==void 0&&(_.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let E=new Headers((o=_.headers)!==null&&o!==void 0?o:m?.headers);E.set("Accept","text/event-stream"),_.headers=E}return _}function Bg(t,e){e!=null&&console.warn(`GoogleGenAI.interactions: request option ${t} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function he(t){let[e,n]=await t.$inspect();if(!e.ok)throw tn(e.error);return uD(e.value,n)}async function Sl(t){try{return await t()}catch(e){throw tn(e)}}function Hg(t){let e=t;return new Proxy(t,{get(n,r){if(r!==Symbol.asyncIterator){let i=Reflect.get(n,r,n);return typeof i=="function"?i.bind(n):i}return function(){let o=e[Symbol.asyncIterator]();return{async next(...a){try{return await o.next(...a)}catch(u){throw tn(u)}},async return(a){if(!o.return)return{done:!0,value:a};try{return await o.return(a)}catch(u){throw tn(u)}},async throw(a){if(!o.throw)throw tn(a);try{return await o.throw(a)}catch(u){throw tn(u)}},[Symbol.asyncIterator](){return this}}}}})}function lD(t){let e=tn(t);if(e instanceof qe||e instanceof rr)return e;if(e instanceof Error&&e.name==="AbortError")return new ir({message:e.message});let n=e instanceof Error?e.message:String(e);return new on({message:n,cause:e})}function Vg(t){let e=t[Symbol.asyncIterator](),n=new ReadableStream({async pull(r){let i=await e.next();i.done?r.close():r.enqueue(i.value)},async cancel(){var r;await((r=e.return)===null||r===void 0?void 0:r.call(e))}},{highWaterMark:0});return Object.setPrototypeOf(n,bo.prototype),n}function uD(t,e){return!Oo(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:cD(e.response,t)})}function cD(t,e){let n={};for(let[r,i]of t.headers.entries())n[r]=i;return{headers:n,responseInternal:t,json:async()=>e}}function Il(t){let e=Vy(t);return e?$y(e):t}function Vy(t){if(Oo(t)){if(Array.isArray(t.steps))return t;if(dD(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,r=Ie(t,["outputs"]);return Object.assign(Object.assign({},r),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function dD(t){let e=t.model;return typeof e=="string"&&iD.has(e)}function Oo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $y(t){var e,n;let r=fD(t),i=(e=r.steps)!==null&&e!==void 0?e:[],o=[],a=!1;e:for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type==="thought")continue;if(h.type!=="model_output"){if(a)break;continue}if(!h.content)continue;let g=h.content;for(let _=g.length-1;_>=0;_--){let m=g[_];if(m.type==="text")a=!0,o.push((n=m.text)!==null&&n!==void 0?n:"");else if(a)break e}}let u,c,d;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type==="model_output"&&h.content)for(let g=h.content.length-1;g>=0;g--){let _=h.content[g];_.type==="image"&&!u&&(u=_),_.type==="audio"&&!c&&(c=_),_.type==="video"&&!d&&(d=_)}}let f=o.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},r),f&&{output_text:f}),u?{output_image:u}:{}),c?{output_audio:c}:{}),d?{output_video:d}:{})}function fD(t){return Object.assign(Object.assign({},t),{created:$g(t.created),updated:$g(t.updated)})}function $g(t){return t instanceof Date?t.toISOString():t}function pD(t){let e=t.slice(t.lastIndexOf(".")+1).toLowerCase();return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[e]}var Yu=class{constructor(e,n){this.resolveClient=e,this.parentClient=n}async list(e,n){return he(Ey(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,ie(n)))}async download(e,n){var r,i;let o=e.environment;if(!o)throw new Error("environment is required.");let a=o.startsWith("environments/")?o:`environments/${o}`,u=e.path.replace(/^\/+/,""),c=`${a}/files/${u}`,d=this.parentClient;if(!d||typeof d.request!="function")throw new Error("apiClient is required to download files.");let f=await d.request({path:c,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:(r=e.api_version)!==null&&r!==void 0?r:(i=n?.httpOptions)===null||i===void 0?void 0:i.apiVersion})});if(f&&f.responseInternal&&typeof f.responseInternal.arrayBuffer=="function"){let p=await f.responseInternal.arrayBuffer();return new Uint8Array(p)}throw new Error("Unexpected response type from download")}async upload(e,n){var r,i,o,a,u,c,d,f;let p=e.environment;if(!p)throw new Error("environment is required.");p.startsWith("environments/")||`${p}`;let h=e.path.replace(/^\/+/,""),g=this.parentClient;if(!g||typeof g.request!="function")throw new Error("apiClient is required to upload files.");let _,m=0,v=e.mime_type;if(typeof e.file=="string"){let q;try{let H=globalThis.require;H&&(q=H("fs").readFileSync(e.file))}catch{}if(!q&&typeof globalThis.process<"u")try{let H=(i=(r=globalThis.process.mainModule)===null||r===void 0?void 0:r.require)!==null&&i!==void 0?i:globalThis.require;H&&(q=H("fs").readFileSync(e.file))}catch{}if(q)_=new Uint8Array(q.buffer,q.byteOffset,q.byteLength),m=_.byteLength;else throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);v||(v=pD(e.file))}else if(typeof Blob<"u"&&e.file instanceof Blob)_=e.file,m=e.file.size,!v&&e.file.type&&(v=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)_=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,m=_.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(e.file)){let q=e.file;_=new Uint8Array(q.buffer,q.byteOffset,q.byteLength),m=_.byteLength}else throw new Error("Unsupported file type for upload.");v||(v="application/octet-stream");let y=p.startsWith("environments/")?p.replace(/^environments\//,""):p,[E,C]=await Ty(this.resolveClient(e.api_version),y,h,"start",m,v,"resumable",e.api_version,e.extract,e.overwrite,ie(n)).$inspect();if(!E.ok)throw tn(E.error);let A=C.status==="complete"?(u=(a=(o=C.response)===null||o===void 0?void 0:o.headers)===null||a===void 0?void 0:a.get("x-goog-upload-url"))!==null&&u!==void 0?u:(d=(c=C.response)===null||c===void 0?void 0:c.headers)===null||d===void 0?void 0:d.get("X-Goog-Upload-URL"):void 0;if(!A)throw new Error("Failed to get upload URL from upload handshake response.");let I=8*1024*1024,k=0,O,B=_ instanceof Blob?_:new Blob([_]);for(;k<m||m===0&&k===0;){let q=Math.min(k+I,m),H=B.slice(k,q),J=q>=m,ne=J?"upload, finalize":"upload";if(O=await g.request({path:"",body:H,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:"",baseUrl:A,headers:Object.assign(Object.assign({},((f=n?.httpOptions)===null||f===void 0?void 0:f.headers)||{}),{"X-Goog-Upload-Command":ne,"X-Goog-Upload-Offset":`${k}`})})}),k=q,J)break}let D;if(O&&typeof O.json=="function"?D=await O.json():O&&O.responseInternal&&typeof O.responseInternal.json=="function"&&(D=await O.responseInternal.json()),D&&typeof D=="object"){if(Array.isArray(D.files))return D;if(D.name||D.path)return{files:[D]};if(D.file&&typeof D.file=="object")return{files:[D.file]}}return D}},zu=class{constructor(e){this.parentClient=e,this.files=new Yu(n=>this.getClient(n),this.parentClient)}async create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return he(gy(this.getClient(r),i,r,ie(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o}=e??{};return he(vy(this.getClient(r),r,i,o,ie(n)))}async get(e,n={},r){return he(yy(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async delete(e,n={},r){return he(_y(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}},Qu=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return he(dy(this.getClient(r),i,r,ie(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o}=e??{};return he(hy(this.getClient(r),r,i,o,ie(n)))}async get(e,n={},r){return he(py(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async update(e,n,r){let{api_version:i,update_mask:o}=n,a=Ie(n,["api_version","update_mask"]);return he(my(this.getClient(i),e,a,i,o,ie(r)))}async delete(e,n={},r){return he(fy(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}},Zu=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ie(e,["api_version"]);return he(Dy(this.getClient(r),i,r,ie(n)))}async list(e={},n){let{api_version:r,accent:i,contexts:o,gender:a,language_code:u,page_size:c,page_token:d,persona:f,pitch:p,region_code:h,search:g,type:_}=e??{};return he(Uy(this.getClient(r),r,i,o,a,u,c,d,f,p,h,g,_,ie(n)))}async get(e,n={},r){return he(My(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}async delete(e,n={},r){return he(by(this.getClient(n?.api_version),e,n?.api_version,ie(r)))}getClient(e){var n;return e?Be(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Be(this.parentClient)),this.sdk)}};var Xg="x-goog-api-key",br="https://www.googleapis.com/auth/cloud-platform",ju=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=hD(e.googleAuthOptions);this.googleAuth=new Yg.GoogleAuth(n)}async addAuthHeaders(e,n){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,n)}addKeyHeader(e){if(e.get(Xg)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(Xg,this.apiKey)}}async addGoogleAuthHeaders(e,n){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let r=await this.googleAuth.getRequestHeaders(n);for(let[i,o]of r)e.get(i)===null&&e.append(i,o)}};function hD(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==br||Array.isArray(e.scopes)&&e.scopes.indexOf(br)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${br}`)}else return e.scopes=[br],e;return e}else return e={scopes:[br]},e}var ec=class{async download(e,n){if(e.downloadPath){let r=await mD(e,n);if(r instanceof Ht){let i=tS(e.downloadPath);rS.fromWeb(r.responseInternal.body).pipe(i),await iS(i)}else try{await nS(e.downloadPath,r,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};async function mD(t,e){var n,r,i;let o=pc(t.file);if(o!==void 0)return await e.request({path:`files/${o}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal});if(s_(t.file)){let a=(i=t.file.video)===null||i===void 0?void 0:i.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(a_(t.file)){let a=t.file.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var Lo=class{create(e,n,r){return new tc(e,n,r)}},tc=class{constructor(e,n,r){this.url=e,this.headers=n,this.callbacks=r}connect(){this.ws=new Cl.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function gD(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function _D(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function yD(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function vD(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function nc(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>UD(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function ED(t,e,n){let r={};if(s(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&l(e,["displayName"],i),s(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["epochCount"]);e!==void 0&&o!=null&&l(e,["tuningTask","hyperparameters","epochCount"],o);let a=s(t,["learningRateMultiplier"]);if(a!=null&&l(r,["tuningTask","hyperparameters","learningRateMultiplier"],a),s(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["batchSize"]);e!==void 0&&u!=null&&l(e,["tuningTask","hyperparameters","batchSize"],u);let c=s(t,["learningRate"]);if(e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","learningRate"],c),s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function TD(t,e,n){let r={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let L=s(t,["validationDataset"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec"],uo(L))}else if(i==="PREFERENCE_TUNING"){let L=s(t,["validationDataset"]);e!==void 0&&L!=null&&l(e,["preferenceOptimizationSpec"],uo(L))}else if(i==="DISTILLATION"){let L=s(t,["validationDataset"]);e!==void 0&&L!=null&&l(e,["distillationSpec"],uo(L))}else if(i==="REINFORCEMENT_TUNING"){let L=s(t,["validationDataset"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec"],uo(L))}let o=s(t,["tunedModelDisplayName"]);e!==void 0&&o!=null&&l(e,["tunedModelDisplayName"],o);let a=s(t,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let u=s(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let L=s(t,["epochCount"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],L)}else if(u==="PREFERENCE_TUNING"){let L=s(t,["epochCount"]);e!==void 0&&L!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],L)}else if(u==="DISTILLATION"){let L=s(t,["epochCount"]);e!==void 0&&L!=null&&l(e,["distillationSpec","hyperParameters","epochCount"],L)}else if(u==="REINFORCEMENT_TUNING"){let L=s(t,["epochCount"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec","hyperParameters","epochCount"],L)}let c=s(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let L=s(t,["learningRateMultiplier"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],L)}else if(c==="PREFERENCE_TUNING"){let L=s(t,["learningRateMultiplier"]);e!==void 0&&L!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],L)}else if(c==="DISTILLATION"){let L=s(t,["learningRateMultiplier"]);e!==void 0&&L!=null&&l(e,["distillationSpec","hyperParameters","learningRateMultiplier"],L)}else if(c==="REINFORCEMENT_TUNING"){let L=s(t,["learningRateMultiplier"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],L)}let d=s(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let L=s(t,["exportLastCheckpointOnly"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],L)}else if(d==="PREFERENCE_TUNING"){let L=s(t,["exportLastCheckpointOnly"]);e!==void 0&&L!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],L)}else if(d==="DISTILLATION"){let L=s(t,["exportLastCheckpointOnly"]);e!==void 0&&L!=null&&l(e,["distillationSpec","exportLastCheckpointOnly"],L)}let f=s(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let L=s(t,["adapterSize"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],L)}else if(f==="PREFERENCE_TUNING"){let L=s(t,["adapterSize"]);e!==void 0&&L!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],L)}else if(f==="DISTILLATION"){let L=s(t,["adapterSize"]);e!==void 0&&L!=null&&l(e,["distillationSpec","hyperParameters","adapterSize"],L)}else if(f==="REINFORCEMENT_TUNING"){let L=s(t,["adapterSize"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],L)}let p=s(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let L=s(t,["tuningMode"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","tuningMode"],L)}else if(p==="DISTILLATION"){let L=s(t,["tuningMode"]);e!==void 0&&L!=null&&l(e,["distillationSpec","tuningMode"],L)}let h=s(t,["customBaseModel"]);e!==void 0&&h!=null&&l(e,["customBaseModel"],h);let g=s(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){let L=s(t,["batchSize"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","hyperParameters","batchSize"],L)}else if(g==="DISTILLATION"){let L=s(t,["batchSize"]);e!==void 0&&L!=null&&l(e,["distillationSpec","hyperParameters","batchSize"],L)}else if(g==="REINFORCEMENT_TUNING"){let L=s(t,["batchSize"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec","hyperParameters","batchSize"],L)}let _=s(n,["config","method"]);if(_===void 0&&(_="SUPERVISED_FINE_TUNING"),_==="SUPERVISED_FINE_TUNING"){let L=s(t,["learningRate"]);e!==void 0&&L!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRate"],L)}else if(_==="DISTILLATION"){let L=s(t,["learningRate"]);e!==void 0&&L!=null&&l(e,["distillationSpec","hyperParameters","learningRate"],L)}let m=s(t,["labels"]);e!==void 0&&m!=null&&l(e,["labels"],m);let v=s(t,["beta"]);e!==void 0&&v!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],v);let y=s(t,["baseTeacherModel"]);e!==void 0&&y!=null&&l(e,["distillationSpec","baseTeacherModel"],y);let E=s(t,["tunedTeacherModelSource"]);e!==void 0&&E!=null&&l(e,["distillationSpec","tunedTeacherModelSource"],E);let C=s(t,["sftLossWeightMultiplier"]);e!==void 0&&C!=null&&l(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],C);let A=s(t,["outputUri"]);e!==void 0&&A!=null&&l(e,["outputUri"],A);let I=s(t,["rewardConfig"]);e!==void 0&&I!=null&&l(e,["reinforcementTuningSpec","singleRewardConfig"],I);let k=s(t,["compositeRewardConfig"]);e!==void 0&&k!=null&&l(e,["reinforcementTuningSpec","compositeRewardConfig"],k);let O=s(t,["samplesPerPrompt"]);e!==void 0&&O!=null&&l(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],O);let B=s(t,["evaluateInterval"]);e!==void 0&&B!=null&&l(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],B);let D=s(t,["checkpointInterval"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],D);let q=s(t,["maxOutputTokens"]);e!==void 0&&q!=null&&l(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],q);let H=s(t,["thinkingLevel"]);e!==void 0&&H!=null&&l(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],H);let J=s(t,["validationDatasetUri"]);e!==void 0&&J!=null&&l(e,["reinforcementTuningSpec","validationDatasetUri"],J);let ne=s(t,["encryptionSpec"]);return e!==void 0&&ne!=null&&l(e,["encryptionSpec"],ne),r}function CD(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let o=s(t,["trainingDataset"]);o!=null&&qD(o);let a=s(t,["config"]);return a!=null&&ED(a,n),n}function AD(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let o=s(t,["trainingDataset"]);o!=null&&FD(o,n,e);let a=s(t,["config"]);return a!=null&&TD(a,n,e),n}function Xy(t,e){let n={},r=s(t,["epochCount"]);r!=null&&l(n,["epochCount"],r);let i=s(t,["learningRateMultiplier"]);i!=null&&l(n,["learningRateMultiplier"],i);let o=s(t,["adapterSize"]);o!=null&&l(n,["adapterSize"],o);let a=s(t,["batchSize"]);a!=null&&l(n,["batchSize"],a);let u=s(t,["learningRate"]);u!=null&&l(n,["learningRate"],u);let c=s(t,["generationConfig"]);return c!=null&&l(n,["generationConfig"],PD(c)),n}function SD(t,e){let n={},r=s(t,["promptDatasetUri"]);r!=null&&l(n,["promptDatasetUri"],r);let i=s(t,["validationDatasetUri"]);i!=null&&l(n,["validationDatasetUri"],i);let o=s(t,["baseTeacherModel"]);o!=null&&l(n,["baseTeacherModel"],o);let a=s(t,["tunedTeacherModelSource"]);a!=null&&l(n,["tunedTeacherModelSource"],a);let u=s(t,["hyperparameters"]);return u!=null&&l(n,["hyperparameters"],Xy(u)),n}function ID(t,e){let n={},r=s(t,["baseTeacherModel"]);r!=null&&l(n,["baseTeacherModel"],r);let i=s(t,["hyperParameters"]);i!=null&&l(n,["hyperParameters"],Xy(i));let o=s(t,["pipelineRootDirectory"]);o!=null&&l(n,["pipelineRootDirectory"],o);let a=s(t,["promptDatasetUri"]);a!=null&&l(n,["promptDatasetUri"],a);let u=s(t,["studentModel"]);u!=null&&l(n,["studentModel"],u);let c=s(t,["trainingDatasetUri"]);c!=null&&l(n,["trainingDatasetUri"],c);let d=s(t,["tunedTeacherModelSource"]);d!=null&&l(n,["tunedTeacherModelSource"],d);let f=s(t,["tuningMode"]);f!=null&&l(n,["tuningMode"],f);let p=s(t,["validationDatasetUri"]);return p!=null&&l(n,["validationDatasetUri"],p),n}function wD(t,e){let n={},r=s(t,["fileData"]);r!=null&&l(n,["fileData"],r);let i=s(t,["inlineData"]);if(i!=null&&l(n,["inlineData"],i),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function RD(t,e){let n={},r=s(t,["id"]);r!=null&&l(n,["id"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["parts"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>wD(d))),l(n,["parts"],c)}let a=s(t,["response"]);a!=null&&l(n,["response"],a);let u=s(t,["scheduling"]);if(u!=null&&l(n,["scheduling"],u),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function PD(t,e){let n={},r=s(t,["modelConfig"]);r!=null&&l(n,["modelSelectionConfig"],r);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let o=s(t,["audioTranscriptionConfig"]);o!=null&&l(n,["audioTranscriptionConfig"],o);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let g=s(t,["presencePenalty"]);g!=null&&l(n,["presencePenalty"],g);let _=s(t,["responseFormat"]);if(_!=null){let J=_;Array.isArray(J)&&(J=J.map(ne=>ne)),l(n,["responseFormat"],J)}let m=s(t,["responseLogprobs"]);m!=null&&l(n,["responseLogprobs"],m);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let E=s(t,["responseSchema"]);E!=null&&l(n,["responseSchema"],E);let C=s(t,["routingConfig"]);C!=null&&l(n,["routingConfig"],C);let A=s(t,["seed"]);A!=null&&l(n,["seed"],A);let I=s(t,["speechConfig"]);I!=null&&l(n,["speechConfig"],I);let k=s(t,["stopSequences"]);k!=null&&l(n,["stopSequences"],k);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let B=s(t,["thinkingConfig"]);B!=null&&l(n,["thinkingConfig"],B);let D=s(t,["topK"]);D!=null&&l(n,["topK"],D);let q=s(t,["topP"]);q!=null&&l(n,["topP"],q);let H=s(t,["translationConfig"]);return H!=null&&l(n,["translationConfig"],H),n}function kD(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function xD(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function ND(t,e,n){let r={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);e!==void 0&&o!=null&&l(e,["_query","pageToken"],o);let a=s(t,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),r}function DD(t,e){let n={},r=s(t,["config"]);return r!=null&&ND(r,n),n}function bD(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["tuningJobs"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>rc(u))),l(n,["tuningJobs"],a)}return n}function MD(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function UD(t,e){let n={},r=s(t,["mediaResolution"]);if(r!=null&&l(n,["mediaResolution"],r),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(n,["codeExecutionResult"],o);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],RD(d));let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let m=s(t,["mediaProcessing"]);m!=null&&l(n,["mediaProcessing"],m);let v=s(t,["speechMetadata"]);return v!=null&&l(n,["speechMetadata"],v),n}function GD(t,e){let n={},r=s(t,["references"]);r!=null&&l(n,["references"],r);let i=s(t,["contents"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>nc(c))),l(n,["contents"],u)}let o=s(t,["systemInstruction"]);o!=null&&l(n,["systemInstruction"],nc(o));let a=s(t,["tools"]);if(a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>OD(c))),l(n,["tools"],u)}return n}function OD(t,e){let n={},r=s(t,["retrieval"]);r!=null&&l(n,["retrieval"],r);let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],i);let o=s(t,["mcpServers"]);if(o!=null){let m=o;Array.isArray(m)&&(m=m.map(v=>MD(v))),l(n,["mcpServers"],m)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],u);let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),l(n,["functionDeclarations"],m)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let g=s(t,["parallelAiSearch"]);g!=null&&l(n,["parallelAiSearch"],g);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function LD(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["model"],r);let i=s(t,["name"]);return i!=null&&l(n,["endpoint"],i),n}function qD(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["examples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(n,["examples","examples"],i)}return n}function FD(t,e,n){let r={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(i==="PREFERENCE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(i==="DISTILLATION"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(i==="REINFORCEMENT_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}let o=s(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(o==="PREFERENCE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(o==="DISTILLATION"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(o==="REINFORCEMENT_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}if(s(t,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function BD(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["state"]);o!=null&&l(n,["state"],o_(o));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["tuningTask","startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["tuningTask","completeTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["description"]);f!=null&&l(n,["description"],f);let p=s(t,["baseModel"]);p!=null&&l(n,["baseModel"],p);let h=s(t,["_self"]);return h!=null&&l(n,["tunedModel"],LD(h)),n}function rc(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["state"]);o!=null&&l(n,["state"],o_(o));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["error"]);f!=null&&l(n,["error"],f);let p=s(t,["description"]);p!=null&&l(n,["description"],p);let h=s(t,["baseModel"]);h!=null&&l(n,["baseModel"],h);let g=s(t,["tunedModel"]);g!=null&&l(n,["tunedModel"],g);let _=s(t,["preTunedModel"]);_!=null&&l(n,["preTunedModel"],_);let m=s(t,["supervisedTuningSpec"]);m!=null&&l(n,["supervisedTuningSpec"],m);let v=s(t,["preferenceOptimizationSpec"]);v!=null&&l(n,["preferenceOptimizationSpec"],v);let y=s(t,["distillationSamplingSpec"]);y!=null&&l(n,["distillationSamplingSpec"],SD(y));let E=s(t,["distillationSpec"]);E!=null&&l(n,["distillationSpec"],ID(E));let C=s(t,["reinforcementTuningSpec"]);C!=null&&l(n,["reinforcementTuningSpec"],C);let A=s(t,["tuningDataStats"]);A!=null&&l(n,["tuningDataStats"],A);let I=s(t,["encryptionSpec"]);I!=null&&l(n,["encryptionSpec"],I);let k=s(t,["partnerModelTuningSpec"]);k!=null&&l(n,["partnerModelTuningSpec"],k);let O=s(t,["customBaseModel"]);O!=null&&l(n,["customBaseModel"],O);let B=s(t,["evaluateDatasetRuns"]);if(B!=null){let Ue=B;Array.isArray(Ue)&&(Ue=Ue.map(Ge=>Ge)),l(n,["evaluateDatasetRuns"],Ue)}let D=s(t,["experiment"]);D!=null&&l(n,["experiment"],D);let q=s(t,["fullFineTuningSpec"]);q!=null&&l(n,["fullFineTuningSpec"],q);let H=s(t,["labels"]);H!=null&&l(n,["labels"],H);let J=s(t,["outputUri"]);J!=null&&l(n,["outputUri"],J);let ne=s(t,["pipelineJob"]);ne!=null&&l(n,["pipelineJob"],ne);let L=s(t,["serviceAccount"]);L!=null&&l(n,["serviceAccount"],L);let X=s(t,["tunedModelDisplayName"]);X!=null&&l(n,["tunedModelDisplayName"],X);let Z=s(t,["tuningJobMetadata"]);Z!=null&&l(n,["tuningJobMetadata"],Z);let ge=s(t,["tuningJobState"]);ge!=null&&l(n,["tuningJobState"],ge);let _e=s(t,["veoLoraTuningSpec"]);_e!=null&&l(n,["veoLoraTuningSpec"],_e);let pe=s(t,["veoTuningSpec"]);pe!=null&&l(n,["veoTuningSpec"],pe);let He=s(t,["gcsMetricsUri"]);return He!=null&&l(n,["gcsMetricsUri"],He),n}function HD(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["metadata"]);o!=null&&l(n,["metadata"],o);let a=s(t,["done"]);a!=null&&l(n,["done"],a);let u=s(t,["error"]);return u!=null&&l(n,["error"],u),n}function uo(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["validationDatasetUri"],r);let i=s(t,["vertexDatasetResource"]);return i!=null&&l(n,["validationDatasetUri"],i),n}function VD(t,e){let n={},r=s(t,["parent"]);r!=null&&l(n,["_url","parent"],r);let i=s(t,["sampleResponse"]);i!=null&&l(n,["sampleResponse"],nc(i));let o=s(t,["example"]);o!=null&&l(n,["example"],GD(o));let a=s(t,["singleRewardConfig"]);a!=null&&l(n,["singleRewardConfig"],a);let u=s(t,["compositeRewardConfig"]);return u!=null&&l(n,["compositeRewardConfig"],u),n}function $D(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["overallReward"]);i!=null&&l(n,["overallReward"],i);let o=s(t,["error"]);o!=null&&l(n,["error"],o);let a=s(t,["rewardInfoDetails"]);return a!=null&&l(n,["rewardInfoDetails"],a),n}var ic=class extends vt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new $t(Vt.PAGED_ITEM_TUNING_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var r;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){let i={tunedModelName:n.baseModel};!((r=n.config)===null||r===void 0)&&r.preTunedModelCheckpointId&&(i.checkpointId=n.config.preTunedModelCheckpointId);let o=Object.assign(Object.assign({},n),{preTunedModel:i});return o.baseModel=void 0,await this.tuneInternal(o)}else{let i=Object.assign({},n);return await this.tuneInternal(i)}else{let i=Object.assign({},n),o=await this.tuneMldevInternal(i),a="";return o.metadata!==void 0&&o.metadata.tunedModel!==void 0?a=o.metadata.tunedModel:o.name!==void 0&&o.name.includes("/operations/")&&(a=o.name.split("/operations/")[0]),{name:a,state:Rl.JOB_STATE_QUEUED}}}}async getInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=xD(e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>rc(f))}else{let d=kD(e);return u=W("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>BD(f))}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=DD(e);return o=W("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=bD(c),f=new Ol;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=_D(e);return u=W("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=vD(f),h=new To;return Object.assign(h,p),h})}else{let d=gD(e);return u=W("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=yD(f),h=new To;return Object.assign(h,p),h})}}async tuneInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=AD(e,e);return o=W("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>rc(c))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=CD(e);return o=W("tunedModels",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>HD(c))}}async validateReward(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=VD(e);return o=W("{parent}/tuningJobs:validateReinforcementTuningReward",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=$D(c),f=new Ll;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},Jy=1024*1024*8,Wy=3,Ky=1e3,Yy=2,nn="x-goog-upload-status";async function XD(t,e,n,r){var i;let o=await zy(t,e,n,r),a=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[nn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function JD(t,e,n,r){var i;let o=await zy(t,e,n,r),a=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[nn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let u=lc(a),c=new Io;return Object.assign(c,u),c}async function zy(t,e,n,r){var i,o,a;let u=e,c=r?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(c){let g=new URL(c),_=new URL(e);_.protocol=g.protocol,_.host=g.host,_.port=g.port,u=_.toString()}let d=0,f=0,p=new Ht(new Response),h="upload";for(d=t.size;f<d;){let g=Math.min(Jy,d-f),_=t.slice(f,f+g);f+g>=d&&(h+=", finalize");let m=0,v=Ky;for(;m<Wy;){let y=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f)});if(p=await n.request({path:"",body:_,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:u,headers:y})}),!((o=p?.headers)===null||o===void 0)&&o[nn])break;m++,await Qy(v),v=v*Yy}if(f+=g,((a=p?.headers)===null||a===void 0?void 0:a[nn])!=="active")break;if(d<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function WD(t){return{size:t.size,type:t.type}}function Qy(t){return new Promise(e=>setTimeout(e,t))}var oc=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let r=await qo.stat(e);return n.size=r.size,n.type=this.inferMimeType(e),n}else return await WD(e)}async upload(e,n,r,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,r,i):XD(e,n,r,i)}async uploadToFileSearchStore(e,n,r,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,r,i):JD(e,n,r,i)}inferMimeType(e){let n=e.slice(e.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[n.toLowerCase()]}async uploadFileFromPath(e,n,r,i){var o;let a=await this.uploadFileFromPathInternal(e,n,r,i),u=await a?.json();if(((o=a?.headers)===null||o===void 0?void 0:o[nn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return u.file}async uploadFileToFileSearchStoreFromPath(e,n,r,i){var o;let a=await this.uploadFileFromPathInternal(e,n,r,i),u=await a?.json();if(((o=a?.headers)===null||o===void 0?void 0:o[nn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=lc(u),d=new Io;return Object.assign(d,c),d}async uploadFileFromPathInternal(e,n,r,i){var o,a,u;let c=n,d=i?.baseUrl||((o=r.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(d){let v=new URL(d),y=new URL(n);y.protocol=v.protocol,y.host=v.host,y.port=v.port,c=y.toString()}let f=0,p=0,h=new Ht(new Response),g="upload",_,m=zg.basename(e);try{if(_=await qo.open(e,"r"),!_)throw new Error("Failed to open file");for(f=(await _.stat()).size;p<f;){let v=Math.min(Jy,f-p);p+v>=f&&(g+=", finalize");let y=new Uint8Array(v),{bytesRead:E}=await _.read(y,0,v,p);if(E!==v)throw new Error(`Failed to read ${v} bytes from file at offset ${p}. bytes actually read: ${E}`);let C=new Blob([y]),A=0,I=Ky;for(;A<Wy;){let k=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":g,"X-Goog-Upload-Offset":String(p),"X-Goog-Upload-File-Name":m});if(h=await r.request({path:"",body:C,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:c,headers:k})}),!((a=h?.headers)===null||a===void 0)&&a[nn])break;A++,await Qy(I),I=I*Yy}if(p+=E,((u=h?.headers)===null||u===void 0?void 0:u[nn])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{_&&await _.close()}}};var sc=class extends hw{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let r=await e.auth.getRequestHeaders(),i=e.config||{},o=i.httpOptions||{},a=Object.assign({},o.headers||{});if(r)if(typeof r[Symbol.iterator]=="function")for(let[u,c]of r)a[u]=c;else for(let[u,c]of Object.entries(r))a[u]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},o),{headers:a})})})}};var KD="gl-node/";function YD(t){var e;if(t&&(t.enterprise!==void 0||t.vertexai!==void 0)){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}let n=Ft("GOOGLE_GENAI_USE_ENTERPRISE"),r=Ft("GOOGLE_GENAI_USE_VERTEXAI"),i=Wg(n),o=Wg(r);return n!==void 0&&r!==void 0&&i!==o&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?i:r!==void 0?o:!1}var Jg=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=Be(this.apiClient,{timeout_ms:e?.timeout})),e?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new Xu(this.apiClient,new Lo),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new Wu(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new Ju(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new Ku(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new zu(this.apiClient),this._environments)}get credentials(){return this._credentials!==void 0?this._credentials:(console.warn("GoogleGenAI.credentials: Credentials usage is experimental and may change in future versions."),this._credentials=new Qu(this.apiClient),this._credentials)}get voices(){return this._voices!==void 0?this._voices:(this._voices=new Zu(this.apiClient),this._voices)}constructor(e={}){var n,r,i,o,a,u;if(this.vertexai=YD(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let c=zD(),d=Ft("GOOGLE_CLOUD_PROJECT"),f=Ft("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:c,this.project=(r=e.project)!==null&&r!==void 0?r:d,this.location=(i=e.location)!==null&&i!==void 0?i:f,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((o=e.googleAuthOptions)===null||o===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),!e.project&&!e.location&&(d||f)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&c?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!e.project&&!e.location&&!e.apiKey&&(d||f)&&c&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let p=sS(e.httpOptions,this.vertexai,Ft("GOOGLE_VERTEX_BASE_URL"),Ft("GOOGLE_GEMINI_BASE_URL"));p&&(e.httpOptions?e.httpOptions.baseUrl=p:e.httpOptions={baseUrl:p});let h=Ft("GOOGLE_GENAI_API_VERSION")||void 0,g=h==="beta"?this.vertexai?"v1beta1":"v1beta":h;this.apiVersion=(a=e.apiVersion)!==null&&a!==void 0?a:((u=e.httpOptions)===null||u===void 0?void 0:u.apiVersion)!==void 0?void 0:g,this.httpOptions=e.httpOptions;let _=new ju({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new iu({auth:_,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:KD+process.version,uploader:new oc,downloader:new ec}),this.models=new nr(this.apiClient),this.live=new au(this.apiClient,_,new Lo),this.batches=new Ql(this.apiClient),this.chats=new jl(this.models,this.apiClient),this.caches=new Zl(this.apiClient),this.files=new sc(this.apiClient),this.operations=new uu(this.apiClient),this.authTokens=new cu(this.apiClient),this.tunings=new ic(this.apiClient),this.fileSearchStores=new fu(this.apiClient)}};function Ft(t){var e,n,r;return(r=(n=(e=process==null?void 0:process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&r!==void 0?r:void 0}function Wg(t){return t===void 0?!1:t.toLowerCase()==="true"}function zD(){let t=Ft("GOOGLE_API_KEY"),e=Ft("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}export{Am as ActivityHandling,Hh as AdapterSize,Wh as AggregationMetric,Gr as ApiError,gh as ApiSpec,qh as AspectRatio,Mm as AudioResponseFormat,kh as AudioTranscriptionConfigMode,hh as AuthType,Ql as Batches,Eh as Behavior,bh as BlockedReason,Zl as Caches,To as CancelTuningJobResponse,eu as Chat,jl as Chats,Ul as ComputeTokensResponse,jm as ContentReferenceImage,Ro as ContinuationInterruptedError,zm as ControlReferenceImage,sm as ControlReferenceType,Eo as CountTokensResponse,$l as CreateFileResponse,Co as DeleteCachedContentResponse,Xl as DeleteFileResponse,vo as DeleteModelResponse,Lh as Delivery,Zh as DocumentState,Th as DynamicRetrievalConfigMode,Nl as EditImageResponse,lm as EditMode,_o as EmbedContentResponse,mo as EmbeddingApiType,Cm as EndSensitivity,yh as Environment,Hm as EvaluateDatasetResponse,nm as FeatureSelectionPreference,gm as FileSource,mm as FileState,hw as Files,po as FinishReason,Ph as FunctionCallingConfigMode,Nm as FunctionResponse,km as FunctionResponseBlob,Pm as FunctionResponseFileData,xm as FunctionResponsePart,ph as FunctionResponseScheduling,yt as GenerateContentResponse,kl as GenerateContentResponsePromptFeedback,go as GenerateContentResponseUsageMetadata,xl as GenerateImagesResponse,Gl as GenerateVideosOperation,qm as GenerateVideosResponse,Jg as GoogleGenAI,wh as HarmBlockMethod,Rh as HarmBlockThreshold,Ih as HarmCategory,xh as HarmProbability,Nh as HarmSeverity,mh as HttpElementLocation,Ht as HttpResponse,im as ImagePromptLanguage,pm as ImageResizeMode,Um as ImageResponseFormat,Fh as ImageSize,Hl as ImportFileOperation,Vm as ImportFileResponse,Jm as InlinedEmbedContentResponse,$m as InlinedResponse,ym as InteractionStatus,Rl as JobState,fh as Language,So as ListBatchJobsResponse,Ao as ListCachedContentsResponse,ql as ListDocumentsResponse,Fl as ListFileSearchStoresResponse,Vl as ListFilesResponse,yo as ListModelsResponse,Ol as ListTuningJobsResponse,au as Live,eg as LiveClientToolResponse,Zn as LiveMusicPlaybackControl,Kl as LiveMusicServerMessage,tg as LiveSendToolResponseParameters,Wl as LiveServerMessage,Ym as MaskReferenceImage,om as MaskReferenceMode,$h as MatchOperation,Uh as MediaModality,ch as MediaProcessing,Oh as MediaResolution,ho as Modality,Gh as ModelStage,nr as Models,wm as MusicGenerationMode,uu as Operations,dh as Outcome,Vt as PagedItem,$t as Pager,Kh as PairwiseChoice,em as PartMediaResolutionLevel,Ah as PersonGeneration,vh as PhishBlockThreshold,Sh as ProminentPeople,Km as RawReferenceImage,bl as RecontextImageResponse,Jl as RegisterFilesResponse,Bm as ReinforcementTuningAutoraterScorerParsedResponseConversionScorer,Fm as ReinforcementTuningParseResponseConfig,Xh as ReinforcementTuningThinkingLevel,Wm as ReplayResponse,Pl as ResourceScope,Lm as ResponseFormat,Vh as ResponseParseType,rm as SafetyFilterLevel,_h as SafetyPolicy,Im as Scale,Ml as SegmentImageResponse,um as SegmentMode,jh as ServiceTier,lu as Session,Xm as SingleEmbedContentResponse,Tm as StartSensitivity,Qm as StyleReferenceImage,Zm as SubjectReferenceImage,am as SubjectReferenceType,Gm as TextResponseFormat,Ch as ThinkingLevel,cu as Tokens,Rm as ToolResponse,tm as ToolType,Mh as TrafficType,Jh as TuningJobState,hm as TuningMethod,Bh as TuningMode,zh as TuningSpeed,Qh as TuningTask,_m as TurnCompleteReason,Sm as TurnCoverage,en as Type,Io as UploadToFileSearchStoreOperation,ng as UploadToFileSearchStoreResponse,Bl as UploadToFileSearchStoreResumableResponse,Dl as UpscaleImageResponse,Dh as UrlRetrievalStatus,vm as VadSignalType,Ll as ValidateRewardResponse,fm as VideoCompressionQuality,dm as VideoGenerationMaskMode,cm as VideoGenerationReferenceType,Yh as VideoOrientation,Om as VideoResponseFormat,Em as VoiceActivityType,BM as createFunctionResponsePartFromBase64,HM as createFunctionResponsePartFromUri,zM as createModelContent,JM as createPartFromBase64,WM as createPartFromCodeExecutionResult,KM as createPartFromExecutableCode,$M as createPartFromFunctionCall,XM as createPartFromFunctionResponse,Dm as createPartFromText,VM as createPartFromUri,YM as createUserContent,ZM as mcpToTool,FM as setDefaultBaseUrls};
|
|
43
|
+
/*! Bundled license information:
|
|
44
|
+
|
|
45
|
+
safe-buffer/index.js:
|
|
46
|
+
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
|
47
|
+
|
|
48
|
+
@google/genai/dist/node/index.mjs:
|
|
49
|
+
@google/genai/dist/node/index.mjs:
|
|
50
|
+
(**
|
|
51
|
+
* @license
|
|
52
|
+
* Copyright 2025 Google LLC
|
|
53
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
54
|
+
*)
|
|
55
|
+
|
|
56
|
+
@google/genai/dist/node/index.mjs:
|
|
57
|
+
(**
|
|
58
|
+
* @license
|
|
59
|
+
* Copyright 2025 Google LLC
|
|
60
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
61
|
+
*)
|
|
62
|
+
(**
|
|
63
|
+
* @license
|
|
64
|
+
* Copyright 2026 Google LLC
|
|
65
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
66
|
+
*)
|
|
67
|
+
(**
|
|
68
|
+
* @license
|
|
69
|
+
* Copyright 2026 Google LLC
|
|
70
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
71
|
+
*
|
|
72
|
+
* g3-prettier-ignore-file
|
|
73
|
+
*)
|
|
74
|
+
*/
|