9remote 3.0.24 → 3.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/cli.cjs +50 -48
  2. package/dist/server.cjs +24 -24
  3. package/dist/ui/assets/index-BOOiLX1B.js +8 -0
  4. package/dist/ui/index.html +1 -1
  5. package/dist/web/404.html +1 -1
  6. package/dist/web/__next.__PAGE__.txt +2 -2
  7. package/dist/web/__next._full.txt +2 -2
  8. package/dist/web/__next._head.txt +1 -1
  9. package/dist/web/__next._index.txt +1 -1
  10. package/dist/web/__next._tree.txt +1 -1
  11. package/dist/web/_next/static/chunks/app/login/{page-2a2743b7f8cb2435.js → page-5a8b059b59f831f9.js} +1 -1
  12. package/dist/web/_next/static/chunks/app/{page-590ad581a1270380.js → page-bd6ebc0a436fea70.js} +2 -2
  13. package/dist/web/_next/static/chunks/app/workspace/{layout-d6c53117c6436790.js → layout-4b7802a47d5a41d9.js} +1 -1
  14. package/dist/web/_not-found/__next._full.txt +1 -1
  15. package/dist/web/_not-found/__next._head.txt +1 -1
  16. package/dist/web/_not-found/__next._index.txt +1 -1
  17. package/dist/web/_not-found/__next._not-found.__PAGE__.txt +1 -1
  18. package/dist/web/_not-found/__next._not-found.txt +1 -1
  19. package/dist/web/_not-found/__next._tree.txt +1 -1
  20. package/dist/web/_not-found.html +1 -1
  21. package/dist/web/_not-found.txt +1 -1
  22. package/dist/web/admin/__next._full.txt +1 -1
  23. package/dist/web/admin/__next._head.txt +1 -1
  24. package/dist/web/admin/__next._index.txt +1 -1
  25. package/dist/web/admin/__next._tree.txt +1 -1
  26. package/dist/web/admin/__next.admin.__PAGE__.txt +1 -1
  27. package/dist/web/admin/__next.admin.txt +1 -1
  28. package/dist/web/admin/admins/__next._full.txt +1 -1
  29. package/dist/web/admin/admins/__next._head.txt +1 -1
  30. package/dist/web/admin/admins/__next._index.txt +1 -1
  31. package/dist/web/admin/admins/__next._tree.txt +1 -1
  32. package/dist/web/admin/admins/__next.admin.admins.__PAGE__.txt +1 -1
  33. package/dist/web/admin/admins/__next.admin.admins.txt +1 -1
  34. package/dist/web/admin/admins/__next.admin.txt +1 -1
  35. package/dist/web/admin/admins.html +1 -1
  36. package/dist/web/admin/admins.txt +1 -1
  37. package/dist/web/admin/login/__next._full.txt +1 -1
  38. package/dist/web/admin/login/__next._head.txt +1 -1
  39. package/dist/web/admin/login/__next._index.txt +1 -1
  40. package/dist/web/admin/login/__next._tree.txt +1 -1
  41. package/dist/web/admin/login/__next.admin.login.__PAGE__.txt +1 -1
  42. package/dist/web/admin/login/__next.admin.login.txt +1 -1
  43. package/dist/web/admin/login/__next.admin.txt +1 -1
  44. package/dist/web/admin/login.html +1 -1
  45. package/dist/web/admin/login.txt +1 -1
  46. package/dist/web/admin/modes/__next._full.txt +1 -1
  47. package/dist/web/admin/modes/__next._head.txt +1 -1
  48. package/dist/web/admin/modes/__next._index.txt +1 -1
  49. package/dist/web/admin/modes/__next._tree.txt +1 -1
  50. package/dist/web/admin/modes/__next.admin.modes.__PAGE__.txt +1 -1
  51. package/dist/web/admin/modes/__next.admin.modes.txt +1 -1
  52. package/dist/web/admin/modes/__next.admin.txt +1 -1
  53. package/dist/web/admin/modes.html +1 -1
  54. package/dist/web/admin/modes.txt +1 -1
  55. package/dist/web/admin/ota/__next._full.txt +1 -1
  56. package/dist/web/admin/ota/__next._head.txt +1 -1
  57. package/dist/web/admin/ota/__next._index.txt +1 -1
  58. package/dist/web/admin/ota/__next._tree.txt +1 -1
  59. package/dist/web/admin/ota/__next.admin.ota.__PAGE__.txt +1 -1
  60. package/dist/web/admin/ota/__next.admin.ota.txt +1 -1
  61. package/dist/web/admin/ota/__next.admin.txt +1 -1
  62. package/dist/web/admin/ota.html +1 -1
  63. package/dist/web/admin/ota.txt +1 -1
  64. package/dist/web/admin/turn/__next._full.txt +1 -1
  65. package/dist/web/admin/turn/__next._head.txt +1 -1
  66. package/dist/web/admin/turn/__next._index.txt +1 -1
  67. package/dist/web/admin/turn/__next._tree.txt +1 -1
  68. package/dist/web/admin/turn/__next.admin.turn.__PAGE__.txt +1 -1
  69. package/dist/web/admin/turn/__next.admin.turn.txt +1 -1
  70. package/dist/web/admin/turn/__next.admin.txt +1 -1
  71. package/dist/web/admin/turn.html +1 -1
  72. package/dist/web/admin/turn.txt +1 -1
  73. package/dist/web/admin.html +1 -1
  74. package/dist/web/admin.txt +1 -1
  75. package/dist/web/dev/question/__next._full.txt +1 -1
  76. package/dist/web/dev/question/__next._head.txt +1 -1
  77. package/dist/web/dev/question/__next._index.txt +1 -1
  78. package/dist/web/dev/question/__next._tree.txt +1 -1
  79. package/dist/web/dev/question/__next.dev.question.__PAGE__.txt +1 -1
  80. package/dist/web/dev/question/__next.dev.question.txt +1 -1
  81. package/dist/web/dev/question/__next.dev.txt +1 -1
  82. package/dist/web/dev/question.html +1 -1
  83. package/dist/web/dev/question.txt +1 -1
  84. package/dist/web/index.html +1 -1
  85. package/dist/web/index.txt +2 -2
  86. package/dist/web/login/__next._full.txt +2 -2
  87. package/dist/web/login/__next._head.txt +1 -1
  88. package/dist/web/login/__next._index.txt +1 -1
  89. package/dist/web/login/__next._tree.txt +1 -1
  90. package/dist/web/login/__next.login.__PAGE__.txt +2 -2
  91. package/dist/web/login/__next.login.txt +1 -1
  92. package/dist/web/login.html +1 -1
  93. package/dist/web/login.txt +2 -2
  94. package/dist/web/workspace/__next._full.txt +2 -2
  95. package/dist/web/workspace/__next._head.txt +1 -1
  96. package/dist/web/workspace/__next._index.txt +1 -1
  97. package/dist/web/workspace/__next._tree.txt +1 -1
  98. package/dist/web/workspace/__next.workspace.__PAGE__.txt +1 -1
  99. package/dist/web/workspace/__next.workspace.txt +2 -2
  100. package/dist/web/workspace/browse/__next._full.txt +2 -2
  101. package/dist/web/workspace/browse/__next._head.txt +1 -1
  102. package/dist/web/workspace/browse/__next._index.txt +1 -1
  103. package/dist/web/workspace/browse/__next._tree.txt +1 -1
  104. package/dist/web/workspace/browse/__next.workspace.browse.__PAGE__.txt +1 -1
  105. package/dist/web/workspace/browse/__next.workspace.browse.txt +1 -1
  106. package/dist/web/workspace/browse/__next.workspace.txt +2 -2
  107. package/dist/web/workspace/browse.html +1 -1
  108. package/dist/web/workspace/browse.txt +2 -2
  109. package/dist/web/workspace/editor/__next._full.txt +2 -2
  110. package/dist/web/workspace/editor/__next._head.txt +1 -1
  111. package/dist/web/workspace/editor/__next._index.txt +1 -1
  112. package/dist/web/workspace/editor/__next._tree.txt +1 -1
  113. package/dist/web/workspace/editor/__next.workspace.editor.__PAGE__.txt +1 -1
  114. package/dist/web/workspace/editor/__next.workspace.editor.txt +1 -1
  115. package/dist/web/workspace/editor/__next.workspace.txt +2 -2
  116. package/dist/web/workspace/editor.html +1 -1
  117. package/dist/web/workspace/editor.txt +2 -2
  118. package/dist/web/workspace/files/__next._full.txt +2 -2
  119. package/dist/web/workspace/files/__next._head.txt +1 -1
  120. package/dist/web/workspace/files/__next._index.txt +1 -1
  121. package/dist/web/workspace/files/__next._tree.txt +1 -1
  122. package/dist/web/workspace/files/__next.workspace.files.__PAGE__.txt +1 -1
  123. package/dist/web/workspace/files/__next.workspace.files.txt +1 -1
  124. package/dist/web/workspace/files/__next.workspace.txt +2 -2
  125. package/dist/web/workspace/files.html +1 -1
  126. package/dist/web/workspace/files.txt +2 -2
  127. package/dist/web/workspace/git/__next._full.txt +2 -2
  128. package/dist/web/workspace/git/__next._head.txt +1 -1
  129. package/dist/web/workspace/git/__next._index.txt +1 -1
  130. package/dist/web/workspace/git/__next._tree.txt +1 -1
  131. package/dist/web/workspace/git/__next.workspace.git.__PAGE__.txt +1 -1
  132. package/dist/web/workspace/git/__next.workspace.git.txt +1 -1
  133. package/dist/web/workspace/git/__next.workspace.txt +2 -2
  134. package/dist/web/workspace/git.html +1 -1
  135. package/dist/web/workspace/git.txt +2 -2
  136. package/dist/web/workspace/mobile/__next._full.txt +2 -2
  137. package/dist/web/workspace/mobile/__next._head.txt +1 -1
  138. package/dist/web/workspace/mobile/__next._index.txt +1 -1
  139. package/dist/web/workspace/mobile/__next._tree.txt +1 -1
  140. package/dist/web/workspace/mobile/__next.workspace.mobile.__PAGE__.txt +1 -1
  141. package/dist/web/workspace/mobile/__next.workspace.mobile.txt +1 -1
  142. package/dist/web/workspace/mobile/__next.workspace.txt +2 -2
  143. package/dist/web/workspace/mobile.html +1 -1
  144. package/dist/web/workspace/mobile.txt +2 -2
  145. package/dist/web/workspace/remote/__next._full.txt +2 -2
  146. package/dist/web/workspace/remote/__next._head.txt +1 -1
  147. package/dist/web/workspace/remote/__next._index.txt +1 -1
  148. package/dist/web/workspace/remote/__next._tree.txt +1 -1
  149. package/dist/web/workspace/remote/__next.workspace.remote.__PAGE__.txt +1 -1
  150. package/dist/web/workspace/remote/__next.workspace.remote.txt +1 -1
  151. package/dist/web/workspace/remote/__next.workspace.txt +2 -2
  152. package/dist/web/workspace/remote.html +1 -1
  153. package/dist/web/workspace/remote.txt +2 -2
  154. package/dist/web/workspace/terminal/default/__next._full.txt +2 -2
  155. package/dist/web/workspace/terminal/default/__next._head.txt +1 -1
  156. package/dist/web/workspace/terminal/default/__next._index.txt +1 -1
  157. package/dist/web/workspace/terminal/default/__next._tree.txt +1 -1
  158. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.__PAGE__.txt +1 -1
  159. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.txt +1 -1
  160. package/dist/web/workspace/terminal/default/__next.workspace.terminal.txt +1 -1
  161. package/dist/web/workspace/terminal/default/__next.workspace.txt +2 -2
  162. package/dist/web/workspace/terminal/default.html +1 -1
  163. package/dist/web/workspace/terminal/default.txt +2 -2
  164. package/dist/web/workspace/workspaces/__next._full.txt +2 -2
  165. package/dist/web/workspace/workspaces/__next._head.txt +1 -1
  166. package/dist/web/workspace/workspaces/__next._index.txt +1 -1
  167. package/dist/web/workspace/workspaces/__next._tree.txt +1 -1
  168. package/dist/web/workspace/workspaces/__next.workspace.txt +2 -2
  169. package/dist/web/workspace/workspaces/__next.workspace.workspaces.__PAGE__.txt +1 -1
  170. package/dist/web/workspace/workspaces/__next.workspace.workspaces.txt +1 -1
  171. package/dist/web/workspace/workspaces.html +1 -1
  172. package/dist/web/workspace/workspaces.txt +2 -2
  173. package/dist/web/workspace.html +1 -1
  174. package/dist/web/workspace.txt +2 -2
  175. package/package.json +1 -1
  176. package/dist/ui/assets/index-DcykK_na.js +0 -8
  177. /package/dist/web/_next/static/{xSpq32VEKUqU6vBkX2q0J → doBLJdxjaGN7ToTue-RM0}/_buildManifest.js +0 -0
  178. /package/dist/web/_next/static/{xSpq32VEKUqU6vBkX2q0J → doBLJdxjaGN7ToTue-RM0}/_ssgManifest.js +0 -0
package/dist/server.cjs CHANGED
@@ -236,7 +236,7 @@ Error uploading file: ${a.message}\r
236
236
  `)){let i=r.trim().match(/^(\d+)\s+(.*)$/);i&&n.set(Number(i[1]),i[2])}return n}async function y4e(t){if(Dq||!t.length)return new Map;let e=await VE(`lsof -a -d cwd -p ${t.join(",")} -F n`).catch(()=>"");return f4e(e)}function _4e(t){if(!t)return null;try{let e=fce.default.readFileSync(Nq.default.join(t,"package.json"),"utf8"),n=JSON.parse(e)?.name;return typeof n=="string"&&n?n:null}catch{return null}}function lce(t,e,n){return new Promise(r=>{let i=t.request({host:"localhost",port:e,method:"HEAD",path:"/",timeout:i4e,...n},s=>{s.resume(),r({active:!0,protocol:n?.rejectUnauthorized===!1?"https":"http",status:s.statusCode})});i.on("error",s=>r({active:!1,error:s.message})),i.on("timeout",()=>{i.destroy(),r({active:!1,error:"timeout"})}),i.end()})}function E4e(t){return v4e.test(String(t||""))}async function w4e(t){let e=await lce(uce.default,t);return e.active||!E4e(e.error)?e:lce(dce.default,t,{rejectUnauthorized:!1})}async function TR({io:t=S4e,now:e=Date.now}={}){if(bR.sites&&e()-bR.at<r4e)return bR.sites;let n=[];try{let r=await t.listeners(),i=await t.cmdlines([...new Set(r.map(l=>l.pid).filter(Boolean))]),s=[],o=[];for(let l of r){let u=i.get(l.pid)||l.command,d=p4e(u,l.port);d===Gy.WEB?s.push({...l,protocol:"http",status:null}):d===Gy.UNKNOWN&&o.push(l)}let a=await Promise.all(o.slice(0,o4e).map(async l=>({row:l,result:await t.probe(l.port)})));for(let{row:l,result:u}of a)u?.active&&s.push({...l,protocol:u.protocol||"http",status:u.status??null});let c=await t.cwds([...new Set(s.map(l=>l.pid).filter(Boolean))]);n=s.map(l=>{let u=c.get(l.pid)||null;return{port:l.port,protocol:l.protocol,url:`${l.protocol}://localhost:${l.port}`,name:h4e({pkgName:t.readPkgName(u),cwd:u,port:l.port}),status:l.status}}).sort((l,u)=>l.port-u.port)}catch(r){return console.error("Failed to scan local sites:",r.message),[]}return bR={at:e(),sites:n},n}var uce,dce,Nq,fce,pce,hce,n4e,Gy,r4e,i4e,s4e,o4e,a4e,c4e,l4e,bR,Dq,v4e,S4e,Lq=ae(()=>{uce=ce(require("http"),1),dce=ce(require("https"),1),Nq=ce(require("path"),1),fce=ce(require("fs"),1),pce=require("child_process"),hce=require("util"),n4e=(0,hce.promisify)(pce.exec),Gy={WEB:"web",SERVICE:"service",UNKNOWN:"unknown"},r4e=8e3,i4e=800,s4e=3e3,o4e=24,a4e=/\b(vite|next-server|next\s+(dev|start)|nuxt|astro|remix|gatsby|webpack(-dev-server)?|parcel|react-scripts|ng\s+serve|storybook|docusaurus|live-server|http-server|serve\b|python[\d.]*\s+-m\s+http\.server|gunicorn|uvicorn|hypercorn|flask|manage\.py\s+runserver|rails|puma|unicorn|thin|php\s+-S|artisan\s+serve|nginx|httpd|apache2?|caddy|jekyll|hugo|catalina|tomcat|spring)\b/i,c4e=/\b(postgres|postmaster|mysqld|mariadbd?|mongod|redis-server|memcached|elasticsearch|cassandra|clickhouse|etcd|zookeeper|kafka|rabbitmq|beam\.smp|sshd|rsync|smbd|nfsd|cupsd|rapportd|controlcenter|dnsmasq|named|ntpd|chronyd|dockerd|containerd|colima|qemu[\w-]*|netsimd|adb|emulator)\b/i,l4e=new Set([22,23,25,53,110,111,135,137,138,139,143,389,445,465,548,587,631,993,995,1433,1521,2049,2181,3306,3389,5432,5433,5672,5900,6379,9092,11211,27017,27018,27019,62078]),bR={at:0,sites:null};Dq=process.platform==="win32";v4e=/EPROTO|SSL|wrong version number|packet length/i;S4e={listeners:m4e,cmdlines:g4e,cwds:y4e,probe:w4e,readPkgName:_4e}});var gce=B((pAt,Uq)=>{"use strict";var x4e=Object.prototype.hasOwnProperty,Bi="~";function zE(){}Object.create&&(zE.prototype=Object.create(null),new zE().__proto__||(Bi=!1));function b4e(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function mce(t,e,n,r,i){if(typeof n!="function")throw new TypeError("The listener must be a function");var s=new b4e(n,r||t,i),o=Bi?Bi+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function AR(t,e){--t._eventsCount===0?t._events=new zE:delete t._events[e]}function wi(){this._events=new zE,this._eventsCount=0}wi.prototype.eventNames=function(){var e=[],n,r;if(this._eventsCount===0)return e;for(r in n=this._events)x4e.call(n,r)&&e.push(Bi?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(n)):e};wi.prototype.listeners=function(e){var n=Bi?Bi+e:e,r=this._events[n];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i<s;i++)o[i]=r[i].fn;return o};wi.prototype.listenerCount=function(e){var n=Bi?Bi+e:e,r=this._events[n];return r?r.fn?1:r.length:0};wi.prototype.emit=function(e,n,r,i,s,o){var a=Bi?Bi+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,n),!0;case 3:return c.fn.call(c.context,n,r),!0;case 4:return c.fn.call(c.context,n,r,i),!0;case 5:return c.fn.call(c.context,n,r,i,s),!0;case 6:return c.fn.call(c.context,n,r,i,s,o),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,m;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,n);break;case 3:c[d].fn.call(c[d].context,n,r);break;case 4:c[d].fn.call(c[d].context,n,r,i);break;default:if(!u)for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c[d].fn.apply(c[d].context,u)}}return!0};wi.prototype.on=function(e,n,r){return mce(this,e,n,r,!1)};wi.prototype.once=function(e,n,r){return mce(this,e,n,r,!0)};wi.prototype.removeListener=function(e,n,r,i){var s=Bi?Bi+e:e;if(!this._events[s])return this;if(!n)return AR(this,s),this;var o=this._events[s];if(o.fn)o.fn===n&&(!i||o.once)&&(!r||o.context===r)&&AR(this,s);else{for(var a=0,c=[],l=o.length;a<l;a++)(o[a].fn!==n||i&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:AR(this,s)}return this};wi.prototype.removeAllListeners=function(e){var n;return e?(n=Bi?Bi+e:e,this._events[n]&&AR(this,n)):(this._events=new zE,this._eventsCount=0),this};wi.prototype.off=wi.prototype.removeListener;wi.prototype.addListener=wi.prototype.on;wi.prefixed=Bi;wi.EventEmitter=wi;typeof Uq<"u"&&(Uq.exports=wi)});var _ce=B((hAt,yce)=>{"use strict";yce.exports=function(e,n){if(n=n.split(":")[0],e=+e,!e)return!1;switch(n){case"http":case"ws":return e!==80;case"https":case"wss":return e!==443;case"ftp":return e!==21;case"gopher":return e!==70;case"file":return!1}return e!==0}});var CR=B(Ece=>{var yu=Ece,T4e=require("url"),vce=require("util")._extend,A4e=_ce(),C4e=/(^|,)\s*upgrade\s*($|,)/i,Fq=/^https|wss/;yu.isSSL=Fq;yu.setupOutgoing=function(t,e,n,r){t.port=e[r||"target"].port||(Fq.test(e[r||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(a){t[a]=e[r||"target"][a]}),t.method=e.method||n.method,t.headers=vce({},n.headers),e.headers&&vce(t.headers,e.headers),e.auth&&(t.auth=e.auth),e.ca&&(t.ca=e.ca),Fq.test(e[r||"target"].protocol)&&(t.rejectUnauthorized=typeof e.secure>"u"?!0:e.secure),t.agent=e.agent||!1,t.localAddress=e.localAddress,t.agent||(t.headers=t.headers||{},(typeof t.headers.connection!="string"||!C4e.test(t.headers.connection))&&(t.headers.connection="close"));var i=e[r||"target"],s=i&&e.prependPath!==!1&&i.path||"",o=e.toProxy?n.url:T4e.parse(n.url).path||"";return o=e.ignorePath?"":o,t.path=yu.urlJoin(s,o),e.changeOrigin&&(t.headers.host=A4e(t.port,e[r||"target"].protocol)&&!R4e(t.host)?t.host+":"+t.port:t.host),t};yu.setupSocket=function(t){return t.setTimeout(0),t.setNoDelay(!0),t.setKeepAlive(!0,0),t};yu.getPort=function(t){var e=t.headers.host?t.headers.host.match(/:(\d+)/):"";return e?e[1]:yu.hasEncryptedConnection(t)?"443":"80"};yu.hasEncryptedConnection=function(t){return!!(t.connection.encrypted||t.connection.pair)};yu.urlJoin=function(){var t=Array.prototype.slice.call(arguments),e=t.length-1,n=t[e],r=n.split("?"),i;return t[e]=r.shift(),i=[t.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://")],i.push.apply(i,r),i.join("?")};yu.rewriteCookieProperty=function t(e,n,r){return Array.isArray(e)?e.map(function(i){return t(i,n,r)}):e.replace(new RegExp("(;\\s*"+r+"=)([^;]+)","i"),function(i,s,o){var a;if(o in n)a=n[o];else if("*"in n)a=n["*"];else return i;return a?s+a:""})};function R4e(t){return!!~t.indexOf(":")}});var bce=B((gAt,xce)=>{var wce=require("url"),Sce=CR(),I4e=/^201|30(1|2|7|8)$/;xce.exports={removeChunked:function(e,n,r){e.httpVersion==="1.0"&&delete r.headers["transfer-encoding"]},setConnection:function(e,n,r){e.httpVersion==="1.0"?r.headers.connection=e.headers.connection||"close":e.httpVersion!=="2.0"&&!r.headers.connection&&(r.headers.connection=e.headers.connection||"keep-alive")},setRedirectHostRewrite:function(e,n,r,i){if((i.hostRewrite||i.autoRewrite||i.protocolRewrite)&&r.headers.location&&I4e.test(r.statusCode)){var s=wce.parse(i.target),o=wce.parse(r.headers.location);if(s.host!=o.host)return;i.hostRewrite?o.host=i.hostRewrite:i.autoRewrite&&(o.host=e.headers.host),i.protocolRewrite&&(o.protocol=i.protocolRewrite),r.headers.location=o.format()}},writeHeaders:function(e,n,r,i){var s=i.cookieDomainRewrite,o=i.cookiePathRewrite,a=i.preserveHeaderKeyCase,c,l=function(f,m){m!=null&&(s&&f.toLowerCase()==="set-cookie"&&(m=Sce.rewriteCookieProperty(m,s,"domain")),o&&f.toLowerCase()==="set-cookie"&&(m=Sce.rewriteCookieProperty(m,o,"path")),n.setHeader(String(f).trim(),m))};if(typeof s=="string"&&(s={"*":s}),typeof o=="string"&&(o={"*":o}),a&&r.rawHeaders!=null){c={};for(var u=0;u<r.rawHeaders.length;u+=2){var d=r.rawHeaders[u];c[d.toLowerCase()]=d}}Object.keys(r.headers).forEach(function(f){var m=r.headers[f];a&&c&&(f=c[f]||f),l(f,m)})},writeStatusCode:function(e,n,r){r.statusMessage?(n.statusCode=r.statusCode,n.statusMessage=r.statusMessage):n.statusCode=r.statusCode}}});var Ace=B((yAt,Tce)=>{var KE;Tce.exports=function(){if(!KE){try{KE=ar()("follow-redirects")}catch{}typeof KE!="function"&&(KE=function(){})}KE.apply(null,arguments)}});var Pce=B((_At,Xq)=>{var XE=require("url"),YE=XE.URL,k4e=require("http"),P4e=require("https"),Hq=require("stream").Writable,jq=require("assert"),Cce=Ace();(function(){var e=typeof process<"u",n=typeof window<"u"&&typeof document<"u",r=bh(Error.captureStackTrace);!e&&(n||!r)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var Wq=!1;try{jq(new YE(""))}catch(t){Wq=t.code==="ERR_INVALID_URL"}var O4e=["Authorization","Proxy-Authorization","Cookie"],M4e=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],Vq=["abort","aborted","connect","error","socket","timeout"],zq=Object.create(null);Vq.forEach(function(t){zq[t]=function(e,n,r){this._redirectable.emit(t,e,n,r)}});var qq=JE("ERR_INVALID_URL","Invalid URL",TypeError),$q=JE("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),N4e=JE("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",$q),D4e=JE("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),L4e=JE("ERR_STREAM_WRITE_AFTER_END","write after end"),U4e=Hq.prototype.destroy||Ice;function ds(t,e){Hq.call(this),this._sanitizeOptions(t),this._options=t,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],e&&this.on("response",e);var n=this;this._onNativeResponse=function(r){try{n._processResponse(r)}catch(i){n.emit("error",i instanceof $q?i:new $q({cause:i}))}},this._headerFilter=new RegExp("^(?:"+O4e.concat(t.sensitiveHeaders).map(H4e).join("|")+")$","i"),this._performRequest()}ds.prototype=Object.create(Hq.prototype);ds.prototype.abort=function(){Yq(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};ds.prototype.destroy=function(t){return Yq(this._currentRequest,t),U4e.call(this,t),this};ds.prototype.write=function(t,e,n){if(this._ending)throw new L4e;if(!xh(t)&&!$4e(t))throw new TypeError("data should be a string, Buffer or Uint8Array");if(bh(e)&&(n=e,e=null),t.length===0){n&&n();return}this._requestBodyLength+t.length<=this._options.maxBodyLength?(this._requestBodyLength+=t.length,this._requestBodyBuffers.push({data:t,encoding:e}),this._currentRequest.write(t,e,n)):(this.emit("error",new D4e),this.abort())};ds.prototype.end=function(t,e,n){if(bh(t)?(n=t,t=e=null):bh(e)&&(n=e,e=null),!t)this._ended=this._ending=!0,this._currentRequest.end(null,null,n);else{var r=this,i=this._currentRequest;this.write(t,e,function(){r._ended=!0,i.end(null,null,n)}),this._ending=!0}};ds.prototype.setHeader=function(t,e){this._options.headers[t]=e,this._currentRequest.setHeader(t,e)};ds.prototype.removeHeader=function(t){delete this._options.headers[t],this._currentRequest.removeHeader(t)};ds.prototype.setTimeout=function(t,e){var n=this;function r(o){o.setTimeout(t),o.removeListener("timeout",o.destroy),o.addListener("timeout",o.destroy)}function i(o){n._timeout&&clearTimeout(n._timeout),n._timeout=setTimeout(function(){n.emit("timeout"),s()},t),r(o)}function s(){n._timeout&&(clearTimeout(n._timeout),n._timeout=null),n.removeListener("abort",s),n.removeListener("error",s),n.removeListener("response",s),n.removeListener("close",s),e&&n.removeListener("timeout",e),n.socket||n._currentRequest.removeListener("socket",i)}return e&&this.on("timeout",e),this.socket?i(this.socket):this._currentRequest.once("socket",i),this.on("socket",r),this.on("abort",s),this.on("error",s),this.on("response",s),this.on("close",s),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(t){ds.prototype[t]=function(e,n){return this._currentRequest[t](e,n)}});["aborted","connection","socket"].forEach(function(t){Object.defineProperty(ds.prototype,t,{get:function(){return this._currentRequest[t]}})});ds.prototype._sanitizeOptions=function(t){if(t.headers||(t.headers={}),q4e(t.sensitiveHeaders)||(t.sensitiveHeaders=[]),t.host&&(t.hostname||(t.hostname=t.host),delete t.host),!t.pathname&&t.path){var e=t.path.indexOf("?");e<0?t.pathname=t.path:(t.pathname=t.path.substring(0,e),t.search=t.path.substring(e))}};ds.prototype._performRequest=function(){var t=this._options.protocol,e=this._options.nativeProtocols[t];if(!e)throw new TypeError("Unsupported protocol "+t);if(this._options.agents){var n=t.slice(0,-1);this._options.agent=this._options.agents[n]}var r=this._currentRequest=e.request(this._options,this._onNativeResponse);r._redirectable=this;for(var i of Vq)r.on(i,zq[i]);if(this._currentUrl=/^\//.test(this._options.path)?XE.format(this._options):this._options.path,this._isRedirect){var s=0,o=this,a=this._requestBodyBuffers;(function c(l){if(r===o._currentRequest)if(l)o.emit("error",l);else if(s<a.length){var u=a[s++];r.finished||r.write(u.data,u.encoding,c)}else o._ended&&r.end()})()}};ds.prototype._processResponse=function(t){var e=t.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:t.headers,statusCode:e});var n=t.headers.location;if(!n||this._options.followRedirects===!1||e<300||e>=400){t.responseUrl=this._currentUrl,t.redirects=this._redirects,this.emit("response",t),this._requestBodyBuffers=[];return}if(Yq(this._currentRequest),t.destroy(),++this._redirectCount>this._options.maxRedirects)throw new N4e;var r,i=this._options.beforeRedirect;i&&(r=Object.assign({Host:t.req.getHeader("host")},this._options.headers));var s=this._options.method;((e===301||e===302)&&this._options.method==="POST"||e===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],Bq(/^content-/i,this._options.headers));var o=Bq(/^host$/i,this._options.headers),a=Kq(this._currentUrl),c=o||a.host,l=/^\w+:/.test(n)?this._currentUrl:XE.format(Object.assign(a,{host:c})),u=F4e(n,l);if(Cce("redirecting to",u.href),this._isRedirect=!0,Gq(u,this._options),(u.protocol!==a.protocol&&u.protocol!=="https:"||u.host!==c&&!B4e(u.host,c))&&Bq(this._headerFilter,this._options.headers),bh(i)){var d={headers:t.headers,statusCode:e},f={url:l,method:s,headers:r};i(this._options,d,f),this._sanitizeOptions(this._options)}this._performRequest()};function Rce(t){var e={maxRedirects:21,maxBodyLength:10485760},n={};return Object.keys(t).forEach(function(r){var i=r+":",s=n[i]=t[r],o=e[r]=Object.create(s);function a(l,u,d){return G4e(l)?l=Gq(l):xh(l)?l=Gq(Kq(l)):(d=u,u=kce(l),l={protocol:i}),bh(u)&&(d=u,u=null),u=Object.assign({maxRedirects:e.maxRedirects,maxBodyLength:e.maxBodyLength},l,u),u.nativeProtocols=n,!xh(u.host)&&!xh(u.hostname)&&(u.hostname="::1"),jq.equal(u.protocol,i,"protocol mismatch"),Cce("options",u),new ds(u,d)}function c(l,u,d){var f=o.request(l,u,d);return f.end(),f}Object.defineProperties(o,{request:{value:a,configurable:!0,enumerable:!0,writable:!0},get:{value:c,configurable:!0,enumerable:!0,writable:!0}})}),e}function Ice(){}function Kq(t){var e;if(Wq)e=new YE(t);else if(e=kce(XE.parse(t)),!xh(e.protocol))throw new qq({input:t});return e}function F4e(t,e){return Wq?new YE(t,e):Kq(XE.resolve(e,t))}function kce(t){if(/^\[/.test(t.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(t.hostname))throw new qq({input:t.href||t});if(/^\[/.test(t.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(t.host))throw new qq({input:t.href||t});return t}function Gq(t,e){var n=e||{};for(var r of M4e)n[r]=t[r];return n.hostname.startsWith("[")&&(n.hostname=n.hostname.slice(1,-1)),n.port!==""&&(n.port=Number(n.port)),n.path=n.search?n.pathname+n.search:n.pathname,n}function Bq(t,e){var n;for(var r in e)t.test(r)&&(n=e[r],delete e[r]);return n===null||typeof n>"u"?void 0:String(n).trim()}function JE(t,e,n){function r(i){bh(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,i||{}),this.code=t,this.message=this.cause?e+": "+this.cause.message:e}return r.prototype=new(n||Error),Object.defineProperties(r.prototype,{constructor:{value:r,enumerable:!1},name:{value:"Error ["+t+"]",enumerable:!1}}),r}function Yq(t,e){for(var n of Vq)t.removeListener(n,zq[n]);t.on("error",Ice),t.destroy(e)}function B4e(t,e){jq(xh(t)&&xh(e));var n=t.length-e.length-1;return n>0&&t[n]==="."&&t.endsWith(e)}function q4e(t){return t instanceof Array}function xh(t){return typeof t=="string"||t instanceof String}function bh(t){return typeof t=="function"}function $4e(t){return typeof t=="object"&&"length"in t}function G4e(t){return YE&&t instanceof YE}function H4e(t){return t.replace(/[\]\\/()*+?.$]/g,"\\$&")}Xq.exports=Rce({http:k4e,https:P4e});Xq.exports.wrap=Rce});var Mce=B((vAt,Oce)=>{var j4e=require("http"),W4e=require("https"),QE=bce(),RR=CR(),V4e=Pce();QE=Object.keys(QE).map(function(t){return QE[t]});var z4e={http:j4e,https:W4e};Oce.exports={deleteLength:function(e,n,r){(e.method==="DELETE"||e.method==="OPTIONS")&&!e.headers["content-length"]&&(e.headers["content-length"]="0",delete e.headers["transfer-encoding"])},timeout:function(e,n,r){r.timeout&&e.socket.setTimeout(r.timeout)},XHeaders:function(e,n,r){if(r.xfwd){var i=e.isSpdy||RR.hasEncryptedConnection(e),s={for:e.connection.remoteAddress||e.socket.remoteAddress,port:RR.getPort(e),proto:i?"https":"http"};["for","port","proto"].forEach(function(o){e.headers["x-forwarded-"+o]=(e.headers["x-forwarded-"+o]||"")+(e.headers["x-forwarded-"+o]?",":"")+s[o]}),e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers.host||""}},stream:function(e,n,r,i,s,o){s.emit("start",e,n,r.target||r.forward);var a=r.followRedirects?V4e:z4e,c=a.http,l=a.https;if(r.forward){var u=(r.forward.protocol==="https:"?l:c).request(RR.setupOutgoing(r.ssl||{},r,e,"forward")),d=g(u,r.forward);if(e.on("error",d),u.on("error",d),(r.buffer||e).pipe(u),!r.target)return n.end()}var f=(r.target.protocol==="https:"?l:c).request(RR.setupOutgoing(r.ssl||{},r,e));f.on("socket",function(y){s&&!f.getHeader("expect")&&s.emit("proxyReq",f,e,n,r)}),r.proxyTimeout&&f.setTimeout(r.proxyTimeout,function(){f.abort()}),e.on("aborted",function(){f.abort()});var m=g(f,r.target);e.on("error",m),f.on("error",m);function g(y,w){return function(T){if(e.socket.destroyed&&T.code==="ECONNRESET")return s.emit("econnreset",T,e,n,w),y.abort();o?o(T,e,n,w):s.emit("error",T,e,n,w)}}(r.buffer||e).pipe(f),f.on("response",function(y){if(s&&s.emit("proxyRes",y,e,n),!n.headersSent&&!r.selfHandleResponse)for(var w=0;w<QE.length&&!QE[w](e,n,y,r);w++);n.finished?s&&s.emit("end",e,n,y):(y.on("end",function(){s&&s.emit("end",e,n,y)}),r.selfHandleResponse||y.pipe(n))})}}});var Dce=B((EAt,Nce)=>{var K4e=require("http"),Y4e=require("https"),Hy=CR();Nce.exports={checkMethodAndHeader:function(e,n){if(e.method!=="GET"||!e.headers.upgrade||e.headers.upgrade.toLowerCase()!=="websocket")return n.destroy(),!0},XHeaders:function(e,n,r){if(r.xfwd){var i={for:e.connection.remoteAddress||e.socket.remoteAddress,port:Hy.getPort(e),proto:Hy.hasEncryptedConnection(e)?"wss":"ws"};["for","port","proto"].forEach(function(s){e.headers["x-forwarded-"+s]=(e.headers["x-forwarded-"+s]||"")+(e.headers["x-forwarded-"+s]?",":"")+i[s]})}},stream:function(e,n,r,i,s,o){var a=function(u,d){return Object.keys(d).reduce(function(f,m){var g=d[m];if(!Array.isArray(g))return f.push(m+": "+g),f;for(var y=0;y<g.length;y++)f.push(m+": "+g[y]);return f},[u]).join(`\r
237
237
  `)+`\r
238
238
  \r
239
- `};Hy.setupSocket(n),i&&i.length&&n.unshift(i);var c=(Hy.isSSL.test(r.target.protocol)?Y4e:K4e).request(Hy.setupOutgoing(r.ssl||{},r,e));return s&&s.emit("proxyReqWs",c,e,n,r,i),c.on("error",l),c.on("response",function(u){u.upgrade||(n.write(a("HTTP/"+u.httpVersion+" "+u.statusCode+" "+u.statusMessage,u.headers)),u.pipe(n))}),c.on("upgrade",function(u,d,f){d.on("error",l),d.on("end",function(){s.emit("close",u,d,f)}),n.on("error",function(){d.end()}),Hy.setupSocket(d),f&&f.length&&d.unshift(f),n.write(a("HTTP/1.1 101 Switching Protocols",u.headers)),d.pipe(n).pipe(d),s.emit("open",d),s.emit("proxySocket",d)}),c.end();function l(u){o?o(u,e,n):s.emit("error",u,e,n),n.end()}}}});var Gce=B((wAt,$ce)=>{var Bce=$ce.exports,Lce=require("util")._extend,X4e=require("url").parse,qce=gce(),J4e=require("http"),Q4e=require("https"),Uce=Mce(),Fce=Dce();Bce.Server=Th;function Jq(t){return function(e){return function(n,r){var i=t==="ws"?this.wsPasses:this.webPasses,s=[].slice.call(arguments),o=s.length-1,a,c;typeof s[o]=="function"&&(c=s[o],o--);var l=e;if(!(s[o]instanceof Buffer)&&s[o]!==r&&(l=Lce({},e),Lce(l,s[o]),o--),s[o]instanceof Buffer&&(a=s[o]),["target","forward"].forEach(function(d){typeof l[d]=="string"&&(l[d]=X4e(l[d]))}),!l.target&&!l.forward)return this.emit("error",new Error("Must provide a proper URL as target"));for(var u=0;u<i.length&&!i[u](n,r,l,a,this,c);u++);}}}Bce.createRightProxy=Jq;function Th(t){qce.call(this),t=t||{},t.prependPath=t.prependPath!==!1,this.web=this.proxyRequest=Jq("web")(t),this.ws=this.proxyWebsocketRequest=Jq("ws")(t),this.options=t,this.webPasses=Object.keys(Uce).map(function(e){return Uce[e]}),this.wsPasses=Object.keys(Fce).map(function(e){return Fce[e]}),this.on("error",this.onError,this)}require("util").inherits(Th,qce);Th.prototype.onError=function(t){if(this.listeners("error").length===1)throw t};Th.prototype.listen=function(t,e){var n=this,r=function(i,s){n.web(i,s)};return this._server=this.options.ssl?Q4e.createServer(this.options.ssl,r):J4e.createServer(r),this.options.ws&&this._server.on("upgrade",function(i,s,o){n.ws(i,s,o)}),this._server.listen(t,e),this};Th.prototype.close=function(t){var e=this;this._server&&this._server.close(n);function n(){e._server=null,t&&t.apply(null,arguments)}};Th.prototype.before=function(t,e,n){if(t!=="ws"&&t!=="web")throw new Error("type must be `web` or `ws`");var r=t==="ws"?this.wsPasses:this.webPasses,i=!1;if(r.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");r.splice(i,0,n)};Th.prototype.after=function(t,e,n){if(t!=="ws"&&t!=="web")throw new Error("type must be `web` or `ws`");var r=t==="ws"?this.wsPasses:this.webPasses,i=!1;if(r.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");r.splice(i++,0,n)}});var jce=B((SAt,Hce)=>{var ZE=Gce().Server;function Qq(t){return new ZE(t)}ZE.createProxyServer=Qq;ZE.createServer=Qq;ZE.createProxy=Qq;Hce.exports=ZE});var Vce=B((xAt,Wce)=>{Wce.exports=jce()});function IR(t,e,n){return!t||Z4e.some(r=>t.startsWith(r))||t.startsWith("/proxy/")?t:t.startsWith(`http://localhost:${n}`)?t.replace(`http://localhost:${n}`,`/proxy/${e}`):t.startsWith("/")&&!t.startsWith("//")?`/proxy/${e}${t}`:t}function zce(t,e,n){let r=`/proxy/${e}`,i=new RegExp(`(${eWe.join("|")})=(["'])([^"']*?)\\2`,"gi");return t=t.replace(i,(s,o,a,c)=>{if(o.toLowerCase()==="srcset"){let l=c.split(",").map(u=>{let[d,...f]=u.trim().split(/\s+/),m=IR(d,e,n);return f.length?`${m} ${f.join(" ")}`:m}).join(", ");return`${o}=${a}${l}${a}`}return`${o}=${a}${IR(c,e,n)}${a}`}),t=t.replace(/url\(\s*(["']?)(\/_next\/[^)"']+)\1\s*\)/gi,(s,o,a)=>`url(${o}${r}${a}${o})`),t=t.replace(/"(\/_next\/[^"]+)"/g,(s,o)=>`"${r}${o}"`),t}var Z4e,eWe,Kce=ae(()=>{Z4e=["data:","javascript:","#","mailto:","blob:"],eWe=["href","src","action","srcset","poster","data","formaction","data-src","data-href","data-url","data-background"]});function Yce(t,e){let n=`/proxy/${t}`;return`
239
+ `};Hy.setupSocket(n),i&&i.length&&n.unshift(i);var c=(Hy.isSSL.test(r.target.protocol)?Y4e:K4e).request(Hy.setupOutgoing(r.ssl||{},r,e));return s&&s.emit("proxyReqWs",c,e,n,r,i),c.on("error",l),c.on("response",function(u){u.upgrade||(n.write(a("HTTP/"+u.httpVersion+" "+u.statusCode+" "+u.statusMessage,u.headers)),u.pipe(n))}),c.on("upgrade",function(u,d,f){d.on("error",l),d.on("end",function(){s.emit("close",u,d,f)}),n.on("error",function(){d.end()}),Hy.setupSocket(d),f&&f.length&&d.unshift(f),n.write(a("HTTP/1.1 101 Switching Protocols",u.headers)),d.pipe(n).pipe(d),s.emit("open",d),s.emit("proxySocket",d)}),c.end();function l(u){o?o(u,e,n):s.emit("error",u,e,n),n.end()}}}});var Gce=B((wAt,$ce)=>{var Bce=$ce.exports,Lce=require("util")._extend,X4e=require("url").parse,qce=gce(),J4e=require("http"),Q4e=require("https"),Uce=Mce(),Fce=Dce();Bce.Server=Th;function Jq(t){return function(e){return function(n,r){var i=t==="ws"?this.wsPasses:this.webPasses,s=[].slice.call(arguments),o=s.length-1,a,c;typeof s[o]=="function"&&(c=s[o],o--);var l=e;if(!(s[o]instanceof Buffer)&&s[o]!==r&&(l=Lce({},e),Lce(l,s[o]),o--),s[o]instanceof Buffer&&(a=s[o]),["target","forward"].forEach(function(d){typeof l[d]=="string"&&(l[d]=X4e(l[d]))}),!l.target&&!l.forward)return this.emit("error",new Error("Must provide a proper URL as target"));for(var u=0;u<i.length&&!i[u](n,r,l,a,this,c);u++);}}}Bce.createRightProxy=Jq;function Th(t){qce.call(this),t=t||{},t.prependPath=t.prependPath!==!1,this.web=this.proxyRequest=Jq("web")(t),this.ws=this.proxyWebsocketRequest=Jq("ws")(t),this.options=t,this.webPasses=Object.keys(Uce).map(function(e){return Uce[e]}),this.wsPasses=Object.keys(Fce).map(function(e){return Fce[e]}),this.on("error",this.onError,this)}require("util").inherits(Th,qce);Th.prototype.onError=function(t){if(this.listeners("error").length===1)throw t};Th.prototype.listen=function(t,e){var n=this,r=function(i,s){n.web(i,s)};return this._server=this.options.ssl?Q4e.createServer(this.options.ssl,r):J4e.createServer(r),this.options.ws&&this._server.on("upgrade",function(i,s,o){n.ws(i,s,o)}),this._server.listen(t,e),this};Th.prototype.close=function(t){var e=this;this._server&&this._server.close(n);function n(){e._server=null,t&&t.apply(null,arguments)}};Th.prototype.before=function(t,e,n){if(t!=="ws"&&t!=="web")throw new Error("type must be `web` or `ws`");var r=t==="ws"?this.wsPasses:this.webPasses,i=!1;if(r.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");r.splice(i,0,n)};Th.prototype.after=function(t,e,n){if(t!=="ws"&&t!=="web")throw new Error("type must be `web` or `ws`");var r=t==="ws"?this.wsPasses:this.webPasses,i=!1;if(r.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");r.splice(i++,0,n)}});var jce=B((SAt,Hce)=>{var ZE=Gce().Server;function Qq(t){return new ZE(t)}ZE.createProxyServer=Qq;ZE.createServer=Qq;ZE.createProxy=Qq;Hce.exports=ZE});var Vce=B((xAt,Wce)=>{Wce.exports=jce()});function IR(t,e,n){return!t||Z4e.some(r=>t.startsWith(r))||t.startsWith("/proxy/")?t:t.startsWith(`http://localhost:${n}`)?t.replace(`http://localhost:${n}`,`/proxy/${e}`):t.startsWith("/")&&!t.startsWith("//")?`/proxy/${e}${t}`:t}function zce(t,e,n){let r=`/proxy/${e}`,i=new RegExp(`(${e3e.join("|")})=(["'])([^"']*?)\\2`,"gi");return t=t.replace(i,(s,o,a,c)=>{if(o.toLowerCase()==="srcset"){let l=c.split(",").map(u=>{let[d,...f]=u.trim().split(/\s+/),m=IR(d,e,n);return f.length?`${m} ${f.join(" ")}`:m}).join(", ");return`${o}=${a}${l}${a}`}return`${o}=${a}${IR(c,e,n)}${a}`}),t=t.replace(/url\(\s*(["']?)(\/_next\/[^)"']+)\1\s*\)/gi,(s,o,a)=>`url(${o}${r}${a}${o})`),t=t.replace(/"(\/_next\/[^"]+)"/g,(s,o)=>`"${r}${o}"`),t}var Z4e,e3e,Kce=ae(()=>{Z4e=["data:","javascript:","#","mailto:","blob:"],e3e=["href","src","action","srcset","poster","data","formaction","data-src","data-href","data-url","data-background"]});function Yce(t,e){let n=`/proxy/${t}`;return`
240
240
  // Service Worker for 9Remote Proxy - Port ${e}
241
241
  const PROXY_BASE = '${n}';
242
242
  const TARGET_PORT = ${e};
@@ -333,7 +333,7 @@ self.addEventListener('fetch', (event) => {
333
333
  });
334
334
  }
335
335
  })();
336
- </script>`}var Jce=ae(()=>{});function t2(t){let e=Number(t);return!Number.isInteger(e)||e<1||e>65535||e===Ts?null:e}function kR(t){let e=t2(t);if(e===null)return null;let n=ew.get(e);if(n)return n;let r=(0,Zce.randomUUID)();return e2.set(r,e),ew.set(e,r),r}function PR(t){let e=t2(t);if(e===null)return;let n=ew.get(e);n&&e2.delete(n),ew.delete(e)}function tWe(t){return typeof t=="string"&&t?e2.get(t)??null:null}function nWe(t){let e=t2(t);return e!==null&&ew.has(e)}function tle(t,e){t.emit("site:httpChunk",e)}function Ah(t,e,n){tle(t,{reqId:e,seq:0,total:1,b64:"",done:!0,error:n})}function nle(t){t.on("site:httpRequest",async(e,n)=>{typeof n=="function"&&n({ok:!0});let{reqId:r,port:i,method:s,target:o,headers:a={},bodyB64:c}=e||{};if(typeof r!="string"||!r)return;let l=Number(i);if(!Number.isInteger(l)||l<1||l>65535)return Ah(t,r,"bad-port");if(!nWe(l))return Ah(t,r,"no-session");if(!rWe.has(s))return Ah(t,r,"bad-method");if(typeof o!="string"||!o.startsWith("/"))return Ah(t,r,"bad-target");if(typeof c=="string"&&c.length>iWe)return Ah(t,r,"body-too-large");let u={};for(let[m,g]of Object.entries(a||{}))aWe.has(m.toLowerCase())||(u[m]=g);let d=new AbortController,f=setTimeout(()=>d.abort(),oWe);try{let m=await fetch(`http://localhost:${l}${o}`,{method:s,headers:u,body:c?Buffer.from(c,"base64"):void 0,redirect:"manual",signal:d.signal}),g={};for(let[T,R]of m.headers)ele.has(T.toLowerCase())||(g[T]=R);let y=Buffer.from(await m.arrayBuffer());if(y.length>sWe)return Ah(t,r,"too-large");let w=y.toString("base64"),S=Math.max(1,Math.ceil(w.length/Zq));for(let T=0;T<S;T++)tle(t,{reqId:r,seq:T,total:S,...T===0?{status:m.status,headers:g}:{},b64:w.slice(T*Zq,(T+1)*Zq),done:T===S-1})}catch(m){Ah(t,r,m.name==="AbortError"?"timeout":m.message)}finally{clearTimeout(f)}})}function cWe(t){switch(t){case"gzip":return(0,jy.createGunzip)();case"deflate":return(0,jy.createInflate)();case"br":return(0,jy.createBrotliDecompress)();default:return null}}function lWe(t,e){if(t.includes("<head>"))return t.replace("<head>","<head>"+e);if(t.includes("<HEAD>"))return t.replace("<HEAD>","<HEAD>"+e);let n=t.match(/<head[^>]*>/i);return n?t.replace(n[0],n[0]+e):e+t}function rle(){"";let t=Qce.default.createProxyServer({selfHandleResponse:!0});return t.on("proxyRes",(e,n,r)=>{let i=n._proxyTargetPort,s=n._proxySessionId,o=e.headers["content-type"]||"",a=e.headers["content-encoding"]||"",c=o.includes("text/html"),l={...e.headers};if(l.location&&(l.location=IR(l.location,s,i)),o.includes("application/json")||o.includes("text/x-component")){r.writeHead(e.statusCode,l),e.pipe(r);return}if(o.includes("javascript")||o.includes("text/javascript")){r.writeHead(e.statusCode,l),e.pipe(r);return}if(!c){r.writeHead(e.statusCode,l),e.pipe(r);return}delete l["content-length"],delete l["content-encoding"];let f=cWe(a),m=f?e.pipe(f):e,g=[];m.on("data",y=>g.push(y)),m.on("error",y=>{console.error("[Proxy] Decompress error:",y.message),r.writeHead(502),r.end("Bad Gateway: Decompression failed")}),m.on("end",()=>{let y=Buffer.concat(g).toString("utf8");y=zce(y,s,i);let w=Xce(s,i);y=lWe(y,w),r.writeHead(e.statusCode,l),r.end(y)})}),t}function ile(t,e,n,r,i,s){let o=tWe(r);if(o&&i==="/sw.js"){let a=Yce(r,o);n.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Service-Worker-Allowed":"/","Cache-Control":"no-store, no-cache, must-revalidate"}),n.end(a);return}if(!o){n.writeHead(401,{"Content-Type":"text/html"}),n.end(`
336
+ </script>`}var Jce=ae(()=>{});function t2(t){let e=Number(t);return!Number.isInteger(e)||e<1||e>65535||e===Ts?null:e}function kR(t){let e=t2(t);if(e===null)return null;let n=ew.get(e);if(n)return n;let r=(0,Zce.randomUUID)();return e2.set(r,e),ew.set(e,r),r}function PR(t){let e=t2(t);if(e===null)return;let n=ew.get(e);n&&e2.delete(n),ew.delete(e)}function t3e(t){return typeof t=="string"&&t?e2.get(t)??null:null}function n3e(t){let e=t2(t);return e!==null&&ew.has(e)}function tle(t,e){t.emit("site:httpChunk",e)}function Ah(t,e,n){tle(t,{reqId:e,seq:0,total:1,b64:"",done:!0,error:n})}function nle(t){t.on("site:httpRequest",async(e,n)=>{typeof n=="function"&&n({ok:!0});let{reqId:r,port:i,method:s,target:o,headers:a={},bodyB64:c}=e||{};if(typeof r!="string"||!r)return;let l=Number(i);if(!Number.isInteger(l)||l<1||l>65535)return Ah(t,r,"bad-port");if(!n3e(l))return Ah(t,r,"no-session");if(!r3e.has(s))return Ah(t,r,"bad-method");if(typeof o!="string"||!o.startsWith("/"))return Ah(t,r,"bad-target");if(typeof c=="string"&&c.length>i3e)return Ah(t,r,"body-too-large");let u={};for(let[m,g]of Object.entries(a||{}))a3e.has(m.toLowerCase())||(u[m]=g);let d=new AbortController,f=setTimeout(()=>d.abort(),o3e);try{let m=await fetch(`http://localhost:${l}${o}`,{method:s,headers:u,body:c?Buffer.from(c,"base64"):void 0,redirect:"manual",signal:d.signal}),g={};for(let[T,R]of m.headers)ele.has(T.toLowerCase())||(g[T]=R);let y=Buffer.from(await m.arrayBuffer());if(y.length>s3e)return Ah(t,r,"too-large");let w=y.toString("base64"),S=Math.max(1,Math.ceil(w.length/Zq));for(let T=0;T<S;T++)tle(t,{reqId:r,seq:T,total:S,...T===0?{status:m.status,headers:g}:{},b64:w.slice(T*Zq,(T+1)*Zq),done:T===S-1})}catch(m){Ah(t,r,m.name==="AbortError"?"timeout":m.message)}finally{clearTimeout(f)}})}function c3e(t){switch(t){case"gzip":return(0,jy.createGunzip)();case"deflate":return(0,jy.createInflate)();case"br":return(0,jy.createBrotliDecompress)();default:return null}}function l3e(t,e){if(t.includes("<head>"))return t.replace("<head>","<head>"+e);if(t.includes("<HEAD>"))return t.replace("<HEAD>","<HEAD>"+e);let n=t.match(/<head[^>]*>/i);return n?t.replace(n[0],n[0]+e):e+t}function rle(){"";let t=Qce.default.createProxyServer({selfHandleResponse:!0});return t.on("proxyRes",(e,n,r)=>{let i=n._proxyTargetPort,s=n._proxySessionId,o=e.headers["content-type"]||"",a=e.headers["content-encoding"]||"",c=o.includes("text/html"),l={...e.headers};if(l.location&&(l.location=IR(l.location,s,i)),o.includes("application/json")||o.includes("text/x-component")){r.writeHead(e.statusCode,l),e.pipe(r);return}if(o.includes("javascript")||o.includes("text/javascript")){r.writeHead(e.statusCode,l),e.pipe(r);return}if(!c){r.writeHead(e.statusCode,l),e.pipe(r);return}delete l["content-length"],delete l["content-encoding"];let f=c3e(a),m=f?e.pipe(f):e,g=[];m.on("data",y=>g.push(y)),m.on("error",y=>{console.error("[Proxy] Decompress error:",y.message),r.writeHead(502),r.end("Bad Gateway: Decompression failed")}),m.on("end",()=>{let y=Buffer.concat(g).toString("utf8");y=zce(y,s,i);let w=Xce(s,i);y=l3e(y,w),r.writeHead(e.statusCode,l),r.end(y)})}),t}function ile(t,e,n,r,i,s){let o=t3e(r);if(o&&i==="/sw.js"){let a=Yce(r,o);n.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Service-Worker-Allowed":"/","Cache-Control":"no-store, no-cache, must-revalidate"}),n.end(a);return}if(!o){n.writeHead(401,{"Content-Type":"text/html"}),n.end(`
337
337
  <!DOCTYPE html>
338
338
  <html>
339
339
  <head><title>Unauthorized</title></head>
@@ -344,24 +344,24 @@ self.addEventListener('fetch', (event) => {
344
344
  </div>
345
345
  </body>
346
346
  </html>
347
- `);return}e._proxyTargetPort=o,e._proxySessionId=r,e.url=i+(s||""),t.web(e,n,{target:`http://localhost:${o}`,changeOrigin:!0},a=>{n.writeHead(502),n.end(`Bad Gateway: ${a.message}`)})}var jy,Qce,Zce,e2,ew,rWe,iWe,sWe,Zq,oWe,ele,aWe,n2=ae(()=>{jy=require("zlib"),Qce=ce(Vce(),1),Zce=require("crypto");Lt();Kce();Jce();e2=new Map,ew=new Map;rWe=new Set(["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]),iWe=7e5,sWe=64*1024*1024,Zq=48e3,oWe=6e4,ele=new Set(["host","connection","cookie","set-cookie","content-encoding","content-length","x-frame-options","content-security-policy","strict-transport-security","transfer-encoding"]),aWe=new Set([...ele,"accept-encoding"])});var Wy,r2=ae(()=>{Wy={HEADER:"x-9remote-session",MAX_PARENT_HOPS:8,PROBE_TIMEOUT_MS:3e3}});function i2(){if(Vy)return Vy;try{let t=OR.default.readFileSync(sle,"utf8").trim();if(t)return Vy=t}catch{}return Vy=(0,MR.randomBytes)(32).toString("hex"),OR.default.mkdirSync(Oe.STATE,{recursive:!0}),OR.default.writeFileSync(sle,Vy,{mode:384}),Vy}function ale(t){let e=String(t||"").replace(/^Bearer\s+/i,""),n=i2();return e.length!==n.length?!1:(0,MR.timingSafeEqual)(Buffer.from(e),Buffer.from(n))}var OR,ole,MR,sle,Vy,s2=ae(()=>{OR=ce(require("fs"),1),ole=ce(require("path"),1),MR=require("crypto");Lt();sle=ole.default.join(Oe.STATE,"mcpToken"),Vy=null});function o2(t){try{return JSON.parse(qo.default.readFileSync(t,"utf8"))}catch{return{}}}function NR(t,e,n){let r=t;for(let i of e){if(!r[i]){if(!n)return null;r[i]={}}r=r[i]}return r}function uWe(t,e){for(let n=e.length;n>0;n--){let r=NR(t,e.slice(0,n-1),!1),i=e[n-1];if(!r?.[i]||Object.keys(r[i]).length)return;delete r[i]}}function Qd({file:t,keyPath:e=["mcpServers"],entry:n,mode:r=384}){let i=s=>typeof e=="function"?e(s):e;return{enable(){let s=t(),o=o2(s);NR(o,i(o),!0)[Ga]=n(),qo.default.mkdirSync(LR.default.dirname(s),{recursive:!0}),xn(s,o,{mode:r})},disable(){let s=t();if(!qo.default.existsSync(s))return;let o=o2(s),a=i(o),c=NR(o,a,!1);c?.[Ga]&&(delete c[Ga],uWe(o,a),xn(s,o,{mode:r}))},isEnabled(){let s=o2(t());return!!NR(s,i(s),!1)?.[Ga]}}}function cle({file:t,lines:e}){let n=`# 9Remote MCP (${Ga})`,r="# /9Remote MCP",i=new RegExp(`${a2(n)}[\\s\\S]*?${a2(r)}\\n?`,"g"),s=new RegExp(`^\\[mcp_servers\\."?${a2(Ga)}"?(?:\\.[^\\]]*)?\\][^\\n]*\\n(?:(?!\\[)[^\\n]*\\n?)*`,"gm"),o=a=>qo.default.existsSync(a)?qo.default.readFileSync(a,"utf8").replace(i,"").replace(s,""):"";return{enable(){let a=t();qo.default.mkdirSync(LR.default.dirname(a),{recursive:!0});let c=o(a);c.length&&!c.endsWith(`
347
+ `);return}e._proxyTargetPort=o,e._proxySessionId=r,e.url=i+(s||""),t.web(e,n,{target:`http://localhost:${o}`,changeOrigin:!0},a=>{n.writeHead(502),n.end(`Bad Gateway: ${a.message}`)})}var jy,Qce,Zce,e2,ew,r3e,i3e,s3e,Zq,o3e,ele,a3e,n2=ae(()=>{jy=require("zlib"),Qce=ce(Vce(),1),Zce=require("crypto");Lt();Kce();Jce();e2=new Map,ew=new Map;r3e=new Set(["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]),i3e=7e5,s3e=64*1024*1024,Zq=48e3,o3e=6e4,ele=new Set(["host","connection","cookie","set-cookie","content-encoding","content-length","x-frame-options","content-security-policy","strict-transport-security","transfer-encoding"]),a3e=new Set([...ele,"accept-encoding"])});var Wy,r2=ae(()=>{Wy={HEADER:"x-9remote-session",MAX_PARENT_HOPS:8,PROBE_TIMEOUT_MS:3e3}});function i2(){if(Vy)return Vy;try{let t=OR.default.readFileSync(sle,"utf8").trim();if(t)return Vy=t}catch{}return Vy=(0,MR.randomBytes)(32).toString("hex"),OR.default.mkdirSync(Oe.STATE,{recursive:!0}),OR.default.writeFileSync(sle,Vy,{mode:384}),Vy}function ale(t){let e=String(t||"").replace(/^Bearer\s+/i,""),n=i2();return e.length!==n.length?!1:(0,MR.timingSafeEqual)(Buffer.from(e),Buffer.from(n))}var OR,ole,MR,sle,Vy,s2=ae(()=>{OR=ce(require("fs"),1),ole=ce(require("path"),1),MR=require("crypto");Lt();sle=ole.default.join(Oe.STATE,"mcpToken"),Vy=null});function o2(t){try{return JSON.parse(qo.default.readFileSync(t,"utf8"))}catch{return{}}}function NR(t,e,n){let r=t;for(let i of e){if(!r[i]){if(!n)return null;r[i]={}}r=r[i]}return r}function u3e(t,e){for(let n=e.length;n>0;n--){let r=NR(t,e.slice(0,n-1),!1),i=e[n-1];if(!r?.[i]||Object.keys(r[i]).length)return;delete r[i]}}function Qd({file:t,keyPath:e=["mcpServers"],entry:n,mode:r=384}){let i=s=>typeof e=="function"?e(s):e;return{enable(){let s=t(),o=o2(s);NR(o,i(o),!0)[Ga]=n(),qo.default.mkdirSync(LR.default.dirname(s),{recursive:!0}),xn(s,o,{mode:r})},disable(){let s=t();if(!qo.default.existsSync(s))return;let o=o2(s),a=i(o),c=NR(o,a,!1);c?.[Ga]&&(delete c[Ga],u3e(o,a),xn(s,o,{mode:r}))},isEnabled(){let s=o2(t());return!!NR(s,i(s),!1)?.[Ga]}}}function cle({file:t,lines:e}){let n=`# 9Remote MCP (${Ga})`,r="# /9Remote MCP",i=new RegExp(`${a2(n)}[\\s\\S]*?${a2(r)}\\n?`,"g"),s=new RegExp(`^\\[mcp_servers\\."?${a2(Ga)}"?(?:\\.[^\\]]*)?\\][^\\n]*\\n(?:(?!\\[)[^\\n]*\\n?)*`,"gm"),o=a=>qo.default.existsSync(a)?qo.default.readFileSync(a,"utf8").replace(i,"").replace(s,""):"";return{enable(){let a=t();qo.default.mkdirSync(LR.default.dirname(a),{recursive:!0});let c=o(a);c.length&&!c.endsWith(`
348
348
  `)&&(c+=`
349
349
  `),qo.default.writeFileSync(a,`${c}${[n,...e(),r].join(`
350
350
  `)}
351
- `,"utf8")},disable(){let a=t();qo.default.existsSync(a)&&qo.default.writeFileSync(a,o(a),"utf8")},isEnabled(){let a=t();return qo.default.existsSync(a)&&qo.default.readFileSync(a,"utf8").includes(n)}}}function tw(){if(DR===null){let t=Ra().artifactEnabled;DR=t===void 0?Pl.DEFAULT_ENABLED:!!t}return DR}function dWe(t,e){let n=dle[t];if(n)try{e?n.enable():n.disable()}catch(r){ule.warn(`${e?"enable":"disable"} ${t} failed: ${r.message}`)}}function fle(t){for(let e of Yy)dWe(e,t)}function ple(t){let e=!!t;return bd({artifactEnabled:e}),DR=e,fle(e),ule.info(`artifact MCP ${e?"enabled":"disabled"} for ${Yy.join(", ")}`),e}function hle(){let t=tw();return fle(t),t}var qo,LR,lle,ule,zc,Ga,Kc,zy,Ky,Yc,a2,dle,Yy,DR,UR=ae(()=>{qo=ce(require("fs"),1),LR=ce(require("path"),1),lle=ce(require("os"),1);Lt();r2();s2();Dg();So();tt();ule=Se("mcp"),zc=`http://127.0.0.1:${Ts}${Pl.PATH}`,Ga=Pl.SERVER_NAME,Kc=()=>`Bearer ${i2()}`,zy=Wy.HEADER,Ky="NINE_REMOTE_SESSION_ID",Yc=(...t)=>LR.default.join(lle.default.homedir(),...t);a2=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");dle={claude:Qd({file:()=>Yc(".claude.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),opencode:Qd({file:()=>Yc(".config","opencode","opencode.json"),keyPath:t=>t?.mcp?.servers?["mcp","servers"]:["mcp"],entry:()=>({type:"remote",url:zc,enabled:!0,headers:{Authorization:Kc(),[zy]:`{env:${Ky}}`}}),mode:420}),codex:cle({file:()=>Yc(".codex","config.toml"),lines:()=>[`[mcp_servers."${Ga}"]`,`url = ${JSON.stringify(zc)}`,`[mcp_servers."${Ga}".http_headers]`,`Authorization = ${JSON.stringify(Kc())}`,`[mcp_servers."${Ga}".env_http_headers]`,`${JSON.stringify(zy)} = ${JSON.stringify(Ky)}`]}),"qwen-code":Qd({file:()=>Yc(".qwen","settings.json"),entry:()=>({httpUrl:zc,headers:{Authorization:Kc()},trust:!0})}),cursor:Qd({file:()=>Yc(".cursor","mcp.json"),entry:()=>({url:zc,headers:{Authorization:Kc()}})}),copilot:Qd({file:()=>Yc(".copilot","mcp-config.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc()}})}),kimi:Qd({file:()=>Yc(".kimi-code","mcp.json"),entry:()=>({url:zc,headers:{Authorization:Kc()}})}),droid:Qd({file:()=>Yc(".factory","mcp.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),crush:Qd({file:()=>Yc(".config","crush","crush.json"),keyPath:["mcp"],entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),grok:cle({file:()=>Yc(".grok","config.toml"),lines:()=>[`[mcp_servers."${Ga}"]`,`url = ${JSON.stringify(zc)}`,"enabled = true",`[mcp_servers."${Ga}".headers]`,`Authorization = ${JSON.stringify(Kc())}`,`${JSON.stringify(zy)} = ${JSON.stringify(`\${${Ky}}`)}`]})},Yy=Object.keys(dle),DR=null});function mle(t,e){t.on("getStatusState",()=>{t.emit("statusState",qc())}),t.on("getNotificationState",()=>{t.emit("notificationState",TF())}),t.on("getLocalSites",async n=>{if(typeof n=="function")try{n({sites:await TR()})}catch(r){n({error:r.message})}}),t.on("startProxySession",(n,r)=>{if(!n)return;let i=kR(n);typeof r=="function"&&r(i?{ok:!0,sessionId:i}:{error:"bad-port"})}),t.on("endProxySession",(n,r)=>{n&&(PR(n),typeof r=="function"&&r({ok:!0}))}),nle(t),t.on("requestUpdate",async()=>{let{pushUiEvent:n}=await Promise.resolve().then(()=>(ns(),HL));n("updating",{}),Aa("update")}),t.on("requestRestart",()=>Aa("restart")),t.on("clearStatus",n=>{if(!n)return;cE(n)&&(nt(null,"statusCleared",n),nt(null,"notificationCleared",n))}),t.on("clearNotification",n=>{if(!n)return;cE(n)&&(nt(null,"notificationCleared",n),nt(null,"statusCleared",n))}),t.on("getVapidKey",n=>n(cce())),t.on("pushSubscribe",n=>{let r=n?.type==="expo"?n.token:n?.endpoint;r&&(oce(t.id,r),nce(n,t.id,t.data?.auth?.deviceId??t.handshake?.auth?.deviceId))}),t.on("pushUnsubscribe",n=>{n&&ice(n)}),t.on("visibilityChange",n=>rce(t.id,n)),t.on("setArtifactEnabled",async({enabled:n}={},r)=>{let i=ple(n);r?.({success:!0,enabled:i,clients:Yy});let{broadcastServerInfo:s}=await Promise.resolve().then(()=>(Ha(),c2));s()}),t.on("getVoiceConfig",n=>{n?.({success:!0,voiceConfig:Ra().voiceConfig||null})}),t.on("setVoiceConfig",async({voiceConfig:n}={},r)=>{let i=bd({voiceConfig:n});r?.({success:!0,voiceConfig:i?.voiceConfig||null});let{broadcastServerInfo:s}=await Promise.resolve().then(()=>(Ha(),c2));s()}),t.on("getAutoStartStatus",n=>{if(!Uc())return n({success:!1,error:"Not in Codespaces"});let r=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();n({success:!0,...ine(r)})}),t.on("setAutoStart",({enabled:n},r)=>{if(!Uc())return r({success:!1,error:"Not in Codespaces"});let i=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();r(sne(i,n))})}var gle=ae(()=>{xR();Fs();UA();Ic();Lq();n2();UR();Dg();es()});function mWe(t,e,n,r){let i=He.default.existsSync(t)?He.default.readFileSync(t,"utf8"):"";i=i.replace(new RegExp(`${BR(e)}[\\s\\S]*?${BR(n)}\\n?`,"g"),""),i.length&&!i.endsWith(`
351
+ `,"utf8")},disable(){let a=t();qo.default.existsSync(a)&&qo.default.writeFileSync(a,o(a),"utf8")},isEnabled(){let a=t();return qo.default.existsSync(a)&&qo.default.readFileSync(a,"utf8").includes(n)}}}function tw(){if(DR===null){let t=Ra().artifactEnabled;DR=t===void 0?Pl.DEFAULT_ENABLED:!!t}return DR}function d3e(t,e){let n=dle[t];if(n)try{e?n.enable():n.disable()}catch(r){ule.warn(`${e?"enable":"disable"} ${t} failed: ${r.message}`)}}function fle(t){for(let e of Yy)d3e(e,t)}function ple(t){let e=!!t;return bd({artifactEnabled:e}),DR=e,fle(e),ule.info(`artifact MCP ${e?"enabled":"disabled"} for ${Yy.join(", ")}`),e}function hle(){let t=tw();return fle(t),t}var qo,LR,lle,ule,zc,Ga,Kc,zy,Ky,Yc,a2,dle,Yy,DR,UR=ae(()=>{qo=ce(require("fs"),1),LR=ce(require("path"),1),lle=ce(require("os"),1);Lt();r2();s2();Dg();So();tt();ule=Se("mcp"),zc=`http://127.0.0.1:${Ts}${Pl.PATH}`,Ga=Pl.SERVER_NAME,Kc=()=>`Bearer ${i2()}`,zy=Wy.HEADER,Ky="NINE_REMOTE_SESSION_ID",Yc=(...t)=>LR.default.join(lle.default.homedir(),...t);a2=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");dle={claude:Qd({file:()=>Yc(".claude.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),opencode:Qd({file:()=>Yc(".config","opencode","opencode.json"),keyPath:t=>t?.mcp?.servers?["mcp","servers"]:["mcp"],entry:()=>({type:"remote",url:zc,enabled:!0,headers:{Authorization:Kc(),[zy]:`{env:${Ky}}`}}),mode:420}),codex:cle({file:()=>Yc(".codex","config.toml"),lines:()=>[`[mcp_servers."${Ga}"]`,`url = ${JSON.stringify(zc)}`,`[mcp_servers."${Ga}".http_headers]`,`Authorization = ${JSON.stringify(Kc())}`,`[mcp_servers."${Ga}".env_http_headers]`,`${JSON.stringify(zy)} = ${JSON.stringify(Ky)}`]}),"qwen-code":Qd({file:()=>Yc(".qwen","settings.json"),entry:()=>({httpUrl:zc,headers:{Authorization:Kc()},trust:!0})}),cursor:Qd({file:()=>Yc(".cursor","mcp.json"),entry:()=>({url:zc,headers:{Authorization:Kc()}})}),copilot:Qd({file:()=>Yc(".copilot","mcp-config.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc()}})}),kimi:Qd({file:()=>Yc(".kimi-code","mcp.json"),entry:()=>({url:zc,headers:{Authorization:Kc()}})}),droid:Qd({file:()=>Yc(".factory","mcp.json"),entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),crush:Qd({file:()=>Yc(".config","crush","crush.json"),keyPath:["mcp"],entry:()=>({type:"http",url:zc,headers:{Authorization:Kc(),[zy]:`\${${Ky}}`}})}),grok:cle({file:()=>Yc(".grok","config.toml"),lines:()=>[`[mcp_servers."${Ga}"]`,`url = ${JSON.stringify(zc)}`,"enabled = true",`[mcp_servers."${Ga}".headers]`,`Authorization = ${JSON.stringify(Kc())}`,`${JSON.stringify(zy)} = ${JSON.stringify(`\${${Ky}}`)}`]})},Yy=Object.keys(dle),DR=null});function mle(t,e){t.on("getStatusState",()=>{t.emit("statusState",qc())}),t.on("getNotificationState",()=>{t.emit("notificationState",TF())}),t.on("getLocalSites",async n=>{if(typeof n=="function")try{n({sites:await TR()})}catch(r){n({error:r.message})}}),t.on("startProxySession",(n,r)=>{if(!n)return;let i=kR(n);typeof r=="function"&&r(i?{ok:!0,sessionId:i}:{error:"bad-port"})}),t.on("endProxySession",(n,r)=>{n&&(PR(n),typeof r=="function"&&r({ok:!0}))}),nle(t),t.on("requestUpdate",async()=>{let{pushUiEvent:n}=await Promise.resolve().then(()=>(ns(),HL));n("updating",{}),Aa("update")}),t.on("requestRestart",()=>Aa("restart")),t.on("clearStatus",n=>{if(!n)return;cE(n)&&(nt(null,"statusCleared",n),nt(null,"notificationCleared",n))}),t.on("clearNotification",n=>{if(!n)return;cE(n)&&(nt(null,"notificationCleared",n),nt(null,"statusCleared",n))}),t.on("getVapidKey",n=>n(cce())),t.on("pushSubscribe",n=>{let r=n?.type==="expo"?n.token:n?.endpoint;r&&(oce(t.id,r),nce(n,t.id,t.data?.auth?.deviceId??t.handshake?.auth?.deviceId))}),t.on("pushUnsubscribe",n=>{n&&ice(n)}),t.on("visibilityChange",n=>rce(t.id,n)),t.on("setArtifactEnabled",async({enabled:n}={},r)=>{let i=ple(n);r?.({success:!0,enabled:i,clients:Yy});let{broadcastServerInfo:s}=await Promise.resolve().then(()=>(Ha(),c2));s()}),t.on("getVoiceConfig",n=>{n?.({success:!0,voiceConfig:Ra().voiceConfig||null})}),t.on("setVoiceConfig",async({voiceConfig:n}={},r)=>{let i=bd({voiceConfig:n});r?.({success:!0,voiceConfig:i?.voiceConfig||null});let{broadcastServerInfo:s}=await Promise.resolve().then(()=>(Ha(),c2));s()}),t.on("getAutoStartStatus",n=>{if(!Uc())return n({success:!1,error:"Not in Codespaces"});let r=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();n({success:!0,...ine(r)})}),t.on("setAutoStart",({enabled:n},r)=>{if(!Uc())return r({success:!1,error:"Not in Codespaces"});let i=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();r(sne(i,n))})}var gle=ae(()=>{xR();Fs();UA();Ic();Lq();n2();UR();Dg();es()});function m3e(t,e,n,r){let i=He.default.existsSync(t)?He.default.readFileSync(t,"utf8"):"";i=i.replace(new RegExp(`${BR(e)}[\\s\\S]*?${BR(n)}\\n?`,"g"),""),i.length&&!i.endsWith(`
352
352
  `)&&(i+=`
353
353
  `),i+=`${r}
354
- `;let s=pr.default.dirname(t);He.default.existsSync(s)||He.default.mkdirSync(s,{recursive:!0}),He.default.writeFileSync(t,i,"utf8")}function gWe(t,e,n){if(!He.default.existsSync(t))return;let r=He.default.readFileSync(t,"utf8");He.default.writeFileSync(t,r.replace(new RegExp(`${BR(e)}[\\s\\S]*?${BR(n)}\\n?`,"g"),""),"utf8")}function Or(t){try{if(He.default.existsSync(t))return JSON.parse(He.default.readFileSync(t,"utf8"))}catch{}return{}}function fs(t,e){xn(t,e,{mode:420})}function ble(t){let e={},n=t.env||{};for(let r of Object.keys(Bv))e[r]=n[r]??null;fs(fWe,e),t.env={...n,...Bv}}function Ch(t,e,n,{matchers:r={},extra:i,sessionId:s=!1}={}){let o=(l,u)=>({hooks:[{type:"command",command:Rh(u,t,{sessionId:s}),timeout:n($R)}],...r[l]!=null?{matcher:r[l]}:{}}),a=l=>l?.hooks?.some(u=>typeof u.command=="string"&&u.command.includes(`&tool=${t}`)),c=l=>l?.hooks?.some(u=>typeof u.command=="string"&&u.command.includes(`&tool=${t}`)&&(!s||u.command.includes("&csid=")));return{enable(l){let u=Or(l),d={...u.hooks||{}};for(let[f,m]of Object.entries(e))d[f]=[...(d[f]||[]).filter(g=>!a(g)),o(f,m)];return u.hooks=d,i&&i(u),fs(l,u),{success:!0}},disable(l){let u=Or(l);if(u.hooks){for(let d of Object.keys(e))u.hooks[d]=(u.hooks[d]||[]).filter(f=>!a(f)),u.hooks[d].length===0&&delete u.hooks[d];Object.keys(u.hooks).length===0&&delete u.hooks}return i&&i(u),fs(l,u),{success:!0}},isEnabled(l){let u=Or(l);return Object.keys(e).every(d=>(u.hooks?.[d]||[]).some(c))}}}function yWe(t,e,{extra:n}={}){let r=s=>typeof s?.command=="string"&&s.command.includes(`&tool=${t}`);return{enable(s){let o=Or(s),a={...o.hooks||{}};for(let[c,l]of Object.entries(e))a[c]=[...(a[c]||[]).filter(u=>!r(u)),{command:Rh(l,t)}];return o.hooks=a,n&&n(o),fs(s,o),{success:!0}},disable(s){let o=Or(s);if(o.hooks){for(let a of Object.keys(e))o.hooks[a]=(o.hooks[a]||[]).filter(c=>!r(c)),o.hooks[a].length===0&&delete o.hooks[a];Object.keys(o.hooks).length===0&&delete o.hooks}return n&&n(o),fs(s,o),{success:!0}},isEnabled(s){let o=Or(s);return Object.keys(e).every(a=>(o.hooks?.[a]||[]).some(r))}}}function _We(t,e,n){return{enable(i){let s=Or(i),o={};for(let[a,c]of Object.entries(n))o[a]=[{type:"command",command:Rh(c,t),timeout:u2($R)}];return s[e]=o,fs(i,s),{success:!0}},disable(i){let s=Or(i);return delete s[e],fs(i,s),{success:!0}},isEnabled(i){return!!Or(i)[e]}}}function vWe(t,e,{name:n,description:r}={}){let i=o=>typeof o?.command=="string"&&o.command.includes(`&tool=${t}`);return{enable(o){let a=Or(o);a.name=a.name||n||"9remote",a.description=a.description||r||`9Remote hooks for ${t} CLI.`,Array.isArray(a.tools)||(a.tools=["*"]);let c={...a.hooks||{}};for(let[l,u]of Object.entries(e))c[l]=[...(c[l]||[]).filter(d=>!i(d)),{command:Rh(u,t),timeout_ms:$R}];return a.hooks=c,fs(o,a),{success:!0}},disable(o){if(!He.default.existsSync(o))return{success:!0};let a=Or(o);if(a.hooks){for(let c of Object.keys(e))a.hooks[c]=(a.hooks[c]||[]).filter(l=>!i(l)),a.hooks[c].length===0&&delete a.hooks[c];Object.keys(a.hooks).length===0&&delete a.hooks}return fs(o,a),{success:!0}},isEnabled(o){let a=Or(o);return Object.keys(e).every(c=>(a.hooks?.[c]||[]).some(i))}}}function yle(t,{begin:e,end:n,items:r}){let i=()=>[e,"hooks:",...r.map(({event:o,type:a})=>` ${o}:
355
- - command: ${hWe(Rh(a,t))}
354
+ `;let s=pr.default.dirname(t);He.default.existsSync(s)||He.default.mkdirSync(s,{recursive:!0}),He.default.writeFileSync(t,i,"utf8")}function g3e(t,e,n){if(!He.default.existsSync(t))return;let r=He.default.readFileSync(t,"utf8");He.default.writeFileSync(t,r.replace(new RegExp(`${BR(e)}[\\s\\S]*?${BR(n)}\\n?`,"g"),""),"utf8")}function Or(t){try{if(He.default.existsSync(t))return JSON.parse(He.default.readFileSync(t,"utf8"))}catch{}return{}}function fs(t,e){xn(t,e,{mode:420})}function ble(t){let e={},n=t.env||{};for(let r of Object.keys(Bv))e[r]=n[r]??null;fs(f3e,e),t.env={...n,...Bv}}function Ch(t,e,n,{matchers:r={},extra:i,sessionId:s=!1}={}){let o=(l,u)=>({hooks:[{type:"command",command:Rh(u,t,{sessionId:s}),timeout:n($R)}],...r[l]!=null?{matcher:r[l]}:{}}),a=l=>l?.hooks?.some(u=>typeof u.command=="string"&&u.command.includes(`&tool=${t}`)),c=l=>l?.hooks?.some(u=>typeof u.command=="string"&&u.command.includes(`&tool=${t}`)&&(!s||u.command.includes("&csid=")));return{enable(l){let u=Or(l),d={...u.hooks||{}};for(let[f,m]of Object.entries(e))d[f]=[...(d[f]||[]).filter(g=>!a(g)),o(f,m)];return u.hooks=d,i&&i(u),fs(l,u),{success:!0}},disable(l){let u=Or(l);if(u.hooks){for(let d of Object.keys(e))u.hooks[d]=(u.hooks[d]||[]).filter(f=>!a(f)),u.hooks[d].length===0&&delete u.hooks[d];Object.keys(u.hooks).length===0&&delete u.hooks}return i&&i(u),fs(l,u),{success:!0}},isEnabled(l){let u=Or(l);return Object.keys(e).every(d=>(u.hooks?.[d]||[]).some(c))}}}function y3e(t,e,{extra:n}={}){let r=s=>typeof s?.command=="string"&&s.command.includes(`&tool=${t}`);return{enable(s){let o=Or(s),a={...o.hooks||{}};for(let[c,l]of Object.entries(e))a[c]=[...(a[c]||[]).filter(u=>!r(u)),{command:Rh(l,t)}];return o.hooks=a,n&&n(o),fs(s,o),{success:!0}},disable(s){let o=Or(s);if(o.hooks){for(let a of Object.keys(e))o.hooks[a]=(o.hooks[a]||[]).filter(c=>!r(c)),o.hooks[a].length===0&&delete o.hooks[a];Object.keys(o.hooks).length===0&&delete o.hooks}return n&&n(o),fs(s,o),{success:!0}},isEnabled(s){let o=Or(s);return Object.keys(e).every(a=>(o.hooks?.[a]||[]).some(r))}}}function _3e(t,e,n){return{enable(i){let s=Or(i),o={};for(let[a,c]of Object.entries(n))o[a]=[{type:"command",command:Rh(c,t),timeout:u2($R)}];return s[e]=o,fs(i,s),{success:!0}},disable(i){let s=Or(i);return delete s[e],fs(i,s),{success:!0}},isEnabled(i){return!!Or(i)[e]}}}function v3e(t,e,{name:n,description:r}={}){let i=o=>typeof o?.command=="string"&&o.command.includes(`&tool=${t}`);return{enable(o){let a=Or(o);a.name=a.name||n||"9remote",a.description=a.description||r||`9Remote hooks for ${t} CLI.`,Array.isArray(a.tools)||(a.tools=["*"]);let c={...a.hooks||{}};for(let[l,u]of Object.entries(e))c[l]=[...(c[l]||[]).filter(d=>!i(d)),{command:Rh(u,t),timeout_ms:$R}];return a.hooks=c,fs(o,a),{success:!0}},disable(o){if(!He.default.existsSync(o))return{success:!0};let a=Or(o);if(a.hooks){for(let c of Object.keys(e))a.hooks[c]=(a.hooks[c]||[]).filter(l=>!i(l)),a.hooks[c].length===0&&delete a.hooks[c];Object.keys(a.hooks).length===0&&delete a.hooks}return fs(o,a),{success:!0}},isEnabled(o){let a=Or(o);return Object.keys(e).every(c=>(a.hooks?.[c]||[]).some(i))}}}function yle(t,{begin:e,end:n,items:r}){let i=()=>[e,"hooks:",...r.map(({event:o,type:a})=>` ${o}:
355
+ - command: ${h3e(Rh(a,t))}
356
356
  timeout: 5`),n].join(`
357
- `);return{enable(s){return mWe(s,e,n,i()),{success:!0}},disable(s){return gWe(s,e,n),{success:!0}},isEnabled(s){return He.default.existsSync(s)&&He.default.readFileSync(s,"utf8").includes(e)}}}function wWe(t){return new Promise(e=>{let n;try{n=(0,wle.spawn)(t,["app-server"],{stdio:["pipe","pipe","ignore"]})}catch{return e([])}let r="",i=!1,s=a=>{if(!i){i=!0,clearTimeout(o);try{n.kill()}catch{}e(a)}},o=setTimeout(()=>s([]),EWe);n.on("error",()=>s([])),n.on("exit",()=>s([])),n.stdout.on("data",a=>{r+=a;let c;for(;(c=r.indexOf(`
357
+ `);return{enable(s){return m3e(s,e,n,i()),{success:!0}},disable(s){return g3e(s,e,n),{success:!0}},isEnabled(s){return He.default.existsSync(s)&&He.default.readFileSync(s,"utf8").includes(e)}}}function w3e(t){return new Promise(e=>{let n;try{n=(0,wle.spawn)(t,["app-server"],{stdio:["pipe","pipe","ignore"]})}catch{return e([])}let r="",i=!1,s=a=>{if(!i){i=!0,clearTimeout(o);try{n.kill()}catch{}e(a)}},o=setTimeout(()=>s([]),E3e);n.on("error",()=>s([])),n.on("exit",()=>s([])),n.stdout.on("data",a=>{r+=a;let c;for(;(c=r.indexOf(`
358
358
  `))>=0;){let l=r.slice(0,c);if(r=r.slice(c+1),!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(u.id===1){n.stdin.write(JSON.stringify({jsonrpc:"2.0",id:2,method:"hooks/list",params:{}})+`
359
359
  `);continue}if(u.id!==2)continue;let d=[];for(let f of u.result?.data||[])for(let m of f.hooks||[])m.currentHash&&d.push({key:m.key,hash:m.currentHash});s(d);return}}),n.stdin.write(JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{clientInfo:{name:"9remote",version:"1"}}})+`
360
- `)})}function Cle(t){let e=Or(t).hooks||{},n=[];for(let[r,i]of Object.entries(e))Array.isArray(i)&&i.forEach((s,o)=>{(s?.hooks||[]).forEach((a,c)=>{typeof a?.command=="string"&&n.push({key:`${t}:${Tle(r)}:${o}:${c}`,event:r,command:a.command})})});return n}function xWe(t,e){let r=(He.default.existsSync(t)?He.default.readFileSync(t,"utf8"):"").split(`
361
- `),i=[],s=new Map;for(let o of e)s.set(o.key,SWe(o.hash));for(let o=0;o<r.length;o++){let a=r[o].match(Ale),c=r[o+1]||"";if(!a||!/^\s*trusted_hash\s*=/.test(c)){i.push(r[o]);continue}let l=s.get(a.groups.key);if(l===void 0){i.push(r[o],c),o++;continue}s.delete(a.groups.key),i.push(r[o],`trusted_hash = "${l}"`),o++}for(let[o,a]of s)i.length&&i[i.length-1]!==""&&i.push(""),i.push(`[hooks.state."${o}"]`,`trusted_hash = "${a}"`);He.default.mkdirSync(pr.default.dirname(t),{recursive:!0}),He.default.writeFileSync(t,i.join(`
362
- `),"utf8")}async function bWe({run:t=wWe,bin:e=xle.codex}={}){let n=fn.codexHooks(),r=await t(e),i=new Map(r.map(c=>[c.key,c.hash])),s=Cle(n).filter(c=>c.command.includes("&tool=codex")),o=[],a=[];for(let c of s){let l=i.get(c.key);l?o.push({key:c.key,hash:l}):a.push(c.key)}return r.length?(xWe(fn.codex(),o),{entries:o,missing:a,skipped:!1}):{entries:[],missing:a,skipped:!0}}function TWe(t,e){if(!He.default.existsSync(t)||!e.size)return;let n=He.default.readFileSync(t,"utf8").split(`
360
+ `)})}function Cle(t){let e=Or(t).hooks||{},n=[];for(let[r,i]of Object.entries(e))Array.isArray(i)&&i.forEach((s,o)=>{(s?.hooks||[]).forEach((a,c)=>{typeof a?.command=="string"&&n.push({key:`${t}:${Tle(r)}:${o}:${c}`,event:r,command:a.command})})});return n}function x3e(t,e){let r=(He.default.existsSync(t)?He.default.readFileSync(t,"utf8"):"").split(`
361
+ `),i=[],s=new Map;for(let o of e)s.set(o.key,S3e(o.hash));for(let o=0;o<r.length;o++){let a=r[o].match(Ale),c=r[o+1]||"";if(!a||!/^\s*trusted_hash\s*=/.test(c)){i.push(r[o]);continue}let l=s.get(a.groups.key);if(l===void 0){i.push(r[o],c),o++;continue}s.delete(a.groups.key),i.push(r[o],`trusted_hash = "${l}"`),o++}for(let[o,a]of s)i.length&&i[i.length-1]!==""&&i.push(""),i.push(`[hooks.state."${o}"]`,`trusted_hash = "${a}"`);He.default.mkdirSync(pr.default.dirname(t),{recursive:!0}),He.default.writeFileSync(t,i.join(`
362
+ `),"utf8")}async function b3e({run:t=w3e,bin:e=xle.codex}={}){let n=fn.codexHooks(),r=await t(e),i=new Map(r.map(c=>[c.key,c.hash])),s=Cle(n).filter(c=>c.command.includes("&tool=codex")),o=[],a=[];for(let c of s){let l=i.get(c.key);l?o.push({key:c.key,hash:l}):a.push(c.key)}return r.length?(x3e(fn.codex(),o),{entries:o,missing:a,skipped:!1}):{entries:[],missing:a,skipped:!0}}function T3e(t,e){if(!He.default.existsSync(t)||!e.size)return;let n=He.default.readFileSync(t,"utf8").split(`
363
363
  `),r=[];for(let i=0;i<n.length;i++){let s=n[i].match(Ale),o=n[i+1]||"";if(!s||!/^\s*trusted_hash\s*=/.test(o)){r.push(n[i]);continue}if(!e.has(s.groups.key)){r.push(n[i],o),i++;continue}i++,r[r.length-1]===""&&r.pop()}He.default.writeFileSync(t,r.join(`
364
- `),"utf8")}function CWe(){let t=fn.codexScript(),e=fn.codex();if(He.default.existsSync(e)){let n=He.default.readFileSync(e,"utf8"),r=n.replace(AWe,""),i=r.match(_le);i&&!i[1].includes(t)?r=r.replace(_le,"$1"):i&&(r=r.replace(/^# 9Remote-saved: notify\s*=.*\n?/m,"")),r=r.replace(/^notify\s*=\s*\[[^\n]*9remote-notify\.sh[^\n]*\]\s*\n?/m,""),r!==n&&He.default.writeFileSync(e,r,"utf8")}if(He.default.existsSync(t))try{He.default.unlinkSync(t)}catch{}}function l2(t){return(t?.hooks||[]).some(e=>typeof e.command=="string"&&e.command.includes("&tool=codex"))}function IWe(t){return{hooks:[{type:"command",command:Rh(t,"codex",{sessionId:!0}),timeout:u2($R)}]}}function kWe(){return`// 9Remote OpenCode status plugin (auto-generated)
364
+ `),"utf8")}function C3e(){let t=fn.codexScript(),e=fn.codex();if(He.default.existsSync(e)){let n=He.default.readFileSync(e,"utf8"),r=n.replace(A3e,""),i=r.match(_le);i&&!i[1].includes(t)?r=r.replace(_le,"$1"):i&&(r=r.replace(/^# 9Remote-saved: notify\s*=.*\n?/m,"")),r=r.replace(/^notify\s*=\s*\[[^\n]*9remote-notify\.sh[^\n]*\]\s*\n?/m,""),r!==n&&He.default.writeFileSync(e,r,"utf8")}if(He.default.existsSync(t))try{He.default.unlinkSync(t)}catch{}}function l2(t){return(t?.hooks||[]).some(e=>typeof e.command=="string"&&e.command.includes("&tool=codex"))}function I3e(t){return{hooks:[{type:"command",command:Rh(t,"codex",{sessionId:!0}),timeout:u2($R)}]}}function k3e(){return`// 9Remote OpenCode status plugin (auto-generated)
365
365
  const base = ${JSON.stringify(qR)};
366
366
  const post = (type, conv) => {
367
367
  const sid = process.env.NINE_REMOTE_SESSION_ID || "";
@@ -394,7 +394,7 @@ export default function (${e}) {
394
394
  ${e}.on(${JSON.stringify(n)}, async () => post("working"));
395
395
  ${e}.on(${JSON.stringify(r)}, async () => post("done"));
396
396
  }
397
- `}function OWe(){return`// 9Remote omp status plugin (auto-generated)
397
+ `}function O3e(){return`// 9Remote omp status plugin (auto-generated)
398
398
  function post(type, csid) {
399
399
  const sid = process.env.NINE_REMOTE_SESSION_ID || "";
400
400
  if (!sid) return;
@@ -409,7 +409,7 @@ export default function (pi) {
409
409
  pi.on("agent_start", async (_e, ctx) => { if (ctx?.hasUI) post("working", csidOf(ctx)); });
410
410
  pi.on("agent_end", async (_e, ctx) => { if (ctx?.hasUI) post("done", csidOf(ctx)); });
411
411
  }
412
- `}function BWe(t){let e=UWe[t];if(!e)return{success:!1,error:"Unknown tool"};try{return t==="codex"||t==="opencode"||t==="amp"||t==="pi"||t==="omp"?e.enable():e.enable(fn[t]())}catch(n){return{success:!1,error:n.message}}}function qWe(t){let e=(process.env.PATH||"").split(pr.default.delimiter).filter(Boolean),n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return e.some(r=>n.some(i=>{try{return He.default.existsSync(pr.default.join(r,t+i))}catch{return!1}}))}function Rle(t){let e=xle[t];if(e&&qWe(e))return!0;let n=pWe[t]?.();return n?(Array.isArray(n)?n:[n]).some(r=>He.default.existsSync(r)):!1}function Ile(){let t={};for(let e of FWe)if(Rle(e))try{let n=BWe(e);t[e]=n.success&&!n.untrusted?.length}catch{t[e]=!1}return t}async function kle(){if(!Rle("codex"))return null;try{let{missing:t}=await bWe();return t.length&&console.warn(`\u26A0\uFE0F codex hooks written but not trusted: ${t.length} \u2014 run codex and trust them`),t.length?{untrusted:t.length}:{untrusted:0}}catch(t){return console.warn(`\u26A0\uFE0F codex hook trust failed: ${t.message}`),{error:t.message}}}function Ple(){let t=fn.claude(),e=Or(t);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let n=e.env||{};Object.keys(Bv).some(i=>n[i]!==Bv[i])&&(ble(e),fs(t,e))}var Ele,He,pr,wle,qR,Sle,fWe,Si,Zd,fn,xle,Rh,pWe,u2,$R,BR,hWe,FR,Tle,eCt,Ale,EWe,SWe,AWe,_le,RWe,PWe,MWe,NWe,DWe,LWe,UWe,FWe,Ole=ae(()=>{Ele=ce(require("os"),1),He=ce(require("fs"),1),pr=ce(require("path"),1),wle=require("child_process");Lt();So();Fc();qR=`http://localhost:${Ts}/api/notify`,Sle="nineRemoteNotify",fWe=pr.default.join(Oe.STATE,"claudeEnvBackup.json"),Si=(...t)=>pr.default.join(Ele.default.homedir(),...t),Zd=(t,...e)=>{let n=process.env[t];return n&&n.trim()?n.trim():Si(...e)},fn={claude:()=>Si(".claude","settings.json"),codex:()=>Si(".codex","config.toml"),codexHooks:()=>Si(".codex","hooks.json"),codexScript:()=>Si(".codex","9remote-notify.sh"),opencode:()=>Si(".config","opencode","plugin",`${Sle}.js`),grok:()=>pr.default.join(Zd("GROK_HOME",".grok"),"hooks","9remote.json"),cursor:()=>Si(".cursor","hooks.json"),antigravity:()=>Si(".gemini","config","hooks.json"),kiro:()=>pr.default.join(Zd("KIRO_HOME",".kiro"),"agents","9remote.json"),copilot:()=>pr.default.join(Zd("COPILOT_HOME",".copilot"),"config.json"),codebuddy:()=>pr.default.join(Zd("CODEBUDDY_CONFIG_DIR",".codebuddy"),"settings.json"),factory:()=>Si(".factory","settings.json"),qoder:()=>pr.default.join(Zd("QODER_CONFIG_DIR",".qoder"),"settings.json"),rovodev:()=>Si(".rovodev","config.yml"),hermes:()=>pr.default.join(Zd("HERMES_HOME",".hermes"),"config.yaml"),amp:()=>Si(".config","amp","plugins","9remote.ts"),devin:()=>Si(".config","devin","config.json"),pi:()=>pr.default.join(Zd("PI_CODING_AGENT_DIR",".pi","agent"),"extensions","9remote.ts"),omp:()=>pr.default.join(Zd("PI_CODING_AGENT_DIR",".omp","agent"),"extensions","9remote.ts")},xle={claude:"claude",codex:"codex",opencode:"opencode",grok:"grok",cursor:"cursor-agent",antigravity:"agy",kiro:"kiro-cli",copilot:"copilot",codebuddy:"codebuddy",factory:"droid",qoder:"qodercli",rovodev:"acli",hermes:"hermes",amp:"amp",pi:"pi",omp:"omp",devin:"devin"},Rh=(t,e,{sessionId:n=!1}={})=>{let r=n?mF(e)[0]:null;return`${r?`csid=$(cat 2>/dev/null | sed -n 's/.*"${r}" *: *"\\([^"]*\\)".*/\\1/p'); `:""}command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${qR}?type=${t}&sessionId=$NINE_REMOTE_SESSION_ID${r?"&csid=$csid":""}&tool=${e}" > /dev/null 2>&1 & true`},pWe={claude:()=>Si(".claude"),codex:()=>Si(".codex"),opencode:()=>[Si(".config","opencode"),Si(".opencode")]},u2=t=>Math.ceil(t/1e3),$R=5e3,BR=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),hWe=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;FR={UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},Tle=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),eCt=Object.fromEntries(Object.keys(FR).map(t=>[Tle(t),t])),Ale=/^\[hooks\.state\."(?<key>[^"]+)"\]$/m,EWe=15e3;SWe=t=>/^sha256:/.test(t)?t:`sha256:${t}`;AWe=/# 9Remote notification\nnotify\s*=.*\n?/g,_le=/^# 9Remote-saved: (notify\s*=.*)$/m;RWe={enable(){let t=fn.codexHooks(),e=Or(t),n={...e.hooks||{}};for(let[r,i]of Object.entries(FR))n[r]=[...(n[r]||[]).filter(s=>!l2(s)),IWe(i)];return e.hooks=n,fs(t,e),CWe(),{success:!0}},disable(){let t=fn.codexHooks(),e=new Set(Cle(t).filter(n=>n.command.includes("&tool=codex")).map(n=>n.key));if(He.default.existsSync(t)){let n=Or(t);if(n.hooks){for(let r of Object.keys(FR))n.hooks[r]=(n.hooks[r]||[]).filter(i=>!l2(i)),n.hooks[r].length===0&&delete n.hooks[r];Object.keys(n.hooks).length===0&&delete n.hooks}fs(t,n)}return TWe(fn.codex(),e),{success:!0}},isEnabled(){let t=Or(fn.codexHooks()).hooks||{};return Object.keys(FR).every(e=>(t[e]||[]).some(l2))}};PWe={enable(){let t=fn.opencode(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,kWe(),"utf8"),{success:!0}},disable(){let t=fn.opencode();return He.default.existsSync(t)&&He.default.unlinkSync(t),{success:!0}},isEnabled(){let t=fn.opencode();return He.default.existsSync(t)&&He.default.readFileSync(t,"utf8").includes("&sessionID=")}};MWe="# 9remote hooks begin",NWe="# 9remote hooks end",DWe=" # 9remote hooks begin",LWe=" # 9remote hooks end",UWe={claude:Ch("claude",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked",Notification:"blocked"},t=>t,{matchers:{Notification:"permission_prompt"},extra:ble,sessionId:!0}),devin:Ch("devin",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},t=>t,{sessionId:!0}),codex:RWe,opencode:PWe,grok:Ch("grok",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",Notification:"blocked"},u2),cursor:yWe("cursor",{stop:"done",beforeShellExecution:"blocked",beforeToolCall:"working"},{extra:t=>{t.version=t.version||1}}),antigravity:_We("antigravity","9remote",{UserPromptSubmit:"working",PreToolUse:"working",Stop:"done",Notification:"blocked"}),kiro:vWe("kiro",{UserPromptSubmit:"working",PostToolUse:"working",preToolUse:"blocked",stop:"done"}),copilot:Ch("copilot",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),codebuddy:Ch("codebuddy",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),factory:Ch("factory",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),qoder:Ch("qoder",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),rovodev:yle("rovodev",{begin:DWe,end:LWe,items:[{event:"on_complete",type:"done"},{event:"on_error",type:"done"},{event:"on_tool_permission",type:"blocked"},{event:"on_message",type:"working"},{event:"on_tool_start",type:"working"}]}),hermes:(()=>{let t=yle("hermes",{begin:MWe,end:NWe,items:[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}]}),e=()=>pr.default.join(pr.default.dirname(fn.hermes()),"shell-hooks-allowlist.json");return{enable:()=>{let n=t.enable(fn.hermes()),r=Or(e()),i=(r.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes")));return r.approvals=[...i,...[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}].map(({event:s,type:o})=>({event:s,command:Rh(o,"hermes"),approved_at:"2020-01-01T00:00:00Z"}))],fs(e(),r),n},disable:()=>{let n=t.disable(fn.hermes()),r=e();if(He.default.existsSync(r)){let i=Or(r);i.approvals=(i.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes"))),i.approvals.length?fs(r,i):He.default.unlinkSync(r)}return n},isEnabled:()=>t.isEnabled(fn.hermes())}})(),amp:{enable(){let t=fn.amp(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,vle("amp","amp","agent.start","agent.end"),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.amp())&&He.default.unlinkSync(fn.amp()),{success:!0}},isEnabled(){return He.default.existsSync(fn.amp())}},pi:{enable(){let t=fn.pi(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,vle("pi","pi","agent_start","agent_end"),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.pi())&&He.default.unlinkSync(fn.pi()),{success:!0}},isEnabled(){return He.default.existsSync(fn.pi())}},omp:{enable(){let t=fn.omp(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,OWe(),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.omp())&&He.default.unlinkSync(fn.omp()),{success:!0}},isEnabled(){return He.default.existsSync(fn.omp())}}},FWe=lK});var d2=ae(()=>{Fs()});var c2={};yr(c2,{broadcastAiStatus:()=>iw,broadcastServerInfo:()=>WR,initializeTerminal:()=>m2,listSessionRoots:()=>_u,matchWorkspacePath:()=>Ble,registerManagedSession:()=>h2,setConnectCheckHandler:()=>g2,setupTerminalHandlers:()=>y2,setupTerminalSocket:()=>nf});async function jWe(t,e){if(!One(e))return;let r=(await Rd().catch(()=>null))?.find(s=>s.id===e);Pne(e,r?.foregroundProcess)?.state==="idle"&&(nt(t,"statusChange",{sessionId:e,state:"idle",tool:null,conversationId:null}),nt(t,"statusState",qc()))}function WWe(t,e){let n=(HR.get(t)||"")+e,r=null;Mle.lastIndex=0;for(let o;o=Mle.exec(n);)r=o[1];if(r){let o=mne(r);o&&os(t,o)}let i=n.lastIndexOf("\x1B]"),s=i===-1?"":n.slice(i);s&&s.length<=GWe&&!s.slice(3).includes("\x07")&&!s.includes("\x1B\\")?HR.set(t,s):HR.delete(t)}function Dle(){let t=(Nle||Promise.resolve()).catch(()=>{}).then(()=>VWe());return Nle=t.catch(()=>{}),t}async function VWe(){let t=await Rd(),e=new Map(t.map(r=>[r.id,r])),n=nC();for(let r of t)if(!n[r.id])try{await Id(r.id)}catch{}Wr.clear();for(let[r,i]of Object.entries(n)){let s=e.get(r);Wr.set(r,{daemon:!0,name:i.name,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,workspacePath:i.workspacePath??nw[r]??null,lastCols:i.cols??null,lastRows:i.rows??null,needsRespawn:!s,agent:i.agent||null}),i.agent&&os(r,i.agent),xF(r,i)}ii(Wr)}function zWe(t){!ef||!t||rw.has(t)||rw.set(t,setTimeout(()=>{rw.delete(t),jC(ef,Wr,t).catch(()=>{})},NQ))}function f2(){let{assignments:t,created:e}=tre({sessions:Wr,workspaces:[...tf.values()],sessionWorkspaces:kh});if(Object.keys(t).length){for(let n of e)tf.set(n.id,n);for(let[n,r]of Object.entries(t)){kh[n]=r;let i=Wr.get(n);i&&!i.workspacePath&&(i.workspacePath=tf.get(r)?.path||null)}my(tf,kh,jR),ii(Wr),console.log(Fle(`\u{1F4C1} Grouped ${Object.keys(t).length} loose terminal(s)`+(e.length?` into ${e.length} new workspace(s)`:"")))}}function _u(){return[...Wr.entries()].map(([t,e])=>({id:t,name:e.name,workspacePath:e.workspacePath||null,cwd:e.cwd||null}))}function Ble(t,e){let n=e?(0,Ih.resolve)(e):"";if(!n)return null;let r=null,i=null,s=null;for(let o of t||[]){if(!o?.path)continue;let a=(0,Ih.resolve)(o.path);n===a?r=o:n.startsWith(a+"/")&&(!i||a.length>(0,Ih.resolve)(i.path).length)?i=o:a.startsWith(n+"/")&&(!s||a.length<(0,Ih.resolve)(s.path).length)&&(s=o)}return r||i||s||null}function h2({sessionId:t,name:e,autoNamed:n=!0,cwd:r=null,workspacePath:i=null,shellId:s=null,shellLabel:o=null,agent:a=null}){let c=Ble([...tf.values()],i||r)||null;return Wr.set(t,{daemon:!0,name:e,autoNamed:n,createdAt:Date.now(),cwd:r||c?.path||null,workspacePath:c?.path||null,shellId:s,shellLabel:o,agent:a}),c&&(kh[t]=c.id,my(tf,kh,jR)),ii(Wr),nt(null,"sessionsChanged"),{success:!0,sessionId:t,workspacePath:c?.path||null}}async function m2(){let t=Vne();if(!t){let r=nC(),i=Wne();t=ere(i,r);let s=new Map(t.workspaces.map(c=>[c.id,c]));if(my(s,t.sessionWorkspaces,t.sessionOrder),nw=t.sessionPaths||{},Object.keys(nw).length){for(let[c,l]of Object.entries(nw))r[c]&&(r[c].workspacePath=l);jne(r)}let o=(i.groups||[]).filter(c=>t.workspaces.some(l=>l.id===c.id)).length,a=(i.groups||[]).length-o;(t.workspaces.length||a)&&console.log(Fle(`\u{1F4C1} Migrated ${t.workspaces.length} workspace(s) from terminal groups`+(a?`, dropped ${a} empty group(s)`:"")))}for(let r of t.workspaces)tf.set(r.id,r);Object.assign(kh,t.sessionWorkspaces),jR.push(...t.sessionOrder),Ane(()=>ii(Wr)),Nne(zWe);try{Ple()}catch{}try{Ile()}catch{}kle().catch(()=>{});try{hle()}catch{}if(p2==="daemon")if(!await iU())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await Dle(),f2(),Fp("connected",()=>{Dle().then(f2).catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=Hne(),n=nC();for(let r of e){let i=n[r]||{};Wr.set(r,{pty:null,name:i.name||`Terminal ${Wr.size+1}`,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt||Date.now(),cwd:i.cwd,workspacePath:i.workspacePath??nw[r]??null,shellId:i.shellId,buffer:[],needsRestore:!0}),xF(r,i),console.log(`\u{1F504} Found saved session: ${r}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`),f2()}function nf(t,e){ef=t,p2==="daemon"&&(Fp("output",({sessionId:i,enc:s,data:o,replay:a})=>{a!==!0&&(JA(i),YA(i));let c=s==="b64"?Buffer.from(o,"base64"):Buffer.from(o||"");c.length>Pa&&(GR++,(GR===1||GR%500===0)&&Ule.info(`[slice] chunk ${c.length>>10}KB \u2192 ${Math.ceil(c.length/Pa)} events (total sliced: ${GR})`)),s==="b64"&&WWe(i,c.toString("utf8"));for(let l=0;l<c.length||l===0;l+=Pa){let u=c.subarray(l,l+Pa),d=a===!0?NE(i):Ase(i);a!==!0&&Cse(i,d,u),nt(t,"output",{sessionId:i,enc:"bin",data:u,replay:a===!0,seq:d})}}),Bne(i=>nt(t,"statusState",qc())),Une(()=>nt(t,"statusState",qc())),Fp("cwdChange",({sessionId:i,cwd:s})=>{let o=Wr.get(i);o&&s&&o.cwd!==s&&(o.cwd=s,ii(Wr)),nt(t,"cwdChange",{sessionId:i,cwd:s})}),Fp("processChange",({sessionId:i,process:s})=>{let o=kne(i,s);if(o?.state==="pendingShell"){setTimeout(()=>jWe(t,i),HWe);return}o?.state==="idle"&&(nt(t,"statusChange",{sessionId:i,state:"idle",tool:null,conversationId:null}),nt(t,"statusState",qc()))}),Fp("sessionClosed",i=>{Wr.delete(i),Iy(i),fy(i),HR.delete(i);let s=rw.get(i);s&&(clearTimeout(s),rw.delete(i)),AF(i),nt(t,"sessionClosed",i),nt(t,"notificationCleared",i)}));let n=()=>({version:$We,remoteAvailable:Mp(),mobileAvailable:Jte(),daemonMode:p2==="daemon"&&Pn(),platform:process.platform,updateAvailable:k0(),canSelfUpdate:!0,caps:{joinSessionSize:!0,artifact:!0},artifactEnabled:tw(),voiceConfig:Ra().voiceConfig||null,mcpClients:Yy,...ene()}),r=()=>{let i=n();for(let s of t.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i)};xL(r),nf._buildServerInfo=n,nf._emitServerInfo=r}function WR(){nf._emitServerInfo?.()}function iw(t,e,n,r=null){if(!ef)return null;if(e==="done")return XA(t,()=>{let a=r?.sessionId||r?.threadId||ss(t)?.id||null,c=Hd(t),l=nh({type:e,sessionId:t,tool:n});!l||l===c||(nt(ef,"statusChange",{sessionId:t,state:e,tool:n,conversationId:a}),nt(ef,"statusState",qc()))}),Hd(t);let i=r?.sessionId||r?.threadId||ss(t)?.id||null,s=Hd(t),o=nh({type:e,sessionId:t,tool:n});return!o||o===s||(nt(ef,"statusChange",{sessionId:t,state:e,tool:n,conversationId:i}),nt(ef,"statusState",qc())),o}function g2(t){qle=t}async function y2(t,e,n){Ule.info(`[diag] setupTerminalHandlers START id=${t.id} virtual=${!!t.defersWsAdapter}`),tne(),qle?.(),t.emit("srvCaps",{env2:1}),t.emit("serverInfo",nf._buildServerInfo?.()),Mse(t,e,Wr,tf,kh,jR),qse(t,Wr),mle(t,e),SA()&&await JZ(t,n).catch(r=>{console.error("\u274C Failed to setup remote handlers:",r.message)}),Qte(t),t.on("disconnect",()=>{sce(t.id),nne()})}var Ih,Lle,Ule,OCt,Fle,p2,$We,Mle,GWe,HWe,HR,Wr,tf,kh,jR,nw,Nle,rw,ef,GR,qle,Ha=ae(()=>{nM();Ih=require("path"),Lle=require("url");_i();xA();Zte();ns();UA();rC();nre();VC();$se();gle();Ole();UR();Dg();xR();d2();Fs();Fc();es();FB();ru();tt();Ule=Se("terminal"),OCt=(0,Ih.dirname)((0,Lle.fileURLToPath)(__importMetaUrl)),Fle=Lv.rgb(230,138,110),p2="daemon",$We="3.0.24",Mle=/\x1b\](?:0|2);([^\x07\x1b]*)(?:\x07|\x1b\\)/g,GWe=256,HWe=1500,HR=new Map;Wr=new Map,tf=new Map,kh={},jR=[],nw={},Nle=null;rw=new Map,ef=null;GR=0;qle=null});var sw=B((MCt,Wle)=>{"use strict";var KWe=require("path"),Xc="\\\\/",$le=`[^${Xc}]`,YWe=0,vu="\\.",XWe="\\+",JWe="\\?",VR="\\/",QWe="(?=.)",Gle="[^/]",_2=`(?:${VR}|$)`,Hle=`(?:^|${VR})`,v2=`${vu}{1,2}${_2}`,ZWe=`(?!${vu})`,e3e=`(?!${Hle}${v2})`,t3e=`(?!${vu}{0,1}${_2})`,n3e=`(?!${v2})`,r3e=`[^.${VR}]`,i3e=`${Gle}*?`,jle={DOT_LITERAL:vu,PLUS_LITERAL:XWe,QMARK_LITERAL:JWe,SLASH_LITERAL:VR,ONE_CHAR:QWe,QMARK:Gle,END_ANCHOR:_2,DOTS_SLASH:v2,NO_DOT:ZWe,NO_DOTS:e3e,NO_DOT_SLASH:t3e,NO_DOTS_SLASH:n3e,QMARK_NO_DOT:r3e,STAR:i3e,START_ANCHOR:Hle},s3e={...jle,SLASH_LITERAL:`[${Xc}]`,QMARK:$le,STAR:`${$le}*?`,DOTS_SLASH:`${vu}{1,2}(?:[${Xc}]|$)`,NO_DOT:`(?!${vu})`,NO_DOTS:`(?!(?:^|[${Xc}])${vu}{1,2}(?:[${Xc}]|$))`,NO_DOT_SLASH:`(?!${vu}{0,1}(?:[${Xc}]|$))`,NO_DOTS_SLASH:`(?!${vu}{1,2}(?:[${Xc}]|$))`,QMARK_NO_DOT:`[^.${Xc}]`,START_ANCHOR:`(?:^|[${Xc}])`,END_ANCHOR:`(?:[${Xc}]|$)`},o3e={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Wle.exports={DEFAULT_MAX_EXTGLOB_RECURSION:YWe,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:o3e,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:KWe.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?s3e:jle}}});var zR=B(ps=>{"use strict";var a3e=require("path"),c3e=process.platform==="win32",{REGEX_BACKSLASH:l3e,REGEX_REMOVE_BACKSLASH:u3e,REGEX_SPECIAL_CHARS:d3e,REGEX_SPECIAL_CHARS_GLOBAL:f3e}=sw();ps.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ps.hasRegexChars=t=>d3e.test(t);ps.isRegexChar=t=>t.length===1&&ps.hasRegexChars(t);ps.escapeRegex=t=>t.replace(f3e,"\\$1");ps.toPosixSlashes=t=>t.replace(l3e,"/");ps.removeBackslashes=t=>t.replace(u3e,e=>e==="\\"?"":e);ps.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};ps.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:c3e===!0||a3e.sep==="\\";ps.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?ps.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};ps.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};ps.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var Zle=B((DCt,Qle)=>{"use strict";var Vle=zR(),{CHAR_ASTERISK:E2,CHAR_AT:p3e,CHAR_BACKWARD_SLASH:ow,CHAR_COMMA:h3e,CHAR_DOT:w2,CHAR_EXCLAMATION_MARK:S2,CHAR_FORWARD_SLASH:Jle,CHAR_LEFT_CURLY_BRACE:x2,CHAR_LEFT_PARENTHESES:b2,CHAR_LEFT_SQUARE_BRACKET:m3e,CHAR_PLUS:g3e,CHAR_QUESTION_MARK:zle,CHAR_RIGHT_CURLY_BRACE:y3e,CHAR_RIGHT_PARENTHESES:Kle,CHAR_RIGHT_SQUARE_BRACKET:_3e}=sw(),Yle=t=>t===Jle||t===ow,Xle=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},v3e=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===!0||n.scanToEnd===!0,s=[],o=[],a=[],c=t,l=-1,u=0,d=0,f=!1,m=!1,g=!1,y=!1,w=!1,S=!1,T=!1,R=!1,C=!1,D=!1,$=0,G,V,L={value:"",depth:0,isGlob:!1},k=()=>l>=r,E=()=>c.charCodeAt(l+1),A=()=>(G=V,c.charCodeAt(++l));for(;l<r;){V=A();let X;if(V===ow){T=L.backslashes=!0,V=A(),V===x2&&(S=!0);continue}if(S===!0||V===x2){for($++;k()!==!0&&(V=A());){if(V===ow){T=L.backslashes=!0,A();continue}if(V===x2){$++;continue}if(S!==!0&&V===w2&&(V=A())===w2){if(f=L.isBrace=!0,g=L.isGlob=!0,D=!0,i===!0)continue;break}if(S!==!0&&V===h3e){if(f=L.isBrace=!0,g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===y3e&&($--,$===0)){S=!1,f=L.isBrace=!0,D=!0;break}}if(i===!0)continue;break}if(V===Jle){if(s.push(l),o.push(L),L={value:"",depth:0,isGlob:!1},D===!0)continue;if(G===w2&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(V===g3e||V===p3e||V===E2||V===zle||V===S2)===!0&&E()===b2){if(g=L.isGlob=!0,y=L.isExtglob=!0,D=!0,V===S2&&l===u&&(C=!0),i===!0){for(;k()!==!0&&(V=A());){if(V===ow){T=L.backslashes=!0,V=A();continue}if(V===Kle){g=L.isGlob=!0,D=!0;break}}continue}break}if(V===E2){if(G===E2&&(w=L.isGlobstar=!0),g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===zle){if(g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===m3e){for(;k()!==!0&&(X=A());){if(X===ow){T=L.backslashes=!0,A();continue}if(X===_3e){m=L.isBracket=!0,g=L.isGlob=!0,D=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&V===S2&&l===u){R=L.negated=!0,u++;continue}if(n.noparen!==!0&&V===b2){if(g=L.isGlob=!0,i===!0){for(;k()!==!0&&(V=A());){if(V===b2){T=L.backslashes=!0,V=A();continue}if(V===Kle){D=!0;break}}continue}break}if(g===!0){if(D=!0,i===!0)continue;break}}n.noext===!0&&(y=!1,g=!1);let M=c,I="",P="";u>0&&(I=c.slice(0,u),c=c.slice(u),d-=u),M&&g===!0&&d>0?(M=c.slice(0,d),P=c.slice(d)):g===!0?(M="",P=c):M=c,M&&M!==""&&M!=="/"&&M!==c&&Yle(M.charCodeAt(M.length-1))&&(M=M.slice(0,-1)),n.unescape===!0&&(P&&(P=Vle.removeBackslashes(P)),M&&T===!0&&(M=Vle.removeBackslashes(M)));let F={prefix:I,input:t,start:u,base:M,glob:P,isBrace:f,isBracket:m,isGlob:g,isExtglob:y,isGlobstar:w,negated:R,negatedExtglob:C};if(n.tokens===!0&&(F.maxDepth=0,Yle(V)||o.push(L),F.tokens=o),n.parts===!0||n.tokens===!0){let X;for(let N=0;N<s.length;N++){let b=X?X+1:u,q=s[N],pe=t.slice(b,q);n.tokens&&(N===0&&u!==0?(o[N].isPrefix=!0,o[N].value=I):o[N].value=pe,Xle(o[N]),F.maxDepth+=o[N].depth),(N!==0||pe!=="")&&a.push(pe),X=q}if(X&&X+1<t.length){let N=t.slice(X+1);a.push(N),n.tokens&&(o[o.length-1].value=N,Xle(o[o.length-1]),F.maxDepth+=o[o.length-1].depth)}F.slashes=s,F.parts=a}return F};Qle.exports=v3e});var iue=B((LCt,rue)=>{"use strict";var aw=sw(),xi=zR(),{MAX_LENGTH:KR,POSIX_REGEX_SOURCE:E3e,REGEX_NON_SPECIAL_CHARS:w3e,REGEX_SPECIAL_CHARS_BACKREF:S3e,REPLACEMENTS:eue}=aw,x3e=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>xi.escapeRegex(i)).join("..")}return n},Xy=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,tue=t=>{let e=[],n=0,r=0,i=0,s="",o=!1;for(let a of t){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},b3e=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},nue=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(b3e(e))return e.replace(/\\(.)/g,"$1")},T3e=t=>{let e=t.map(nue).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},T2=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=!1;for(let o=1;o<t.length;o++){let a=t[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},A3e=t=>{let e=0,n=[];for(;e<t.length;){let i=T2(t.slice(e),!1);if(!i||i.type!=="*")return;let s=tue(i.body).map(a=>a.trim());if(s.length!==1)return;let o=nue(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?xi.escapeRegex(n[0]):`[${n.map(i=>xi.escapeRegex(i)).join("")}]`}*`},C3e=t=>{let e=0,n=t.trim(),r=T2(n);for(;r;)e++,n=r.body.trim(),r=T2(n);return e},R3e=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:aw.DEFAULT_MAX_EXTGLOB_RECURSION,r=tue(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||T3e(r)))return{risky:!0};for(let i of r){let s=A3e(i);if(s)return{risky:!0,safeOutput:s};if(C3e(i)>n)return{risky:!0}}return{risky:!1}},A2=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=eue[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(KR,n.maxLength):KR,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",c=xi.isWindows(e),l=aw.globChars(c),u=aw.extglobChars(l),{DOT_LITERAL:d,PLUS_LITERAL:f,SLASH_LITERAL:m,ONE_CHAR:g,DOTS_SLASH:y,NO_DOT:w,NO_DOT_SLASH:S,NO_DOTS_SLASH:T,QMARK:R,QMARK_NO_DOT:C,STAR:D,START_ANCHOR:$}=l,G=U=>`(${a}(?:(?!${$}${U.dot?y:d}).)*?)`,V=n.dot?"":w,L=n.dot?R:C,k=n.bash===!0?G(n):D;n.capture&&(k=`(${k})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let E={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=xi.removePrefix(t,E),i=t.length;let A=[],M=[],I=[],P=s,F,X=()=>E.index===i-1,N=E.peek=(U=1)=>t[E.index+U],b=E.advance=()=>t[++E.index]||"",q=()=>t.slice(E.index+1),pe=(U="",K=0)=>{E.consumed+=U,E.index+=K},oe=U=>{E.output+=U.output!=null?U.output:U.value,pe(U.value)},J=()=>{let U=1;for(;N()==="!"&&(N(2)!=="("||N(3)==="?");)b(),E.start++,U++;return U%2===0?!1:(E.negated=!0,E.start++,!0)},ve=U=>{E[U]++,I.push(U)},we=U=>{E[U]--,I.pop()},xe=U=>{if(P.type==="globstar"){let K=E.braces>0&&(U.type==="comma"||U.type==="brace"),j=U.extglob===!0||A.length&&(U.type==="pipe"||U.type==="paren");U.type!=="slash"&&U.type!=="paren"&&!K&&!j&&(E.output=E.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=k,E.output+=P.output)}if(A.length&&U.type!=="paren"&&(A[A.length-1].inner+=U.value),(U.value||U.output)&&oe(U),P&&P.type==="text"&&U.type==="text"){P.value+=U.value,P.output=(P.output||"")+U.value;return}U.prev=P,o.push(U),P=U},lt=(U,K)=>{let j={...u[K],conditions:1,inner:""};j.prev=P,j.parens=E.parens,j.output=E.output,j.startIndex=E.index,j.tokensIndex=o.length;let Q=(n.capture?"(":"")+j.open;ve("parens"),xe({type:U,value:K,output:E.output?"":g}),xe({type:"paren",extglob:!0,value:b(),output:Q}),A.push(j)},Ue=U=>{let K=t.slice(U.startIndex,E.index+1),j=t.slice(U.startIndex+2,E.index),Q=R3e(j,n);if((U.type==="plus"||U.type==="star")&&Q.risky){let ie=Q.safeOutput?(U.output?"":g)+(n.capture?`(${Q.safeOutput})`:Q.safeOutput):void 0,ne=o[U.tokensIndex];ne.type="text",ne.value=K,ne.output=ie||xi.escapeRegex(K);for(let re=U.tokensIndex+1;re<o.length;re++)o[re].value="",o[re].output="",delete o[re].suffix;E.output=U.output+ne.output,E.backtrack=!0,xe({type:"paren",extglob:!0,value:F,output:""}),we("parens");return}let Z=U.close+(n.capture?")":""),ee;if(U.type==="negate"){let ie=k;if(U.inner&&U.inner.length>1&&U.inner.includes("/")&&(ie=G(n)),(ie!==k||X()||/^\)+$/.test(q()))&&(Z=U.close=`)$))${ie}`),U.inner.includes("*")&&(ee=q())&&/^\.[^\\/.]+$/.test(ee)){let ne=A2(ee,{...e,fastpaths:!1}).output;Z=U.close=`)${ne})${ie})`}U.prev.type==="bos"&&(E.negatedExtglob=!0)}xe({type:"paren",extglob:!0,value:F,output:Z}),we("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let U=!1,K=t.replace(S3e,(j,Q,Z,ee,ie,ne)=>ee==="\\"?(U=!0,j):ee==="?"?Q?Q+ee+(ie?R.repeat(ie.length):""):ne===0?L+(ie?R.repeat(ie.length):""):R.repeat(Z.length):ee==="."?d.repeat(Z.length):ee==="*"?Q?Q+ee+(ie?k:""):k:Q?j:`\\${j}`);return U===!0&&(n.unescape===!0?K=K.replace(/\\/g,""):K=K.replace(/\\+/g,j=>j.length%2===0?"\\\\":j?"\\":"")),K===t&&n.contains===!0?(E.output=t,E):(E.output=xi.wrapOutput(K,E,e),E)}for(;!X();){if(F=b(),F==="\0")continue;if(F==="\\"){let j=N();if(j==="/"&&n.bash!==!0||j==="."||j===";")continue;if(!j){F+="\\",xe({type:"text",value:F});continue}let Q=/^\\+/.exec(q()),Z=0;if(Q&&Q[0].length>2&&(Z=Q[0].length,E.index+=Z,Z%2!==0&&(F+="\\")),n.unescape===!0?F=b():F+=b(),E.brackets===0){xe({type:"text",value:F});continue}}if(E.brackets>0&&(F!=="]"||P.value==="["||P.value==="[^")){if(n.posix!==!1&&F===":"){let j=P.value.slice(1);if(j.includes("[")&&(P.posix=!0,j.includes(":"))){let Q=P.value.lastIndexOf("["),Z=P.value.slice(0,Q),ee=P.value.slice(Q+2),ie=E3e[ee];if(ie){P.value=Z+ie,E.backtrack=!0,b(),!s.output&&o.indexOf(P)===1&&(s.output=g);continue}}}(F==="["&&N()!==":"||F==="-"&&N()==="]")&&(F=`\\${F}`),F==="]"&&(P.value==="["||P.value==="[^")&&(F=`\\${F}`),n.posix===!0&&F==="!"&&P.value==="["&&(F="^"),P.value+=F,oe({value:F});continue}if(E.quotes===1&&F!=='"'){F=xi.escapeRegex(F),P.value+=F,oe({value:F});continue}if(F==='"'){E.quotes=E.quotes===1?0:1,n.keepQuotes===!0&&xe({type:"text",value:F});continue}if(F==="("){ve("parens"),xe({type:"paren",value:F});continue}if(F===")"){if(E.parens===0&&n.strictBrackets===!0)throw new SyntaxError(Xy("opening","("));let j=A[A.length-1];if(j&&E.parens===j.parens+1){Ue(A.pop());continue}xe({type:"paren",value:F,output:E.parens?")":"\\)"}),we("parens");continue}if(F==="["){if(n.nobracket===!0||!q().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(Xy("closing","]"));F=`\\${F}`}else ve("brackets");xe({type:"bracket",value:F});continue}if(F==="]"){if(n.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){xe({type:"text",value:F,output:`\\${F}`});continue}if(E.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(Xy("opening","["));xe({type:"text",value:F,output:`\\${F}`});continue}we("brackets");let j=P.value.slice(1);if(P.posix!==!0&&j[0]==="^"&&!j.includes("/")&&(F=`/${F}`),P.value+=F,oe({value:F}),n.literalBrackets===!1||xi.hasRegexChars(j))continue;let Q=xi.escapeRegex(P.value);if(E.output=E.output.slice(0,-P.value.length),n.literalBrackets===!0){E.output+=Q,P.value=Q;continue}P.value=`(${a}${Q}|${P.value})`,E.output+=P.value;continue}if(F==="{"&&n.nobrace!==!0){ve("braces");let j={type:"brace",value:F,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};M.push(j),xe(j);continue}if(F==="}"){let j=M[M.length-1];if(n.nobrace===!0||!j){xe({type:"text",value:F,output:F});continue}let Q=")";if(j.dots===!0){let Z=o.slice(),ee=[];for(let ie=Z.length-1;ie>=0&&(o.pop(),Z[ie].type!=="brace");ie--)Z[ie].type!=="dots"&&ee.unshift(Z[ie].value);Q=x3e(ee,n),E.backtrack=!0}if(j.comma!==!0&&j.dots!==!0){let Z=E.output.slice(0,j.outputIndex),ee=E.tokens.slice(j.tokensIndex);j.value=j.output="\\{",F=Q="\\}",E.output=Z;for(let ie of ee)E.output+=ie.output||ie.value}xe({type:"brace",value:F,output:Q}),we("braces"),M.pop();continue}if(F==="|"){A.length>0&&A[A.length-1].conditions++,xe({type:"text",value:F});continue}if(F===","){let j=F,Q=M[M.length-1];Q&&I[I.length-1]==="braces"&&(Q.comma=!0,j="|"),xe({type:"comma",value:F,output:j});continue}if(F==="/"){if(P.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",o.pop(),P=s;continue}xe({type:"slash",value:F,output:m});continue}if(F==="."){if(E.braces>0&&P.type==="dot"){P.value==="."&&(P.output=d);let j=M[M.length-1];P.type="dots",P.output+=F,P.value+=F,j.dots=!0;continue}if(E.braces+E.parens===0&&P.type!=="bos"&&P.type!=="slash"){xe({type:"text",value:F,output:d});continue}xe({type:"dot",value:F,output:d});continue}if(F==="?"){if(!(P&&P.value==="(")&&n.noextglob!==!0&&N()==="("&&N(2)!=="?"){lt("qmark",F);continue}if(P&&P.type==="paren"){let Q=N(),Z=F;if(Q==="<"&&!xi.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(P.value==="("&&!/[!=<:]/.test(Q)||Q==="<"&&!/<([!=]|\w+>)/.test(q()))&&(Z=`\\${F}`),xe({type:"text",value:F,output:Z});continue}if(n.dot!==!0&&(P.type==="slash"||P.type==="bos")){xe({type:"qmark",value:F,output:C});continue}xe({type:"qmark",value:F,output:R});continue}if(F==="!"){if(n.noextglob!==!0&&N()==="("&&(N(2)!=="?"||!/[!=<:]/.test(N(3)))){lt("negate",F);continue}if(n.nonegate!==!0&&E.index===0){J();continue}}if(F==="+"){if(n.noextglob!==!0&&N()==="("&&N(2)!=="?"){lt("plus",F);continue}if(P&&P.value==="("||n.regex===!1){xe({type:"plus",value:F,output:f});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||E.parens>0){xe({type:"plus",value:F});continue}xe({type:"plus",value:f});continue}if(F==="@"){if(n.noextglob!==!0&&N()==="("&&N(2)!=="?"){xe({type:"at",extglob:!0,value:F,output:""});continue}xe({type:"text",value:F});continue}if(F!=="*"){(F==="$"||F==="^")&&(F=`\\${F}`);let j=w3e.exec(q());j&&(F+=j[0],E.index+=j[0].length),xe({type:"text",value:F});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=F,P.output=k,E.backtrack=!0,E.globstar=!0,pe(F);continue}let U=q();if(n.noextglob!==!0&&/^\([^?]/.test(U)){lt("star",F);continue}if(P.type==="star"){if(n.noglobstar===!0){pe(F);continue}let j=P.prev,Q=j.prev,Z=j.type==="slash"||j.type==="bos",ee=Q&&(Q.type==="star"||Q.type==="globstar");if(n.bash===!0&&(!Z||U[0]&&U[0]!=="/")){xe({type:"star",value:F,output:""});continue}let ie=E.braces>0&&(j.type==="comma"||j.type==="brace"),ne=A.length&&(j.type==="pipe"||j.type==="paren");if(!Z&&j.type!=="paren"&&!ie&&!ne){xe({type:"star",value:F,output:""});continue}for(;U.slice(0,3)==="/**";){let re=t[E.index+4];if(re&&re!=="/")break;U=U.slice(3),pe("/**",3)}if(j.type==="bos"&&X()){P.type="globstar",P.value+=F,P.output=G(n),E.output=P.output,E.globstar=!0,pe(F);continue}if(j.type==="slash"&&j.prev.type!=="bos"&&!ee&&X()){E.output=E.output.slice(0,-(j.output+P.output).length),j.output=`(?:${j.output}`,P.type="globstar",P.output=G(n)+(n.strictSlashes?")":"|$)"),P.value+=F,E.globstar=!0,E.output+=j.output+P.output,pe(F);continue}if(j.type==="slash"&&j.prev.type!=="bos"&&U[0]==="/"){let re=U[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(j.output+P.output).length),j.output=`(?:${j.output}`,P.type="globstar",P.output=`${G(n)}${m}|${m}${re})`,P.value+=F,E.output+=j.output+P.output,E.globstar=!0,pe(F+b()),xe({type:"slash",value:"/",output:""});continue}if(j.type==="bos"&&U[0]==="/"){P.type="globstar",P.value+=F,P.output=`(?:^|${m}|${G(n)}${m})`,E.output=P.output,E.globstar=!0,pe(F+b()),xe({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-P.output.length),P.type="globstar",P.output=G(n),P.value+=F,E.output+=P.output,E.globstar=!0,pe(F);continue}let K={type:"star",value:F,output:k};if(n.bash===!0){K.output=".*?",(P.type==="bos"||P.type==="slash")&&(K.output=V+K.output),xe(K);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&n.regex===!0){K.output=F,xe(K);continue}(E.index===E.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(E.output+=S,P.output+=S):n.dot===!0?(E.output+=T,P.output+=T):(E.output+=V,P.output+=V),N()!=="*"&&(E.output+=g,P.output+=g)),xe(K)}for(;E.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing","]"));E.output=xi.escapeLast(E.output,"["),we("brackets")}for(;E.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing",")"));E.output=xi.escapeLast(E.output,"("),we("parens")}for(;E.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing","}"));E.output=xi.escapeLast(E.output,"{"),we("braces")}if(n.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&xe({type:"maybe_slash",value:"",output:`${m}?`}),E.backtrack===!0){E.output="";for(let U of E.tokens)E.output+=U.output!=null?U.output:U.value,U.suffix&&(E.output+=U.suffix)}return E};A2.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(KR,n.maxLength):KR,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=eue[t]||t;let s=xi.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:f,STAR:m,START_ANCHOR:g}=aw.globChars(s),y=n.dot?d:u,w=n.dot?f:u,S=n.capture?"":"?:",T={negated:!1,prefix:""},R=n.bash===!0?".*?":m;n.capture&&(R=`(${R})`);let C=V=>V.noglobstar===!0?R:`(${S}(?:(?!${g}${V.dot?l:o}).)*?)`,D=V=>{switch(V){case"*":return`${y}${c}${R}`;case".*":return`${o}${c}${R}`;case"*.*":return`${y}${R}${o}${c}${R}`;case"*/*":return`${y}${R}${a}${c}${w}${R}`;case"**":return y+C(n);case"**/*":return`(?:${y}${C(n)}${a})?${w}${c}${R}`;case"**/*.*":return`(?:${y}${C(n)}${a})?${w}${R}${o}${c}${R}`;case"**/.*":return`(?:${y}${C(n)}${a})?${o}${c}${R}`;default:{let L=/^(.*?)\.(\w+)$/.exec(V);if(!L)return;let k=D(L[1]);return k?k+o+L[2]:void 0}}},$=xi.removePrefix(t,T),G=D($);return G&&n.strictSlashes!==!0&&(G+=`${a}?`),G};rue.exports=A2});var oue=B((UCt,sue)=>{"use strict";var I3e=require("path"),k3e=Zle(),C2=iue(),R2=zR(),P3e=sw(),O3e=t=>t&&typeof t=="object"&&!Array.isArray(t),hr=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(f=>hr(f,e,n));return f=>{for(let m of u){let g=m(f);if(g)return g}return!1}}let r=O3e(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=R2.isWindows(e),o=r?hr.compileRe(t,e):hr.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=hr(i.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:f,match:m,output:g}=hr.test(u,o,e,{glob:t,posix:s}),y={glob:t,state:a,regex:o,posix:s,input:u,output:g,match:m,isMatch:f};return typeof i.onResult=="function"&&i.onResult(y),f===!1?(y.isMatch=!1,d?y:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(y),y.isMatch=!1,d?y:!1):(typeof i.onMatch=="function"&&i.onMatch(y),d?y:!0)};return n&&(l.state=a),l};hr.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=n||{},o=s.format||(i?R2.toPosixSlashes:null),a=t===r,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===r),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=hr.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};hr.matchBase=(t,e,n,r=R2.isWindows(n))=>(e instanceof RegExp?e:hr.makeRe(e,n)).test(I3e.basename(t));hr.isMatch=(t,e,n)=>hr(e,n)(t);hr.parse=(t,e)=>Array.isArray(t)?t.map(n=>hr.parse(n,e)):C2(t,{...e,fastpaths:!1});hr.scan=(t,e)=>k3e(t,e);hr.compileRe=(t,e,n=!1,r=!1)=>{if(n===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=hr.toRegex(a,e);return r===!0&&(c.state=t),c};hr.makeRe=(t,e={},n=!1,r=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=C2.fastpaths(t,e)),i.output||(i=C2(t,e)),hr.compileRe(i,e,n,r)};hr.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};hr.constants=P3e;sue.exports=hr});var I2=B((FCt,aue)=>{"use strict";aue.exports=oue()});var mue=B((BCt,hue)=>{"use strict";var lw=require("fs"),{Readable:M3e}=require("stream"),cw=require("path"),{promisify:QR}=require("util"),k2=I2(),N3e=QR(lw.readdir),D3e=QR(lw.stat),cue=QR(lw.lstat),L3e=QR(lw.realpath),U3e="!",fue="READDIRP_RECURSIVE_ERROR",F3e=new Set(["ENOENT","EPERM","EACCES","ELOOP",fue]),P2="files",pue="directories",XR="files_directories",YR="all",lue=[P2,pue,XR,YR],B3e=t=>F3e.has(t.code),[uue,q3e]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),$3e=process.platform==="win32"&&(uue>10||uue===10&&q3e>=5),due=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=k2(t.trim());return n=>e(n.basename)}if(Array.isArray(t)){let e=[],n=[];for(let r of t){let i=r.trim();i.charAt(0)===U3e?n.push(k2(i.slice(1))):e.push(k2(i))}return n.length>0?e.length>0?r=>e.some(i=>i(r.basename))&&!n.some(i=>i(r.basename)):r=>!n.some(i=>i(r.basename)):r=>e.some(i=>i(r.basename))}}},JR=class t extends M3e{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:P2,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let n={...t.defaultOptions,...e},{root:r,type:i}=n;this._fileFilter=due(n.fileFilter),this._directoryFilter=due(n.directoryFilter);let s=n.lstat?cue:D3e;$3e?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth,this._wantsDir=[pue,XR,YR].includes(i),this._wantsFile=[P2,XR,YR].includes(i),this._wantsEverything=i===YR,this._root=cw.resolve(r),this._isDirent="Dirent"in lw&&!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:n,depth:r,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,n));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await N3e(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}async _formatEntry(e,n){let r;try{let i=this._isDirent?e.name:e,s=cw.resolve(cw.join(n,i));r={path:cw.relative(this._root,s),fullPath:s,basename:i},r[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return r}_onError(e){B3e(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let n=e&&e[this._statsProp];if(n){if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let r=e.fullPath;try{let i=await L3e(r),s=await cue(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(r.startsWith(i)&&r.substr(o,1)===cw.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${i}"`);return a.code=fue,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}},Jy=(t,e={})=>{let n=e.entryType||e.type;if(n==="both"&&(n=XR),n&&(e.type=n),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!lue.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${lue.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new JR(e)},G3e=(t,e={})=>new Promise((n,r)=>{let i=[];Jy(t,e).on("data",s=>i.push(s)).on("end",()=>n(i)).on("error",s=>r(s))});Jy.promise=G3e;Jy.ReaddirpStream=JR;Jy.default=Jy;hue.exports=Jy});var Qy=B((qCt,gue)=>{gue.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var n=t.length;if(n<=1)return t;var r="";if(n>4&&t[3]==="\\"){var i=t[2];(i==="?"||i===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),r="//")}var s=t.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),r+s.join("/")}});var Sue=B((Eue,wue)=>{"use strict";Object.defineProperty(Eue,"__esModule",{value:!0});var vue=I2(),H3e=Qy(),yue="!",j3e={returnIndex:!1},W3e=t=>Array.isArray(t)?t:[t],V3e=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let n=vue(t,e);return r=>t===r||n(r)}return t instanceof RegExp?n=>t.test(n):n=>!1},_ue=(t,e,n,r)=>{let i=Array.isArray(n),s=i?n[0]:n;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=H3e(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return r?-1:!1}let a=i&&[o].concat(n.slice(1));for(let c=0;c<t.length;c++){let l=t[c];if(i?l(...a):l(o))return r?c:!0}return r?-1:!1},O2=(t,e,n=j3e)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let r=typeof n=="boolean"?{returnIndex:n}:n,i=r.returnIndex||!1,s=W3e(t),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===yue).map(c=>c.slice(1)).map(c=>vue(c,r)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==yue).map(c=>V3e(c,r));return e==null?(c,l=!1)=>_ue(a,o,c,typeof l=="boolean"?l:!1):_ue(a,o,e,i)};O2.default=O2;wue.exports=O2});var bue=B(($Ct,xue)=>{xue.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var M2=B((GCt,Aue)=>{var z3e=bue(),Tue={"{":"}","(":")","[":"]"},K3e=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,r=-2,i=-2,s=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||r!==-1&&t[e]==="["&&t[e+1]!=="]"&&(r<e&&(r=t.indexOf("]",e)),r>e&&(o===-1||o>r||(o=t.indexOf("\\",e),o===-1||o>r)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(s=t.indexOf(")",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(s=t.indexOf(")",n),s>n&&(o=t.indexOf("\\",n),o===-1||o>s))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=Tue[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},Y3e=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var r=Tue[n];if(r){var i=t.indexOf(r,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};Aue.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(z3e(e))return!0;var r=K3e;return n&&n.strict===!1&&(r=Y3e),r(e)}});var Rue=B((HCt,Cue)=>{"use strict";var X3e=M2(),J3e=require("path").posix.dirname,Q3e=require("os").platform()==="win32",N2="/",Z3e=/\\/g,e6e=/[\{\[].*[\}\]]$/,t6e=/(^|[^\\])([\{\[]|\([^\)]+$)/,n6e=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Cue.exports=function(e,n){var r=Object.assign({flipBackslashes:!0},n);r.flipBackslashes&&Q3e&&e.indexOf(N2)<0&&(e=e.replace(Z3e,N2)),e6e.test(e)&&(e+=N2),e+="a";do e=J3e(e);while(X3e(e)||t6e.test(e));return e.replace(n6e,"$1")}});var ZR=B($o=>{"use strict";$o.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;$o.find=(t,e)=>t.nodes.find(n=>n.type===e);$o.exceedsLimit=(t,e,n=1,r)=>r===!1||!$o.isInteger(t)||!$o.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=r;$o.escapeNode=(t,e=0,n)=>{let r=t.nodes[e];r&&(n&&r.type===n||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};$o.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;$o.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;$o.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;$o.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);$o.flatten=(...t)=>{let e=[],n=r=>{for(let i=0;i<r.length;i++){let s=r[i];if(Array.isArray(s)){n(s);continue}s!==void 0&&e.push(s)}return e};return n(t),e}});var eI=B((WCt,kue)=>{"use strict";var Iue=ZR();kue.exports=(t,e={})=>{let n=(r,i={})=>{let s=e.escapeInvalid&&Iue.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(s||o)&&Iue.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let c of r.nodes)a+=n(c);return a};return n(t)}});var Oue=B((VCt,Pue)=>{"use strict";Pue.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var $ue=B((zCt,que)=>{"use strict";var Mue=Oue(),Ph=(t,e,n)=>{if(Mue(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Mue(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...n};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let i=String(r.relaxZeros),s=String(r.shorthand),o=String(r.capture),a=String(r.wrap),c=t+":"+e+"="+i+s+o+a;if(Ph.cache.hasOwnProperty(c))return Ph.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let y=t+"|"+e;return r.capture?`(${y})`:r.wrap===!1?y:`(?:${y})`}let d=Bue(t)||Bue(e),f={min:t,max:e,a:l,b:u},m=[],g=[];if(d&&(f.isPadded=d,f.maxLen=String(f.max).length),l<0){let y=u<0?Math.abs(u):1;g=Nue(y,Math.abs(l),f,r),l=f.a=0}return u>=0&&(m=Nue(l,u,f,r)),f.negatives=g,f.positives=m,f.result=r6e(g,m,r),r.capture===!0?f.result=`(${f.result})`:r.wrap!==!1&&m.length+g.length>1&&(f.result=`(?:${f.result})`),Ph.cache[c]=f,f.result};function r6e(t,e,n){let r=D2(t,e,"-",!1,n)||[],i=D2(e,t,"",!1,n)||[],s=D2(t,e,"-?",!0,n)||[];return r.concat(s).concat(i).join("|")}function i6e(t,e){let n=1,r=1,i=Lue(t,n),s=new Set([e]);for(;t<=i&&i<=e;)s.add(i),n+=1,i=Lue(t,n);for(i=Uue(e+1,r)-1;t<i&&i<=e;)s.add(i),r+=1,i=Uue(e+1,r)-1;return s=[...s],s.sort(a6e),s}function s6e(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let r=o6e(t,e),i=r.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=r[a];c===l?s+=c:c!=="0"||l!=="9"?s+=c6e(c,l,n):o++}return o&&(s+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function Nue(t,e,n,r){let i=i6e(t,e),s=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=s6e(String(o),String(l),r),d="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Fue(a.count),o=l+1;continue}n.isPadded&&(d=l6e(l,n,r)),u.string=d+u.pattern+Fue(u.count),s.push(u),o=l+1,a=u}return s}function D2(t,e,n,r,i){let s=[];for(let o of t){let{string:a}=o;!r&&!Due(e,"string",a)&&s.push(n+a),r&&Due(e,"string",a)&&s.push(n+a)}return s}function o6e(t,e){let n=[];for(let r=0;r<t.length;r++)n.push([t[r],e[r]]);return n}function a6e(t,e){return t>e?1:e>t?-1:0}function Due(t,e,n){return t.some(r=>r[e]===n)}function Lue(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Uue(t,e){return t-t%Math.pow(10,e)}function Fue(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function c6e(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Bue(t){return/^-?(0+)\d/.test(t)}function l6e(t,e,n){if(!e.isPadded)return t;let r=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(r){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${r}}`:`0{${r}}`}}Ph.cache={};Ph.clearCache=()=>Ph.cache={};que.exports=Ph});var F2=B((KCt,Kue)=>{"use strict";var u6e=require("util"),Hue=$ue(),Gue=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),d6e=t=>e=>t===!0?Number(e):String(e),L2=t=>typeof t=="number"||typeof t=="string"&&t!=="",uw=t=>Number.isInteger(+t),U2=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},f6e=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,p6e=(t,e,n)=>{if(e>0){let r=t[0]==="-"?"-":"";r&&(t=t.slice(1)),t=r+t.padStart(r?e-1:e,"0")}return n===!1?String(t):t},nI=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},h6e=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let r=e.capture?"":"?:",i="",s="",o;return t.positives.length&&(i=t.positives.map(a=>nI(String(a),n)).join("|")),t.negatives.length&&(s=`-(${r}${t.negatives.map(a=>nI(String(a),n)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${r}${o})`:o},jue=(t,e,n,r)=>{if(n)return Hue(t,e,{wrap:!1,...r});let i=String.fromCharCode(t);if(t===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},Wue=(t,e,n)=>{if(Array.isArray(t)){let r=n.wrap===!0,i=n.capture?"":"?:";return r?`(${i}${t.join("|")})`:t.join("|")}return Hue(t,e,n)},Vue=(...t)=>new RangeError("Invalid range arguments: "+u6e.inspect(...t)),zue=(t,e,n)=>{if(n.strictRanges===!0)throw Vue([t,e]);return[]},m6e=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},g6e=(t,e,n=1,r={})=>{let i=Number(t),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(r.strictRanges===!0)throw Vue([t,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=U2(a)||U2(c)||U2(l),d=u?Math.max(a.length,c.length,l.length):0,f=u===!1&&f6e(t,e,r)===!1,m=r.transform||d6e(f);if(r.toRegex&&n===1)return jue(nI(t,d),nI(e,d),!0,r);let g={negatives:[],positives:[]},y=T=>g[T<0?"negatives":"positives"].push(Math.abs(T)),w=[],S=0;for(;o?i>=s:i<=s;)r.toRegex===!0&&n>1?y(i):w.push(p6e(m(i,S),d,f)),i=o?i-n:i+n,S++;return r.toRegex===!0?n>1?h6e(g,r,d):Wue(w,null,{wrap:!1,...r}):w},y6e=(t,e,n=1,r={})=>{if(!uw(t)&&t.length>1||!uw(e)&&e.length>1)return zue(t,e,r);let i=r.transform||(f=>String.fromCharCode(f)),s=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(r.toRegex&&n===1)return jue(c,l,!1,r);let u=[],d=0;for(;a?s>=o:s<=o;)u.push(i(s,d)),s=a?s-n:s+n,d++;return r.toRegex===!0?Wue(u,null,{wrap:!1,options:r}):u},tI=(t,e,n,r={})=>{if(e==null&&L2(t))return[t];if(!L2(t)||!L2(e))return zue(t,e,r);if(typeof n=="function")return tI(t,e,1,{transform:n});if(Gue(n))return tI(t,e,0,n);let i={...r};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,uw(n)?uw(t)&&uw(e)?g6e(t,e,n,i):y6e(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Gue(n)?m6e(n,i):tI(t,e,1,n)};Kue.exports=tI});var Jue=B((YCt,Xue)=>{"use strict";var _6e=F2(),Yue=ZR(),v6e=(t,e={})=>{let n=(r,i={})=>{let s=Yue.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(r.isOpen===!0)return c+r.value;if(r.isClose===!0)return console.log("node.isClose",c,r.value),c+r.value;if(r.type==="open")return a?c+r.value:"(";if(r.type==="close")return a?c+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=Yue.reduce(r.nodes),d=_6e(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)l+=n(u,r);return l};return n(t)};Xue.exports=v6e});var ede=B((XCt,Zue)=>{"use strict";var E6e=F2(),Que=eI(),Zy=ZR(),Oh=(t="",e="",n=!1)=>{let r=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?Zy.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let s of i)r.push(Oh(s,e,n));else for(let s of e)n===!0&&typeof s=="string"&&(s=`{${s}}`),r.push(Array.isArray(s)?Oh(i,s,n):i+s);return Zy.flatten(r)},w6e=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(Oh(a.pop(),Que(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Oh(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let d=Zy.reduce(i.nodes);if(Zy.exceedsLimit(...d,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=E6e(...d,e);f.length===0&&(f=Que(i,e)),a.push(Oh(a.pop(),f)),i.nodes=[];return}let c=Zy.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let d=0;d<i.nodes.length;d++){let f=i.nodes[d];if(f.type==="comma"&&i.type==="brace"){d===1&&l.push(""),l.push("");continue}if(f.type==="close"){a.push(Oh(a.pop(),l,c));continue}if(f.value&&f.type!=="open"){l.push(Oh(l.pop(),f.value));continue}f.nodes&&r(f,i)}return l};return Zy.flatten(r(t))};Zue.exports=w6e});var nde=B((JCt,tde)=>{"use strict";tde.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
412
+ `}function B3e(t){let e=U3e[t];if(!e)return{success:!1,error:"Unknown tool"};try{return t==="codex"||t==="opencode"||t==="amp"||t==="pi"||t==="omp"?e.enable():e.enable(fn[t]())}catch(n){return{success:!1,error:n.message}}}function q3e(t){let e=(process.env.PATH||"").split(pr.default.delimiter).filter(Boolean),n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return e.some(r=>n.some(i=>{try{return He.default.existsSync(pr.default.join(r,t+i))}catch{return!1}}))}function Rle(t){let e=xle[t];if(e&&q3e(e))return!0;let n=p3e[t]?.();return n?(Array.isArray(n)?n:[n]).some(r=>He.default.existsSync(r)):!1}function Ile(){let t={};for(let e of F3e)if(Rle(e))try{let n=B3e(e);t[e]=n.success&&!n.untrusted?.length}catch{t[e]=!1}return t}async function kle(){if(!Rle("codex"))return null;try{let{missing:t}=await b3e();return t.length&&console.warn(`\u26A0\uFE0F codex hooks written but not trusted: ${t.length} \u2014 run codex and trust them`),t.length?{untrusted:t.length}:{untrusted:0}}catch(t){return console.warn(`\u26A0\uFE0F codex hook trust failed: ${t.message}`),{error:t.message}}}function Ple(){let t=fn.claude(),e=Or(t);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let n=e.env||{};Object.keys(Bv).some(i=>n[i]!==Bv[i])&&(ble(e),fs(t,e))}var Ele,He,pr,wle,qR,Sle,f3e,Si,Zd,fn,xle,Rh,p3e,u2,$R,BR,h3e,FR,Tle,eCt,Ale,E3e,S3e,A3e,_le,R3e,P3e,M3e,N3e,D3e,L3e,U3e,F3e,Ole=ae(()=>{Ele=ce(require("os"),1),He=ce(require("fs"),1),pr=ce(require("path"),1),wle=require("child_process");Lt();So();Fc();qR=`http://localhost:${Ts}/api/notify`,Sle="nineRemoteNotify",f3e=pr.default.join(Oe.STATE,"claudeEnvBackup.json"),Si=(...t)=>pr.default.join(Ele.default.homedir(),...t),Zd=(t,...e)=>{let n=process.env[t];return n&&n.trim()?n.trim():Si(...e)},fn={claude:()=>Si(".claude","settings.json"),codex:()=>Si(".codex","config.toml"),codexHooks:()=>Si(".codex","hooks.json"),codexScript:()=>Si(".codex","9remote-notify.sh"),opencode:()=>Si(".config","opencode","plugin",`${Sle}.js`),grok:()=>pr.default.join(Zd("GROK_HOME",".grok"),"hooks","9remote.json"),cursor:()=>Si(".cursor","hooks.json"),antigravity:()=>Si(".gemini","config","hooks.json"),kiro:()=>pr.default.join(Zd("KIRO_HOME",".kiro"),"agents","9remote.json"),copilot:()=>pr.default.join(Zd("COPILOT_HOME",".copilot"),"config.json"),codebuddy:()=>pr.default.join(Zd("CODEBUDDY_CONFIG_DIR",".codebuddy"),"settings.json"),factory:()=>Si(".factory","settings.json"),qoder:()=>pr.default.join(Zd("QODER_CONFIG_DIR",".qoder"),"settings.json"),rovodev:()=>Si(".rovodev","config.yml"),hermes:()=>pr.default.join(Zd("HERMES_HOME",".hermes"),"config.yaml"),amp:()=>Si(".config","amp","plugins","9remote.ts"),devin:()=>Si(".config","devin","config.json"),pi:()=>pr.default.join(Zd("PI_CODING_AGENT_DIR",".pi","agent"),"extensions","9remote.ts"),omp:()=>pr.default.join(Zd("PI_CODING_AGENT_DIR",".omp","agent"),"extensions","9remote.ts")},xle={claude:"claude",codex:"codex",opencode:"opencode",grok:"grok",cursor:"cursor-agent",antigravity:"agy",kiro:"kiro-cli",copilot:"copilot",codebuddy:"codebuddy",factory:"droid",qoder:"qodercli",rovodev:"acli",hermes:"hermes",amp:"amp",pi:"pi",omp:"omp",devin:"devin"},Rh=(t,e,{sessionId:n=!1}={})=>{let r=n?mF(e)[0]:null;return`${r?`csid=$(cat 2>/dev/null | sed -n 's/.*"${r}" *: *"\\([^"]*\\)".*/\\1/p'); `:""}command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${qR}?type=${t}&sessionId=$NINE_REMOTE_SESSION_ID${r?"&csid=$csid":""}&tool=${e}" > /dev/null 2>&1 & true`},p3e={claude:()=>Si(".claude"),codex:()=>Si(".codex"),opencode:()=>[Si(".config","opencode"),Si(".opencode")]},u2=t=>Math.ceil(t/1e3),$R=5e3,BR=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h3e=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;FR={UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},Tle=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),eCt=Object.fromEntries(Object.keys(FR).map(t=>[Tle(t),t])),Ale=/^\[hooks\.state\."(?<key>[^"]+)"\]$/m,E3e=15e3;S3e=t=>/^sha256:/.test(t)?t:`sha256:${t}`;A3e=/# 9Remote notification\nnotify\s*=.*\n?/g,_le=/^# 9Remote-saved: (notify\s*=.*)$/m;R3e={enable(){let t=fn.codexHooks(),e=Or(t),n={...e.hooks||{}};for(let[r,i]of Object.entries(FR))n[r]=[...(n[r]||[]).filter(s=>!l2(s)),I3e(i)];return e.hooks=n,fs(t,e),C3e(),{success:!0}},disable(){let t=fn.codexHooks(),e=new Set(Cle(t).filter(n=>n.command.includes("&tool=codex")).map(n=>n.key));if(He.default.existsSync(t)){let n=Or(t);if(n.hooks){for(let r of Object.keys(FR))n.hooks[r]=(n.hooks[r]||[]).filter(i=>!l2(i)),n.hooks[r].length===0&&delete n.hooks[r];Object.keys(n.hooks).length===0&&delete n.hooks}fs(t,n)}return T3e(fn.codex(),e),{success:!0}},isEnabled(){let t=Or(fn.codexHooks()).hooks||{};return Object.keys(FR).every(e=>(t[e]||[]).some(l2))}};P3e={enable(){let t=fn.opencode(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,k3e(),"utf8"),{success:!0}},disable(){let t=fn.opencode();return He.default.existsSync(t)&&He.default.unlinkSync(t),{success:!0}},isEnabled(){let t=fn.opencode();return He.default.existsSync(t)&&He.default.readFileSync(t,"utf8").includes("&sessionID=")}};M3e="# 9remote hooks begin",N3e="# 9remote hooks end",D3e=" # 9remote hooks begin",L3e=" # 9remote hooks end",U3e={claude:Ch("claude",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked",Notification:"blocked"},t=>t,{matchers:{Notification:"permission_prompt"},extra:ble,sessionId:!0}),devin:Ch("devin",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},t=>t,{sessionId:!0}),codex:R3e,opencode:P3e,grok:Ch("grok",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",Notification:"blocked"},u2),cursor:y3e("cursor",{stop:"done",beforeShellExecution:"blocked",beforeToolCall:"working"},{extra:t=>{t.version=t.version||1}}),antigravity:_3e("antigravity","9remote",{UserPromptSubmit:"working",PreToolUse:"working",Stop:"done",Notification:"blocked"}),kiro:v3e("kiro",{UserPromptSubmit:"working",PostToolUse:"working",preToolUse:"blocked",stop:"done"}),copilot:Ch("copilot",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),codebuddy:Ch("codebuddy",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),factory:Ch("factory",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),qoder:Ch("qoder",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),rovodev:yle("rovodev",{begin:D3e,end:L3e,items:[{event:"on_complete",type:"done"},{event:"on_error",type:"done"},{event:"on_tool_permission",type:"blocked"},{event:"on_message",type:"working"},{event:"on_tool_start",type:"working"}]}),hermes:(()=>{let t=yle("hermes",{begin:M3e,end:N3e,items:[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}]}),e=()=>pr.default.join(pr.default.dirname(fn.hermes()),"shell-hooks-allowlist.json");return{enable:()=>{let n=t.enable(fn.hermes()),r=Or(e()),i=(r.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes")));return r.approvals=[...i,...[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}].map(({event:s,type:o})=>({event:s,command:Rh(o,"hermes"),approved_at:"2020-01-01T00:00:00Z"}))],fs(e(),r),n},disable:()=>{let n=t.disable(fn.hermes()),r=e();if(He.default.existsSync(r)){let i=Or(r);i.approvals=(i.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes"))),i.approvals.length?fs(r,i):He.default.unlinkSync(r)}return n},isEnabled:()=>t.isEnabled(fn.hermes())}})(),amp:{enable(){let t=fn.amp(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,vle("amp","amp","agent.start","agent.end"),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.amp())&&He.default.unlinkSync(fn.amp()),{success:!0}},isEnabled(){return He.default.existsSync(fn.amp())}},pi:{enable(){let t=fn.pi(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,vle("pi","pi","agent_start","agent_end"),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.pi())&&He.default.unlinkSync(fn.pi()),{success:!0}},isEnabled(){return He.default.existsSync(fn.pi())}},omp:{enable(){let t=fn.omp(),e=pr.default.dirname(t);return He.default.existsSync(e)||He.default.mkdirSync(e,{recursive:!0}),He.default.writeFileSync(t,O3e(),"utf8"),{success:!0}},disable(){return He.default.existsSync(fn.omp())&&He.default.unlinkSync(fn.omp()),{success:!0}},isEnabled(){return He.default.existsSync(fn.omp())}}},F3e=lK});var d2=ae(()=>{Fs()});var c2={};yr(c2,{broadcastAiStatus:()=>iw,broadcastServerInfo:()=>WR,initializeTerminal:()=>m2,listSessionRoots:()=>_u,matchWorkspacePath:()=>Ble,registerManagedSession:()=>h2,setConnectCheckHandler:()=>g2,setupTerminalHandlers:()=>y2,setupTerminalSocket:()=>nf});async function j3e(t,e){if(!One(e))return;let r=(await Rd().catch(()=>null))?.find(s=>s.id===e);Pne(e,r?.foregroundProcess)?.state==="idle"&&(nt(t,"statusChange",{sessionId:e,state:"idle",tool:null,conversationId:null}),nt(t,"statusState",qc()))}function W3e(t,e){let n=(HR.get(t)||"")+e,r=null;Mle.lastIndex=0;for(let o;o=Mle.exec(n);)r=o[1];if(r){let o=mne(r);o&&os(t,o)}let i=n.lastIndexOf("\x1B]"),s=i===-1?"":n.slice(i);s&&s.length<=G3e&&!s.slice(3).includes("\x07")&&!s.includes("\x1B\\")?HR.set(t,s):HR.delete(t)}function Dle(){let t=(Nle||Promise.resolve()).catch(()=>{}).then(()=>V3e());return Nle=t.catch(()=>{}),t}async function V3e(){let t=await Rd(),e=new Map(t.map(r=>[r.id,r])),n=nC();for(let r of t)if(!n[r.id])try{await Id(r.id)}catch{}Wr.clear();for(let[r,i]of Object.entries(n)){let s=e.get(r);Wr.set(r,{daemon:!0,name:i.name,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,workspacePath:i.workspacePath??nw[r]??null,lastCols:i.cols??null,lastRows:i.rows??null,needsRespawn:!s,agent:i.agent||null}),i.agent&&os(r,i.agent),xF(r,i)}ii(Wr)}function z3e(t){!ef||!t||rw.has(t)||rw.set(t,setTimeout(()=>{rw.delete(t),jC(ef,Wr,t).catch(()=>{})},NQ))}function f2(){let{assignments:t,created:e}=tre({sessions:Wr,workspaces:[...tf.values()],sessionWorkspaces:kh});if(Object.keys(t).length){for(let n of e)tf.set(n.id,n);for(let[n,r]of Object.entries(t)){kh[n]=r;let i=Wr.get(n);i&&!i.workspacePath&&(i.workspacePath=tf.get(r)?.path||null)}my(tf,kh,jR),ii(Wr),console.log(Fle(`\u{1F4C1} Grouped ${Object.keys(t).length} loose terminal(s)`+(e.length?` into ${e.length} new workspace(s)`:"")))}}function _u(){return[...Wr.entries()].map(([t,e])=>({id:t,name:e.name,workspacePath:e.workspacePath||null,cwd:e.cwd||null}))}function Ble(t,e){let n=e?(0,Ih.resolve)(e):"";if(!n)return null;let r=null,i=null,s=null;for(let o of t||[]){if(!o?.path)continue;let a=(0,Ih.resolve)(o.path);n===a?r=o:n.startsWith(a+"/")&&(!i||a.length>(0,Ih.resolve)(i.path).length)?i=o:a.startsWith(n+"/")&&(!s||a.length<(0,Ih.resolve)(s.path).length)&&(s=o)}return r||i||s||null}function h2({sessionId:t,name:e,autoNamed:n=!0,cwd:r=null,workspacePath:i=null,shellId:s=null,shellLabel:o=null,agent:a=null}){let c=Ble([...tf.values()],i||r)||null;return Wr.set(t,{daemon:!0,name:e,autoNamed:n,createdAt:Date.now(),cwd:r||c?.path||null,workspacePath:c?.path||null,shellId:s,shellLabel:o,agent:a}),c&&(kh[t]=c.id,my(tf,kh,jR)),ii(Wr),nt(null,"sessionsChanged"),{success:!0,sessionId:t,workspacePath:c?.path||null}}async function m2(){let t=Vne();if(!t){let r=nC(),i=Wne();t=ere(i,r);let s=new Map(t.workspaces.map(c=>[c.id,c]));if(my(s,t.sessionWorkspaces,t.sessionOrder),nw=t.sessionPaths||{},Object.keys(nw).length){for(let[c,l]of Object.entries(nw))r[c]&&(r[c].workspacePath=l);jne(r)}let o=(i.groups||[]).filter(c=>t.workspaces.some(l=>l.id===c.id)).length,a=(i.groups||[]).length-o;(t.workspaces.length||a)&&console.log(Fle(`\u{1F4C1} Migrated ${t.workspaces.length} workspace(s) from terminal groups`+(a?`, dropped ${a} empty group(s)`:"")))}for(let r of t.workspaces)tf.set(r.id,r);Object.assign(kh,t.sessionWorkspaces),jR.push(...t.sessionOrder),Ane(()=>ii(Wr)),Nne(z3e);try{Ple()}catch{}try{Ile()}catch{}kle().catch(()=>{});try{hle()}catch{}if(p2==="daemon")if(!await iU())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await Dle(),f2(),Fp("connected",()=>{Dle().then(f2).catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=Hne(),n=nC();for(let r of e){let i=n[r]||{};Wr.set(r,{pty:null,name:i.name||`Terminal ${Wr.size+1}`,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt||Date.now(),cwd:i.cwd,workspacePath:i.workspacePath??nw[r]??null,shellId:i.shellId,buffer:[],needsRestore:!0}),xF(r,i),console.log(`\u{1F504} Found saved session: ${r}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`),f2()}function nf(t,e){ef=t,p2==="daemon"&&(Fp("output",({sessionId:i,enc:s,data:o,replay:a})=>{a!==!0&&(JA(i),YA(i));let c=s==="b64"?Buffer.from(o,"base64"):Buffer.from(o||"");c.length>Pa&&(GR++,(GR===1||GR%500===0)&&Ule.info(`[slice] chunk ${c.length>>10}KB \u2192 ${Math.ceil(c.length/Pa)} events (total sliced: ${GR})`)),s==="b64"&&W3e(i,c.toString("utf8"));for(let l=0;l<c.length||l===0;l+=Pa){let u=c.subarray(l,l+Pa),d=a===!0?NE(i):Ase(i);a!==!0&&Cse(i,d,u),nt(t,"output",{sessionId:i,enc:"bin",data:u,replay:a===!0,seq:d})}}),Bne(i=>nt(t,"statusState",qc())),Une(()=>nt(t,"statusState",qc())),Fp("cwdChange",({sessionId:i,cwd:s})=>{let o=Wr.get(i);o&&s&&o.cwd!==s&&(o.cwd=s,ii(Wr)),nt(t,"cwdChange",{sessionId:i,cwd:s})}),Fp("processChange",({sessionId:i,process:s})=>{let o=kne(i,s);if(o?.state==="pendingShell"){setTimeout(()=>j3e(t,i),H3e);return}o?.state==="idle"&&(nt(t,"statusChange",{sessionId:i,state:"idle",tool:null,conversationId:null}),nt(t,"statusState",qc()))}),Fp("sessionClosed",i=>{Wr.delete(i),Iy(i),fy(i),HR.delete(i);let s=rw.get(i);s&&(clearTimeout(s),rw.delete(i)),AF(i),nt(t,"sessionClosed",i),nt(t,"notificationCleared",i)}));let n=()=>({version:$3e,remoteAvailable:Mp(),mobileAvailable:Jte(),daemonMode:p2==="daemon"&&Pn(),platform:process.platform,updateAvailable:k0(),canSelfUpdate:!0,caps:{joinSessionSize:!0,artifact:!0},artifactEnabled:tw(),voiceConfig:Ra().voiceConfig||null,mcpClients:Yy,...ene()}),r=()=>{let i=n();for(let s of t.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i)};xL(r),nf._buildServerInfo=n,nf._emitServerInfo=r}function WR(){nf._emitServerInfo?.()}function iw(t,e,n,r=null){if(!ef)return null;if(e==="done")return XA(t,()=>{let a=r?.sessionId||r?.threadId||ss(t)?.id||null,c=Hd(t),l=nh({type:e,sessionId:t,tool:n});!l||l===c||(nt(ef,"statusChange",{sessionId:t,state:e,tool:n,conversationId:a}),nt(ef,"statusState",qc()))}),Hd(t);let i=r?.sessionId||r?.threadId||ss(t)?.id||null,s=Hd(t),o=nh({type:e,sessionId:t,tool:n});return!o||o===s||(nt(ef,"statusChange",{sessionId:t,state:e,tool:n,conversationId:i}),nt(ef,"statusState",qc())),o}function g2(t){qle=t}async function y2(t,e,n){Ule.info(`[diag] setupTerminalHandlers START id=${t.id} virtual=${!!t.defersWsAdapter}`),tne(),qle?.(),t.emit("srvCaps",{env2:1}),t.emit("serverInfo",nf._buildServerInfo?.()),Mse(t,e,Wr,tf,kh,jR),qse(t,Wr),mle(t,e),SA()&&await JZ(t,n).catch(r=>{console.error("\u274C Failed to setup remote handlers:",r.message)}),Qte(t),t.on("disconnect",()=>{sce(t.id),nne()})}var Ih,Lle,Ule,OCt,Fle,p2,$3e,Mle,G3e,H3e,HR,Wr,tf,kh,jR,nw,Nle,rw,ef,GR,qle,Ha=ae(()=>{nM();Ih=require("path"),Lle=require("url");_i();xA();Zte();ns();UA();rC();nre();VC();$se();gle();Ole();UR();Dg();xR();d2();Fs();Fc();es();FB();ru();tt();Ule=Se("terminal"),OCt=(0,Ih.dirname)((0,Lle.fileURLToPath)(__importMetaUrl)),Fle=Lv.rgb(230,138,110),p2="daemon",$3e="3.0.25",Mle=/\x1b\](?:0|2);([^\x07\x1b]*)(?:\x07|\x1b\\)/g,G3e=256,H3e=1500,HR=new Map;Wr=new Map,tf=new Map,kh={},jR=[],nw={},Nle=null;rw=new Map,ef=null;GR=0;qle=null});var sw=B((MCt,Wle)=>{"use strict";var K3e=require("path"),Xc="\\\\/",$le=`[^${Xc}]`,Y3e=0,vu="\\.",X3e="\\+",J3e="\\?",VR="\\/",Q3e="(?=.)",Gle="[^/]",_2=`(?:${VR}|$)`,Hle=`(?:^|${VR})`,v2=`${vu}{1,2}${_2}`,Z3e=`(?!${vu})`,eWe=`(?!${Hle}${v2})`,tWe=`(?!${vu}{0,1}${_2})`,nWe=`(?!${v2})`,rWe=`[^.${VR}]`,iWe=`${Gle}*?`,jle={DOT_LITERAL:vu,PLUS_LITERAL:X3e,QMARK_LITERAL:J3e,SLASH_LITERAL:VR,ONE_CHAR:Q3e,QMARK:Gle,END_ANCHOR:_2,DOTS_SLASH:v2,NO_DOT:Z3e,NO_DOTS:eWe,NO_DOT_SLASH:tWe,NO_DOTS_SLASH:nWe,QMARK_NO_DOT:rWe,STAR:iWe,START_ANCHOR:Hle},sWe={...jle,SLASH_LITERAL:`[${Xc}]`,QMARK:$le,STAR:`${$le}*?`,DOTS_SLASH:`${vu}{1,2}(?:[${Xc}]|$)`,NO_DOT:`(?!${vu})`,NO_DOTS:`(?!(?:^|[${Xc}])${vu}{1,2}(?:[${Xc}]|$))`,NO_DOT_SLASH:`(?!${vu}{0,1}(?:[${Xc}]|$))`,NO_DOTS_SLASH:`(?!${vu}{1,2}(?:[${Xc}]|$))`,QMARK_NO_DOT:`[^.${Xc}]`,START_ANCHOR:`(?:^|[${Xc}])`,END_ANCHOR:`(?:[${Xc}]|$)`},oWe={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Wle.exports={DEFAULT_MAX_EXTGLOB_RECURSION:Y3e,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:oWe,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:K3e.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?sWe:jle}}});var zR=B(ps=>{"use strict";var aWe=require("path"),cWe=process.platform==="win32",{REGEX_BACKSLASH:lWe,REGEX_REMOVE_BACKSLASH:uWe,REGEX_SPECIAL_CHARS:dWe,REGEX_SPECIAL_CHARS_GLOBAL:fWe}=sw();ps.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ps.hasRegexChars=t=>dWe.test(t);ps.isRegexChar=t=>t.length===1&&ps.hasRegexChars(t);ps.escapeRegex=t=>t.replace(fWe,"\\$1");ps.toPosixSlashes=t=>t.replace(lWe,"/");ps.removeBackslashes=t=>t.replace(uWe,e=>e==="\\"?"":e);ps.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};ps.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:cWe===!0||aWe.sep==="\\";ps.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?ps.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};ps.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};ps.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var Zle=B((DCt,Qle)=>{"use strict";var Vle=zR(),{CHAR_ASTERISK:E2,CHAR_AT:pWe,CHAR_BACKWARD_SLASH:ow,CHAR_COMMA:hWe,CHAR_DOT:w2,CHAR_EXCLAMATION_MARK:S2,CHAR_FORWARD_SLASH:Jle,CHAR_LEFT_CURLY_BRACE:x2,CHAR_LEFT_PARENTHESES:b2,CHAR_LEFT_SQUARE_BRACKET:mWe,CHAR_PLUS:gWe,CHAR_QUESTION_MARK:zle,CHAR_RIGHT_CURLY_BRACE:yWe,CHAR_RIGHT_PARENTHESES:Kle,CHAR_RIGHT_SQUARE_BRACKET:_We}=sw(),Yle=t=>t===Jle||t===ow,Xle=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},vWe=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===!0||n.scanToEnd===!0,s=[],o=[],a=[],c=t,l=-1,u=0,d=0,f=!1,m=!1,g=!1,y=!1,w=!1,S=!1,T=!1,R=!1,C=!1,D=!1,$=0,G,V,L={value:"",depth:0,isGlob:!1},k=()=>l>=r,E=()=>c.charCodeAt(l+1),A=()=>(G=V,c.charCodeAt(++l));for(;l<r;){V=A();let X;if(V===ow){T=L.backslashes=!0,V=A(),V===x2&&(S=!0);continue}if(S===!0||V===x2){for($++;k()!==!0&&(V=A());){if(V===ow){T=L.backslashes=!0,A();continue}if(V===x2){$++;continue}if(S!==!0&&V===w2&&(V=A())===w2){if(f=L.isBrace=!0,g=L.isGlob=!0,D=!0,i===!0)continue;break}if(S!==!0&&V===hWe){if(f=L.isBrace=!0,g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===yWe&&($--,$===0)){S=!1,f=L.isBrace=!0,D=!0;break}}if(i===!0)continue;break}if(V===Jle){if(s.push(l),o.push(L),L={value:"",depth:0,isGlob:!1},D===!0)continue;if(G===w2&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(V===gWe||V===pWe||V===E2||V===zle||V===S2)===!0&&E()===b2){if(g=L.isGlob=!0,y=L.isExtglob=!0,D=!0,V===S2&&l===u&&(C=!0),i===!0){for(;k()!==!0&&(V=A());){if(V===ow){T=L.backslashes=!0,V=A();continue}if(V===Kle){g=L.isGlob=!0,D=!0;break}}continue}break}if(V===E2){if(G===E2&&(w=L.isGlobstar=!0),g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===zle){if(g=L.isGlob=!0,D=!0,i===!0)continue;break}if(V===mWe){for(;k()!==!0&&(X=A());){if(X===ow){T=L.backslashes=!0,A();continue}if(X===_We){m=L.isBracket=!0,g=L.isGlob=!0,D=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&V===S2&&l===u){R=L.negated=!0,u++;continue}if(n.noparen!==!0&&V===b2){if(g=L.isGlob=!0,i===!0){for(;k()!==!0&&(V=A());){if(V===b2){T=L.backslashes=!0,V=A();continue}if(V===Kle){D=!0;break}}continue}break}if(g===!0){if(D=!0,i===!0)continue;break}}n.noext===!0&&(y=!1,g=!1);let M=c,I="",P="";u>0&&(I=c.slice(0,u),c=c.slice(u),d-=u),M&&g===!0&&d>0?(M=c.slice(0,d),P=c.slice(d)):g===!0?(M="",P=c):M=c,M&&M!==""&&M!=="/"&&M!==c&&Yle(M.charCodeAt(M.length-1))&&(M=M.slice(0,-1)),n.unescape===!0&&(P&&(P=Vle.removeBackslashes(P)),M&&T===!0&&(M=Vle.removeBackslashes(M)));let F={prefix:I,input:t,start:u,base:M,glob:P,isBrace:f,isBracket:m,isGlob:g,isExtglob:y,isGlobstar:w,negated:R,negatedExtglob:C};if(n.tokens===!0&&(F.maxDepth=0,Yle(V)||o.push(L),F.tokens=o),n.parts===!0||n.tokens===!0){let X;for(let N=0;N<s.length;N++){let b=X?X+1:u,q=s[N],pe=t.slice(b,q);n.tokens&&(N===0&&u!==0?(o[N].isPrefix=!0,o[N].value=I):o[N].value=pe,Xle(o[N]),F.maxDepth+=o[N].depth),(N!==0||pe!=="")&&a.push(pe),X=q}if(X&&X+1<t.length){let N=t.slice(X+1);a.push(N),n.tokens&&(o[o.length-1].value=N,Xle(o[o.length-1]),F.maxDepth+=o[o.length-1].depth)}F.slashes=s,F.parts=a}return F};Qle.exports=vWe});var iue=B((LCt,rue)=>{"use strict";var aw=sw(),xi=zR(),{MAX_LENGTH:KR,POSIX_REGEX_SOURCE:EWe,REGEX_NON_SPECIAL_CHARS:wWe,REGEX_SPECIAL_CHARS_BACKREF:SWe,REPLACEMENTS:eue}=aw,xWe=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>xi.escapeRegex(i)).join("..")}return n},Xy=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,tue=t=>{let e=[],n=0,r=0,i=0,s="",o=!1;for(let a of t){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},bWe=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},nue=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(bWe(e))return e.replace(/\\(.)/g,"$1")},TWe=t=>{let e=t.map(nue).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},T2=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=!1;for(let o=1;o<t.length;o++){let a=t[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},AWe=t=>{let e=0,n=[];for(;e<t.length;){let i=T2(t.slice(e),!1);if(!i||i.type!=="*")return;let s=tue(i.body).map(a=>a.trim());if(s.length!==1)return;let o=nue(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?xi.escapeRegex(n[0]):`[${n.map(i=>xi.escapeRegex(i)).join("")}]`}*`},CWe=t=>{let e=0,n=t.trim(),r=T2(n);for(;r;)e++,n=r.body.trim(),r=T2(n);return e},RWe=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:aw.DEFAULT_MAX_EXTGLOB_RECURSION,r=tue(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||TWe(r)))return{risky:!0};for(let i of r){let s=AWe(i);if(s)return{risky:!0,safeOutput:s};if(CWe(i)>n)return{risky:!0}}return{risky:!1}},A2=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=eue[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(KR,n.maxLength):KR,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",c=xi.isWindows(e),l=aw.globChars(c),u=aw.extglobChars(l),{DOT_LITERAL:d,PLUS_LITERAL:f,SLASH_LITERAL:m,ONE_CHAR:g,DOTS_SLASH:y,NO_DOT:w,NO_DOT_SLASH:S,NO_DOTS_SLASH:T,QMARK:R,QMARK_NO_DOT:C,STAR:D,START_ANCHOR:$}=l,G=U=>`(${a}(?:(?!${$}${U.dot?y:d}).)*?)`,V=n.dot?"":w,L=n.dot?R:C,k=n.bash===!0?G(n):D;n.capture&&(k=`(${k})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let E={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=xi.removePrefix(t,E),i=t.length;let A=[],M=[],I=[],P=s,F,X=()=>E.index===i-1,N=E.peek=(U=1)=>t[E.index+U],b=E.advance=()=>t[++E.index]||"",q=()=>t.slice(E.index+1),pe=(U="",K=0)=>{E.consumed+=U,E.index+=K},oe=U=>{E.output+=U.output!=null?U.output:U.value,pe(U.value)},J=()=>{let U=1;for(;N()==="!"&&(N(2)!=="("||N(3)==="?");)b(),E.start++,U++;return U%2===0?!1:(E.negated=!0,E.start++,!0)},ve=U=>{E[U]++,I.push(U)},we=U=>{E[U]--,I.pop()},xe=U=>{if(P.type==="globstar"){let K=E.braces>0&&(U.type==="comma"||U.type==="brace"),j=U.extglob===!0||A.length&&(U.type==="pipe"||U.type==="paren");U.type!=="slash"&&U.type!=="paren"&&!K&&!j&&(E.output=E.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=k,E.output+=P.output)}if(A.length&&U.type!=="paren"&&(A[A.length-1].inner+=U.value),(U.value||U.output)&&oe(U),P&&P.type==="text"&&U.type==="text"){P.value+=U.value,P.output=(P.output||"")+U.value;return}U.prev=P,o.push(U),P=U},lt=(U,K)=>{let j={...u[K],conditions:1,inner:""};j.prev=P,j.parens=E.parens,j.output=E.output,j.startIndex=E.index,j.tokensIndex=o.length;let Q=(n.capture?"(":"")+j.open;ve("parens"),xe({type:U,value:K,output:E.output?"":g}),xe({type:"paren",extglob:!0,value:b(),output:Q}),A.push(j)},Ue=U=>{let K=t.slice(U.startIndex,E.index+1),j=t.slice(U.startIndex+2,E.index),Q=RWe(j,n);if((U.type==="plus"||U.type==="star")&&Q.risky){let ie=Q.safeOutput?(U.output?"":g)+(n.capture?`(${Q.safeOutput})`:Q.safeOutput):void 0,ne=o[U.tokensIndex];ne.type="text",ne.value=K,ne.output=ie||xi.escapeRegex(K);for(let re=U.tokensIndex+1;re<o.length;re++)o[re].value="",o[re].output="",delete o[re].suffix;E.output=U.output+ne.output,E.backtrack=!0,xe({type:"paren",extglob:!0,value:F,output:""}),we("parens");return}let Z=U.close+(n.capture?")":""),ee;if(U.type==="negate"){let ie=k;if(U.inner&&U.inner.length>1&&U.inner.includes("/")&&(ie=G(n)),(ie!==k||X()||/^\)+$/.test(q()))&&(Z=U.close=`)$))${ie}`),U.inner.includes("*")&&(ee=q())&&/^\.[^\\/.]+$/.test(ee)){let ne=A2(ee,{...e,fastpaths:!1}).output;Z=U.close=`)${ne})${ie})`}U.prev.type==="bos"&&(E.negatedExtglob=!0)}xe({type:"paren",extglob:!0,value:F,output:Z}),we("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let U=!1,K=t.replace(SWe,(j,Q,Z,ee,ie,ne)=>ee==="\\"?(U=!0,j):ee==="?"?Q?Q+ee+(ie?R.repeat(ie.length):""):ne===0?L+(ie?R.repeat(ie.length):""):R.repeat(Z.length):ee==="."?d.repeat(Z.length):ee==="*"?Q?Q+ee+(ie?k:""):k:Q?j:`\\${j}`);return U===!0&&(n.unescape===!0?K=K.replace(/\\/g,""):K=K.replace(/\\+/g,j=>j.length%2===0?"\\\\":j?"\\":"")),K===t&&n.contains===!0?(E.output=t,E):(E.output=xi.wrapOutput(K,E,e),E)}for(;!X();){if(F=b(),F==="\0")continue;if(F==="\\"){let j=N();if(j==="/"&&n.bash!==!0||j==="."||j===";")continue;if(!j){F+="\\",xe({type:"text",value:F});continue}let Q=/^\\+/.exec(q()),Z=0;if(Q&&Q[0].length>2&&(Z=Q[0].length,E.index+=Z,Z%2!==0&&(F+="\\")),n.unescape===!0?F=b():F+=b(),E.brackets===0){xe({type:"text",value:F});continue}}if(E.brackets>0&&(F!=="]"||P.value==="["||P.value==="[^")){if(n.posix!==!1&&F===":"){let j=P.value.slice(1);if(j.includes("[")&&(P.posix=!0,j.includes(":"))){let Q=P.value.lastIndexOf("["),Z=P.value.slice(0,Q),ee=P.value.slice(Q+2),ie=EWe[ee];if(ie){P.value=Z+ie,E.backtrack=!0,b(),!s.output&&o.indexOf(P)===1&&(s.output=g);continue}}}(F==="["&&N()!==":"||F==="-"&&N()==="]")&&(F=`\\${F}`),F==="]"&&(P.value==="["||P.value==="[^")&&(F=`\\${F}`),n.posix===!0&&F==="!"&&P.value==="["&&(F="^"),P.value+=F,oe({value:F});continue}if(E.quotes===1&&F!=='"'){F=xi.escapeRegex(F),P.value+=F,oe({value:F});continue}if(F==='"'){E.quotes=E.quotes===1?0:1,n.keepQuotes===!0&&xe({type:"text",value:F});continue}if(F==="("){ve("parens"),xe({type:"paren",value:F});continue}if(F===")"){if(E.parens===0&&n.strictBrackets===!0)throw new SyntaxError(Xy("opening","("));let j=A[A.length-1];if(j&&E.parens===j.parens+1){Ue(A.pop());continue}xe({type:"paren",value:F,output:E.parens?")":"\\)"}),we("parens");continue}if(F==="["){if(n.nobracket===!0||!q().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(Xy("closing","]"));F=`\\${F}`}else ve("brackets");xe({type:"bracket",value:F});continue}if(F==="]"){if(n.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){xe({type:"text",value:F,output:`\\${F}`});continue}if(E.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(Xy("opening","["));xe({type:"text",value:F,output:`\\${F}`});continue}we("brackets");let j=P.value.slice(1);if(P.posix!==!0&&j[0]==="^"&&!j.includes("/")&&(F=`/${F}`),P.value+=F,oe({value:F}),n.literalBrackets===!1||xi.hasRegexChars(j))continue;let Q=xi.escapeRegex(P.value);if(E.output=E.output.slice(0,-P.value.length),n.literalBrackets===!0){E.output+=Q,P.value=Q;continue}P.value=`(${a}${Q}|${P.value})`,E.output+=P.value;continue}if(F==="{"&&n.nobrace!==!0){ve("braces");let j={type:"brace",value:F,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};M.push(j),xe(j);continue}if(F==="}"){let j=M[M.length-1];if(n.nobrace===!0||!j){xe({type:"text",value:F,output:F});continue}let Q=")";if(j.dots===!0){let Z=o.slice(),ee=[];for(let ie=Z.length-1;ie>=0&&(o.pop(),Z[ie].type!=="brace");ie--)Z[ie].type!=="dots"&&ee.unshift(Z[ie].value);Q=xWe(ee,n),E.backtrack=!0}if(j.comma!==!0&&j.dots!==!0){let Z=E.output.slice(0,j.outputIndex),ee=E.tokens.slice(j.tokensIndex);j.value=j.output="\\{",F=Q="\\}",E.output=Z;for(let ie of ee)E.output+=ie.output||ie.value}xe({type:"brace",value:F,output:Q}),we("braces"),M.pop();continue}if(F==="|"){A.length>0&&A[A.length-1].conditions++,xe({type:"text",value:F});continue}if(F===","){let j=F,Q=M[M.length-1];Q&&I[I.length-1]==="braces"&&(Q.comma=!0,j="|"),xe({type:"comma",value:F,output:j});continue}if(F==="/"){if(P.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",o.pop(),P=s;continue}xe({type:"slash",value:F,output:m});continue}if(F==="."){if(E.braces>0&&P.type==="dot"){P.value==="."&&(P.output=d);let j=M[M.length-1];P.type="dots",P.output+=F,P.value+=F,j.dots=!0;continue}if(E.braces+E.parens===0&&P.type!=="bos"&&P.type!=="slash"){xe({type:"text",value:F,output:d});continue}xe({type:"dot",value:F,output:d});continue}if(F==="?"){if(!(P&&P.value==="(")&&n.noextglob!==!0&&N()==="("&&N(2)!=="?"){lt("qmark",F);continue}if(P&&P.type==="paren"){let Q=N(),Z=F;if(Q==="<"&&!xi.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(P.value==="("&&!/[!=<:]/.test(Q)||Q==="<"&&!/<([!=]|\w+>)/.test(q()))&&(Z=`\\${F}`),xe({type:"text",value:F,output:Z});continue}if(n.dot!==!0&&(P.type==="slash"||P.type==="bos")){xe({type:"qmark",value:F,output:C});continue}xe({type:"qmark",value:F,output:R});continue}if(F==="!"){if(n.noextglob!==!0&&N()==="("&&(N(2)!=="?"||!/[!=<:]/.test(N(3)))){lt("negate",F);continue}if(n.nonegate!==!0&&E.index===0){J();continue}}if(F==="+"){if(n.noextglob!==!0&&N()==="("&&N(2)!=="?"){lt("plus",F);continue}if(P&&P.value==="("||n.regex===!1){xe({type:"plus",value:F,output:f});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||E.parens>0){xe({type:"plus",value:F});continue}xe({type:"plus",value:f});continue}if(F==="@"){if(n.noextglob!==!0&&N()==="("&&N(2)!=="?"){xe({type:"at",extglob:!0,value:F,output:""});continue}xe({type:"text",value:F});continue}if(F!=="*"){(F==="$"||F==="^")&&(F=`\\${F}`);let j=wWe.exec(q());j&&(F+=j[0],E.index+=j[0].length),xe({type:"text",value:F});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=F,P.output=k,E.backtrack=!0,E.globstar=!0,pe(F);continue}let U=q();if(n.noextglob!==!0&&/^\([^?]/.test(U)){lt("star",F);continue}if(P.type==="star"){if(n.noglobstar===!0){pe(F);continue}let j=P.prev,Q=j.prev,Z=j.type==="slash"||j.type==="bos",ee=Q&&(Q.type==="star"||Q.type==="globstar");if(n.bash===!0&&(!Z||U[0]&&U[0]!=="/")){xe({type:"star",value:F,output:""});continue}let ie=E.braces>0&&(j.type==="comma"||j.type==="brace"),ne=A.length&&(j.type==="pipe"||j.type==="paren");if(!Z&&j.type!=="paren"&&!ie&&!ne){xe({type:"star",value:F,output:""});continue}for(;U.slice(0,3)==="/**";){let re=t[E.index+4];if(re&&re!=="/")break;U=U.slice(3),pe("/**",3)}if(j.type==="bos"&&X()){P.type="globstar",P.value+=F,P.output=G(n),E.output=P.output,E.globstar=!0,pe(F);continue}if(j.type==="slash"&&j.prev.type!=="bos"&&!ee&&X()){E.output=E.output.slice(0,-(j.output+P.output).length),j.output=`(?:${j.output}`,P.type="globstar",P.output=G(n)+(n.strictSlashes?")":"|$)"),P.value+=F,E.globstar=!0,E.output+=j.output+P.output,pe(F);continue}if(j.type==="slash"&&j.prev.type!=="bos"&&U[0]==="/"){let re=U[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(j.output+P.output).length),j.output=`(?:${j.output}`,P.type="globstar",P.output=`${G(n)}${m}|${m}${re})`,P.value+=F,E.output+=j.output+P.output,E.globstar=!0,pe(F+b()),xe({type:"slash",value:"/",output:""});continue}if(j.type==="bos"&&U[0]==="/"){P.type="globstar",P.value+=F,P.output=`(?:^|${m}|${G(n)}${m})`,E.output=P.output,E.globstar=!0,pe(F+b()),xe({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-P.output.length),P.type="globstar",P.output=G(n),P.value+=F,E.output+=P.output,E.globstar=!0,pe(F);continue}let K={type:"star",value:F,output:k};if(n.bash===!0){K.output=".*?",(P.type==="bos"||P.type==="slash")&&(K.output=V+K.output),xe(K);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&n.regex===!0){K.output=F,xe(K);continue}(E.index===E.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(E.output+=S,P.output+=S):n.dot===!0?(E.output+=T,P.output+=T):(E.output+=V,P.output+=V),N()!=="*"&&(E.output+=g,P.output+=g)),xe(K)}for(;E.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing","]"));E.output=xi.escapeLast(E.output,"["),we("brackets")}for(;E.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing",")"));E.output=xi.escapeLast(E.output,"("),we("parens")}for(;E.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(Xy("closing","}"));E.output=xi.escapeLast(E.output,"{"),we("braces")}if(n.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&xe({type:"maybe_slash",value:"",output:`${m}?`}),E.backtrack===!0){E.output="";for(let U of E.tokens)E.output+=U.output!=null?U.output:U.value,U.suffix&&(E.output+=U.suffix)}return E};A2.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(KR,n.maxLength):KR,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=eue[t]||t;let s=xi.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:f,STAR:m,START_ANCHOR:g}=aw.globChars(s),y=n.dot?d:u,w=n.dot?f:u,S=n.capture?"":"?:",T={negated:!1,prefix:""},R=n.bash===!0?".*?":m;n.capture&&(R=`(${R})`);let C=V=>V.noglobstar===!0?R:`(${S}(?:(?!${g}${V.dot?l:o}).)*?)`,D=V=>{switch(V){case"*":return`${y}${c}${R}`;case".*":return`${o}${c}${R}`;case"*.*":return`${y}${R}${o}${c}${R}`;case"*/*":return`${y}${R}${a}${c}${w}${R}`;case"**":return y+C(n);case"**/*":return`(?:${y}${C(n)}${a})?${w}${c}${R}`;case"**/*.*":return`(?:${y}${C(n)}${a})?${w}${R}${o}${c}${R}`;case"**/.*":return`(?:${y}${C(n)}${a})?${o}${c}${R}`;default:{let L=/^(.*?)\.(\w+)$/.exec(V);if(!L)return;let k=D(L[1]);return k?k+o+L[2]:void 0}}},$=xi.removePrefix(t,T),G=D($);return G&&n.strictSlashes!==!0&&(G+=`${a}?`),G};rue.exports=A2});var oue=B((UCt,sue)=>{"use strict";var IWe=require("path"),kWe=Zle(),C2=iue(),R2=zR(),PWe=sw(),OWe=t=>t&&typeof t=="object"&&!Array.isArray(t),hr=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(f=>hr(f,e,n));return f=>{for(let m of u){let g=m(f);if(g)return g}return!1}}let r=OWe(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=R2.isWindows(e),o=r?hr.compileRe(t,e):hr.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=hr(i.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:f,match:m,output:g}=hr.test(u,o,e,{glob:t,posix:s}),y={glob:t,state:a,regex:o,posix:s,input:u,output:g,match:m,isMatch:f};return typeof i.onResult=="function"&&i.onResult(y),f===!1?(y.isMatch=!1,d?y:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(y),y.isMatch=!1,d?y:!1):(typeof i.onMatch=="function"&&i.onMatch(y),d?y:!0)};return n&&(l.state=a),l};hr.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=n||{},o=s.format||(i?R2.toPosixSlashes:null),a=t===r,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===r),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=hr.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};hr.matchBase=(t,e,n,r=R2.isWindows(n))=>(e instanceof RegExp?e:hr.makeRe(e,n)).test(IWe.basename(t));hr.isMatch=(t,e,n)=>hr(e,n)(t);hr.parse=(t,e)=>Array.isArray(t)?t.map(n=>hr.parse(n,e)):C2(t,{...e,fastpaths:!1});hr.scan=(t,e)=>kWe(t,e);hr.compileRe=(t,e,n=!1,r=!1)=>{if(n===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=hr.toRegex(a,e);return r===!0&&(c.state=t),c};hr.makeRe=(t,e={},n=!1,r=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=C2.fastpaths(t,e)),i.output||(i=C2(t,e)),hr.compileRe(i,e,n,r)};hr.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};hr.constants=PWe;sue.exports=hr});var I2=B((FCt,aue)=>{"use strict";aue.exports=oue()});var mue=B((BCt,hue)=>{"use strict";var lw=require("fs"),{Readable:MWe}=require("stream"),cw=require("path"),{promisify:QR}=require("util"),k2=I2(),NWe=QR(lw.readdir),DWe=QR(lw.stat),cue=QR(lw.lstat),LWe=QR(lw.realpath),UWe="!",fue="READDIRP_RECURSIVE_ERROR",FWe=new Set(["ENOENT","EPERM","EACCES","ELOOP",fue]),P2="files",pue="directories",XR="files_directories",YR="all",lue=[P2,pue,XR,YR],BWe=t=>FWe.has(t.code),[uue,qWe]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),$We=process.platform==="win32"&&(uue>10||uue===10&&qWe>=5),due=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=k2(t.trim());return n=>e(n.basename)}if(Array.isArray(t)){let e=[],n=[];for(let r of t){let i=r.trim();i.charAt(0)===UWe?n.push(k2(i.slice(1))):e.push(k2(i))}return n.length>0?e.length>0?r=>e.some(i=>i(r.basename))&&!n.some(i=>i(r.basename)):r=>!n.some(i=>i(r.basename)):r=>e.some(i=>i(r.basename))}}},JR=class t extends MWe{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:P2,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let n={...t.defaultOptions,...e},{root:r,type:i}=n;this._fileFilter=due(n.fileFilter),this._directoryFilter=due(n.directoryFilter);let s=n.lstat?cue:DWe;$We?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth,this._wantsDir=[pue,XR,YR].includes(i),this._wantsFile=[P2,XR,YR].includes(i),this._wantsEverything=i===YR,this._root=cw.resolve(r),this._isDirent="Dirent"in lw&&!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:n,depth:r,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,n));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await NWe(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}async _formatEntry(e,n){let r;try{let i=this._isDirent?e.name:e,s=cw.resolve(cw.join(n,i));r={path:cw.relative(this._root,s),fullPath:s,basename:i},r[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return r}_onError(e){BWe(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let n=e&&e[this._statsProp];if(n){if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let r=e.fullPath;try{let i=await LWe(r),s=await cue(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(r.startsWith(i)&&r.substr(o,1)===cw.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${i}"`);return a.code=fue,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}},Jy=(t,e={})=>{let n=e.entryType||e.type;if(n==="both"&&(n=XR),n&&(e.type=n),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!lue.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${lue.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new JR(e)},GWe=(t,e={})=>new Promise((n,r)=>{let i=[];Jy(t,e).on("data",s=>i.push(s)).on("end",()=>n(i)).on("error",s=>r(s))});Jy.promise=GWe;Jy.ReaddirpStream=JR;Jy.default=Jy;hue.exports=Jy});var Qy=B((qCt,gue)=>{gue.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var n=t.length;if(n<=1)return t;var r="";if(n>4&&t[3]==="\\"){var i=t[2];(i==="?"||i===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),r="//")}var s=t.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),r+s.join("/")}});var Sue=B((Eue,wue)=>{"use strict";Object.defineProperty(Eue,"__esModule",{value:!0});var vue=I2(),HWe=Qy(),yue="!",jWe={returnIndex:!1},WWe=t=>Array.isArray(t)?t:[t],VWe=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let n=vue(t,e);return r=>t===r||n(r)}return t instanceof RegExp?n=>t.test(n):n=>!1},_ue=(t,e,n,r)=>{let i=Array.isArray(n),s=i?n[0]:n;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=HWe(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return r?-1:!1}let a=i&&[o].concat(n.slice(1));for(let c=0;c<t.length;c++){let l=t[c];if(i?l(...a):l(o))return r?c:!0}return r?-1:!1},O2=(t,e,n=jWe)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let r=typeof n=="boolean"?{returnIndex:n}:n,i=r.returnIndex||!1,s=WWe(t),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===yue).map(c=>c.slice(1)).map(c=>vue(c,r)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==yue).map(c=>VWe(c,r));return e==null?(c,l=!1)=>_ue(a,o,c,typeof l=="boolean"?l:!1):_ue(a,o,e,i)};O2.default=O2;wue.exports=O2});var bue=B(($Ct,xue)=>{xue.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var M2=B((GCt,Aue)=>{var zWe=bue(),Tue={"{":"}","(":")","[":"]"},KWe=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,r=-2,i=-2,s=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||r!==-1&&t[e]==="["&&t[e+1]!=="]"&&(r<e&&(r=t.indexOf("]",e)),r>e&&(o===-1||o>r||(o=t.indexOf("\\",e),o===-1||o>r)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(s=t.indexOf(")",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(s=t.indexOf(")",n),s>n&&(o=t.indexOf("\\",n),o===-1||o>s))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=Tue[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},YWe=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var r=Tue[n];if(r){var i=t.indexOf(r,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};Aue.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(zWe(e))return!0;var r=KWe;return n&&n.strict===!1&&(r=YWe),r(e)}});var Rue=B((HCt,Cue)=>{"use strict";var XWe=M2(),JWe=require("path").posix.dirname,QWe=require("os").platform()==="win32",N2="/",ZWe=/\\/g,e6e=/[\{\[].*[\}\]]$/,t6e=/(^|[^\\])([\{\[]|\([^\)]+$)/,n6e=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Cue.exports=function(e,n){var r=Object.assign({flipBackslashes:!0},n);r.flipBackslashes&&QWe&&e.indexOf(N2)<0&&(e=e.replace(ZWe,N2)),e6e.test(e)&&(e+=N2),e+="a";do e=JWe(e);while(XWe(e)||t6e.test(e));return e.replace(n6e,"$1")}});var ZR=B($o=>{"use strict";$o.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;$o.find=(t,e)=>t.nodes.find(n=>n.type===e);$o.exceedsLimit=(t,e,n=1,r)=>r===!1||!$o.isInteger(t)||!$o.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=r;$o.escapeNode=(t,e=0,n)=>{let r=t.nodes[e];r&&(n&&r.type===n||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};$o.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;$o.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;$o.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;$o.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);$o.flatten=(...t)=>{let e=[],n=r=>{for(let i=0;i<r.length;i++){let s=r[i];if(Array.isArray(s)){n(s);continue}s!==void 0&&e.push(s)}return e};return n(t),e}});var eI=B((WCt,kue)=>{"use strict";var Iue=ZR();kue.exports=(t,e={})=>{let n=(r,i={})=>{let s=e.escapeInvalid&&Iue.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(s||o)&&Iue.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let c of r.nodes)a+=n(c);return a};return n(t)}});var Oue=B((VCt,Pue)=>{"use strict";Pue.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var $ue=B((zCt,que)=>{"use strict";var Mue=Oue(),Ph=(t,e,n)=>{if(Mue(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Mue(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...n};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let i=String(r.relaxZeros),s=String(r.shorthand),o=String(r.capture),a=String(r.wrap),c=t+":"+e+"="+i+s+o+a;if(Ph.cache.hasOwnProperty(c))return Ph.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let y=t+"|"+e;return r.capture?`(${y})`:r.wrap===!1?y:`(?:${y})`}let d=Bue(t)||Bue(e),f={min:t,max:e,a:l,b:u},m=[],g=[];if(d&&(f.isPadded=d,f.maxLen=String(f.max).length),l<0){let y=u<0?Math.abs(u):1;g=Nue(y,Math.abs(l),f,r),l=f.a=0}return u>=0&&(m=Nue(l,u,f,r)),f.negatives=g,f.positives=m,f.result=r6e(g,m,r),r.capture===!0?f.result=`(${f.result})`:r.wrap!==!1&&m.length+g.length>1&&(f.result=`(?:${f.result})`),Ph.cache[c]=f,f.result};function r6e(t,e,n){let r=D2(t,e,"-",!1,n)||[],i=D2(e,t,"",!1,n)||[],s=D2(t,e,"-?",!0,n)||[];return r.concat(s).concat(i).join("|")}function i6e(t,e){let n=1,r=1,i=Lue(t,n),s=new Set([e]);for(;t<=i&&i<=e;)s.add(i),n+=1,i=Lue(t,n);for(i=Uue(e+1,r)-1;t<i&&i<=e;)s.add(i),r+=1,i=Uue(e+1,r)-1;return s=[...s],s.sort(a6e),s}function s6e(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let r=o6e(t,e),i=r.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=r[a];c===l?s+=c:c!=="0"||l!=="9"?s+=c6e(c,l,n):o++}return o&&(s+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function Nue(t,e,n,r){let i=i6e(t,e),s=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=s6e(String(o),String(l),r),d="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Fue(a.count),o=l+1;continue}n.isPadded&&(d=l6e(l,n,r)),u.string=d+u.pattern+Fue(u.count),s.push(u),o=l+1,a=u}return s}function D2(t,e,n,r,i){let s=[];for(let o of t){let{string:a}=o;!r&&!Due(e,"string",a)&&s.push(n+a),r&&Due(e,"string",a)&&s.push(n+a)}return s}function o6e(t,e){let n=[];for(let r=0;r<t.length;r++)n.push([t[r],e[r]]);return n}function a6e(t,e){return t>e?1:e>t?-1:0}function Due(t,e,n){return t.some(r=>r[e]===n)}function Lue(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Uue(t,e){return t-t%Math.pow(10,e)}function Fue(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function c6e(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Bue(t){return/^-?(0+)\d/.test(t)}function l6e(t,e,n){if(!e.isPadded)return t;let r=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(r){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${r}}`:`0{${r}}`}}Ph.cache={};Ph.clearCache=()=>Ph.cache={};que.exports=Ph});var F2=B((KCt,Kue)=>{"use strict";var u6e=require("util"),Hue=$ue(),Gue=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),d6e=t=>e=>t===!0?Number(e):String(e),L2=t=>typeof t=="number"||typeof t=="string"&&t!=="",uw=t=>Number.isInteger(+t),U2=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},f6e=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,p6e=(t,e,n)=>{if(e>0){let r=t[0]==="-"?"-":"";r&&(t=t.slice(1)),t=r+t.padStart(r?e-1:e,"0")}return n===!1?String(t):t},nI=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},h6e=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let r=e.capture?"":"?:",i="",s="",o;return t.positives.length&&(i=t.positives.map(a=>nI(String(a),n)).join("|")),t.negatives.length&&(s=`-(${r}${t.negatives.map(a=>nI(String(a),n)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${r}${o})`:o},jue=(t,e,n,r)=>{if(n)return Hue(t,e,{wrap:!1,...r});let i=String.fromCharCode(t);if(t===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},Wue=(t,e,n)=>{if(Array.isArray(t)){let r=n.wrap===!0,i=n.capture?"":"?:";return r?`(${i}${t.join("|")})`:t.join("|")}return Hue(t,e,n)},Vue=(...t)=>new RangeError("Invalid range arguments: "+u6e.inspect(...t)),zue=(t,e,n)=>{if(n.strictRanges===!0)throw Vue([t,e]);return[]},m6e=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},g6e=(t,e,n=1,r={})=>{let i=Number(t),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(r.strictRanges===!0)throw Vue([t,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=U2(a)||U2(c)||U2(l),d=u?Math.max(a.length,c.length,l.length):0,f=u===!1&&f6e(t,e,r)===!1,m=r.transform||d6e(f);if(r.toRegex&&n===1)return jue(nI(t,d),nI(e,d),!0,r);let g={negatives:[],positives:[]},y=T=>g[T<0?"negatives":"positives"].push(Math.abs(T)),w=[],S=0;for(;o?i>=s:i<=s;)r.toRegex===!0&&n>1?y(i):w.push(p6e(m(i,S),d,f)),i=o?i-n:i+n,S++;return r.toRegex===!0?n>1?h6e(g,r,d):Wue(w,null,{wrap:!1,...r}):w},y6e=(t,e,n=1,r={})=>{if(!uw(t)&&t.length>1||!uw(e)&&e.length>1)return zue(t,e,r);let i=r.transform||(f=>String.fromCharCode(f)),s=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(r.toRegex&&n===1)return jue(c,l,!1,r);let u=[],d=0;for(;a?s>=o:s<=o;)u.push(i(s,d)),s=a?s-n:s+n,d++;return r.toRegex===!0?Wue(u,null,{wrap:!1,options:r}):u},tI=(t,e,n,r={})=>{if(e==null&&L2(t))return[t];if(!L2(t)||!L2(e))return zue(t,e,r);if(typeof n=="function")return tI(t,e,1,{transform:n});if(Gue(n))return tI(t,e,0,n);let i={...r};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,uw(n)?uw(t)&&uw(e)?g6e(t,e,n,i):y6e(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Gue(n)?m6e(n,i):tI(t,e,1,n)};Kue.exports=tI});var Jue=B((YCt,Xue)=>{"use strict";var _6e=F2(),Yue=ZR(),v6e=(t,e={})=>{let n=(r,i={})=>{let s=Yue.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(r.isOpen===!0)return c+r.value;if(r.isClose===!0)return console.log("node.isClose",c,r.value),c+r.value;if(r.type==="open")return a?c+r.value:"(";if(r.type==="close")return a?c+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=Yue.reduce(r.nodes),d=_6e(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)l+=n(u,r);return l};return n(t)};Xue.exports=v6e});var ede=B((XCt,Zue)=>{"use strict";var E6e=F2(),Que=eI(),Zy=ZR(),Oh=(t="",e="",n=!1)=>{let r=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?Zy.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let s of i)r.push(Oh(s,e,n));else for(let s of e)n===!0&&typeof s=="string"&&(s=`{${s}}`),r.push(Array.isArray(s)?Oh(i,s,n):i+s);return Zy.flatten(r)},w6e=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(Oh(a.pop(),Que(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Oh(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let d=Zy.reduce(i.nodes);if(Zy.exceedsLimit(...d,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=E6e(...d,e);f.length===0&&(f=Que(i,e)),a.push(Oh(a.pop(),f)),i.nodes=[];return}let c=Zy.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let d=0;d<i.nodes.length;d++){let f=i.nodes[d];if(f.type==="comma"&&i.type==="brace"){d===1&&l.push(""),l.push("");continue}if(f.type==="close"){a.push(Oh(a.pop(),l,c));continue}if(f.value&&f.type!=="open"){l.push(Oh(l.pop(),f.value));continue}f.nodes&&r(f,i)}return l};return Zy.flatten(r(t))};Zue.exports=w6e});var nde=B((JCt,tde)=>{"use strict";tde.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
413
413
  `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var ade=B((QCt,ode)=>{"use strict";var S6e=eI(),{MAX_LENGTH:rde,CHAR_BACKSLASH:B2,CHAR_BACKTICK:x6e,CHAR_COMMA:b6e,CHAR_DOT:T6e,CHAR_LEFT_PARENTHESES:A6e,CHAR_RIGHT_PARENTHESES:C6e,CHAR_LEFT_CURLY_BRACE:R6e,CHAR_RIGHT_CURLY_BRACE:I6e,CHAR_LEFT_SQUARE_BRACKET:ide,CHAR_RIGHT_SQUARE_BRACKET:sde,CHAR_DOUBLE_QUOTE:k6e,CHAR_SINGLE_QUOTE:P6e,CHAR_NO_BREAK_SPACE:O6e,CHAR_ZERO_WIDTH_NOBREAK_SPACE:M6e}=nde(),N6e=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},r=typeof n.maxLength=="number"?Math.min(rde,n.maxLength):rde;if(t.length>r)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${r})`);let i={type:"root",input:t,nodes:[]},s=[i],o=i,a=i,c=0,l=t.length,u=0,d=0,f,m=()=>t[u++],g=y=>{if(y.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&y.type==="text"){a.value+=y.value;return}return o.nodes.push(y),y.parent=o,y.prev=a,a=y,y};for(g({type:"bos"});u<l;)if(o=s[s.length-1],f=m(),!(f===M6e||f===O6e)){if(f===B2){g({type:"text",value:(e.keepEscaping?f:"")+m()});continue}if(f===sde){g({type:"text",value:"\\"+f});continue}if(f===ide){c++;let y;for(;u<l&&(y=m());){if(f+=y,y===ide){c++;continue}if(y===B2){f+=m();continue}if(y===sde&&(c--,c===0))break}g({type:"text",value:f});continue}if(f===A6e){o=g({type:"paren",nodes:[]}),s.push(o),g({type:"text",value:f});continue}if(f===C6e){if(o.type!=="paren"){g({type:"text",value:f});continue}o=s.pop(),g({type:"text",value:f}),o=s[s.length-1];continue}if(f===k6e||f===P6e||f===x6e){let y=f,w;for(e.keepQuotes!==!0&&(f="");u<l&&(w=m());){if(w===B2){f+=w+m();continue}if(w===y){e.keepQuotes===!0&&(f+=w);break}f+=w}g({type:"text",value:f});continue}if(f===R6e){d++;let w={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=g(w),s.push(o),g({type:"open",value:f});continue}if(f===I6e){if(o.type!=="brace"){g({type:"text",value:f});continue}let y="close";o=s.pop(),o.close=!0,g({type:y,value:f}),d--,o=s[s.length-1];continue}if(f===b6e&&d>0){if(o.ranges>0){o.ranges=0;let y=o.nodes.shift();o.nodes=[y,{type:"text",value:S6e(o)}]}g({type:"comma",value:f}),o.commas++;continue}if(f===T6e&&d>0&&o.commas===0){let y=o.nodes;if(d===0||y.length===0){g({type:"text",value:f});continue}if(a.type==="dot"){if(o.range=[],a.value+=f,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){y.pop();let w=y[y.length-1];w.value+=a.value+f,a=w,o.ranges--;continue}g({type:"dot",value:f});continue}g({type:"text",value:f})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(S=>{S.nodes||(S.type==="open"&&(S.isOpen=!0),S.type==="close"&&(S.isClose=!0),S.nodes||(S.type="text"),S.invalid=!0)});let y=s[s.length-1],w=y.nodes.indexOf(o);y.nodes.splice(w,1,...o.nodes)}while(s.length>0);return g({type:"eos"}),i};ode.exports=N6e});var ude=B((ZCt,lde)=>{"use strict";var cde=eI(),D6e=Jue(),L6e=ede(),U6e=ade(),js=(t,e={})=>{let n=[];if(Array.isArray(t))for(let r of t){let i=js.create(r,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(js.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};js.parse=(t,e={})=>U6e(t,e);js.stringify=(t,e={})=>cde(typeof t=="string"?js.parse(t,e):t,e);js.compile=(t,e={})=>(typeof t=="string"&&(t=js.parse(t,e)),D6e(t,e));js.expand=(t,e={})=>{typeof t=="string"&&(t=js.parse(t,e));let n=L6e(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};js.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?js.compile(t,e):js.expand(t,e);lde.exports=js});var dde=B((eRt,F6e)=>{F6e.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var pde=B((tRt,fde)=>{fde.exports=dde()});var mde=B((nRt,hde)=>{"use strict";var B6e=require("path"),q6e=pde(),$6e=new Set(q6e);hde.exports=t=>$6e.has(B6e.extname(t).slice(1).toLowerCase())});var rI=B(qe=>{"use strict";var{sep:G6e}=require("path"),{platform:q2}=process,H6e=require("os");qe.EV_ALL="all";qe.EV_READY="ready";qe.EV_ADD="add";qe.EV_CHANGE="change";qe.EV_ADD_DIR="addDir";qe.EV_UNLINK="unlink";qe.EV_UNLINK_DIR="unlinkDir";qe.EV_RAW="raw";qe.EV_ERROR="error";qe.STR_DATA="data";qe.STR_END="end";qe.STR_CLOSE="close";qe.FSEVENT_CREATED="created";qe.FSEVENT_MODIFIED="modified";qe.FSEVENT_DELETED="deleted";qe.FSEVENT_MOVED="moved";qe.FSEVENT_CLONED="cloned";qe.FSEVENT_UNKNOWN="unknown";qe.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;qe.FSEVENT_TYPE_FILE="file";qe.FSEVENT_TYPE_DIRECTORY="directory";qe.FSEVENT_TYPE_SYMLINK="symlink";qe.KEY_LISTENERS="listeners";qe.KEY_ERR="errHandlers";qe.KEY_RAW="rawEmitters";qe.HANDLER_KEYS=[qe.KEY_LISTENERS,qe.KEY_ERR,qe.KEY_RAW];qe.DOT_SLASH=`.${G6e}`;qe.BACK_SLASH_RE=/\\/g;qe.DOUBLE_SLASH_RE=/\/\//;qe.SLASH_OR_BACK_SLASH_RE=/[/\\]/;qe.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;qe.REPLACER_RE=/^\.[/\\]/;qe.SLASH="/";qe.SLASH_SLASH="//";qe.BRACE_START="{";qe.BANG="!";qe.ONE_DOT=".";qe.TWO_DOTS="..";qe.STAR="*";qe.GLOBSTAR="**";qe.ROOT_GLOBSTAR="/**/*";qe.SLASH_GLOBSTAR="/**";qe.DIR_SUFFIX="Dir";qe.ANYMATCH_OPTS={dot:!0};qe.STRING_TYPE="string";qe.FUNCTION_TYPE="function";qe.EMPTY_STR="";qe.EMPTY_FN=()=>{};qe.IDENTITY_FN=t=>t;qe.isWindows=q2==="win32";qe.isMacos=q2==="darwin";qe.isLinux=q2==="linux";qe.isIBMi=H6e.type()==="OS400"});var wde=B((iRt,Ede)=>{"use strict";var Eu=require("fs"),Vr=require("path"),{promisify:hw}=require("util"),j6e=mde(),{isWindows:W6e,isLinux:V6e,EMPTY_FN:z6e,EMPTY_STR:K6e,KEY_LISTENERS:e_,KEY_ERR:$2,KEY_RAW:dw,HANDLER_KEYS:Y6e,EV_CHANGE:sI,EV_ADD:iI,EV_ADD_DIR:X6e,EV_ERROR:yde,STR_DATA:J6e,STR_END:Q6e,BRACE_START:Z6e,STAR:eVe}=rI(),tVe="watch",nVe=hw(Eu.open),_de=hw(Eu.stat),rVe=hw(Eu.lstat),iVe=hw(Eu.close),G2=hw(Eu.realpath),sVe={lstat:rVe,stat:_de},j2=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},fw=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},oVe=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},pw=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},vde=t=>t instanceof Set?t.size===0:!t,oI=new Map;function gde(t,e,n,r,i){let s=(o,a)=>{n(t),i(o,a,{watchedPath:t}),a&&t!==a&&aI(Vr.resolve(t,a),e_,Vr.join(t,a))};try{return Eu.watch(t,e,s)}catch(o){r(o)}}var aI=(t,e,n,r,i)=>{let s=oI.get(t);s&&j2(s[e],o=>{o(n,r,i)})},aVe=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:o}=r,a=oI.get(e),c;if(!n.persistent)return c=gde(t,n,i,s,o),c.close.bind(c);if(a)fw(a,e_,i),fw(a,$2,s),fw(a,dw,o);else{if(c=gde(t,n,aI.bind(null,e,e_),s,aI.bind(null,e,dw)),!c)return;c.on(yde,async l=>{let u=aI.bind(null,e,$2);if(a.watcherUnusable=!0,W6e&&l.code==="EPERM")try{let d=await nVe(t,"r");await iVe(d),u(l)}catch{}else u(l)}),a={listeners:i,errHandlers:s,rawEmitters:o,watcher:c},oI.set(e,a)}return()=>{pw(a,e_,i),pw(a,$2,s),pw(a,dw,o),vde(a.listeners)&&(a.watcher.close(),oI.delete(e),Y6e.forEach(oVe(a)),a.watcher=void 0,Object.freeze(a))}},H2=new Map,cVe=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,o=H2.get(e),a=new Set,c=new Set,l=o&&o.options;return l&&(l.persistent<n.persistent||l.interval>n.interval)&&(a=o.listeners,c=o.rawEmitters,Eu.unwatchFile(e),o=void 0),o?(fw(o,e_,i),fw(o,dw,s)):(o={listeners:i,rawEmitters:s,options:n,watcher:Eu.watchFile(e,n,(u,d)=>{j2(o.rawEmitters,m=>{m(sI,e,{curr:u,prev:d})});let f=u.mtimeMs;(u.size!==d.size||f>d.mtimeMs||f===0)&&j2(o.listeners,m=>m(t,u))})},H2.set(e,o)),()=>{pw(o,e_,i),pw(o,dw,s),vde(o.listeners)&&(H2.delete(e),Eu.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},W2=class{constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=Vr.dirname(e),s=Vr.basename(e);this.fsw._getWatchedDir(i).add(s);let a=Vr.resolve(e),c={persistent:r.persistent};n||(n=z6e);let l;return r.usePolling?(c.interval=r.enableBinaryInterval&&j6e(s)?r.binaryInterval:r.interval,l=cVe(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})):l=aVe(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),l}_handleFile(e,n,r){if(this.fsw.closed)return;let i=Vr.dirname(e),s=Vr.basename(e),o=this.fsw._getWatchedDir(i),a=n;if(o.has(s))return;let c=async(u,d)=>{if(this.fsw._throttle(tVe,e,5)){if(!d||d.mtimeMs===0)try{let f=await _de(e);if(this.fsw.closed)return;let m=f.atimeMs,g=f.mtimeMs;(!m||m<=g||g!==a.mtimeMs)&&this.fsw._emit(sI,e,f),V6e&&a.ino!==f.ino?(this.fsw._closeFile(u),a=f,this.fsw._addPathCloser(u,this._watchWithNodeFs(e,c))):a=f}catch{this.fsw._remove(i,s)}else if(o.has(s)){let f=d.atimeMs,m=d.mtimeMs;(!f||f<=m||m!==a.mtimeMs)&&this.fsw._emit(sI,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(iI,e,0))return;this.fsw._emit(iI,e,n)}return l}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,o=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await G2(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(i)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(sI,r,e.stats)):(o.add(i),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(iI,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,o,a){if(e=Vr.join(e,K6e),!r.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(r.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:d=>r.filterPath(d),directoryFilter:d=>r.filterDir(d),depth:0}).on(J6e,async d=>{if(this.fsw.closed){u=void 0;return}let f=d.path,m=Vr.join(e,f);if(l.add(f),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,m,f))){if(this.fsw.closed){u=void 0;return}(f===i||!i&&!c.has(f))&&(this.fsw._incrReadyCount(),m=Vr.join(s,Vr.relative(s,m)),this._addToNodeFs(m,n,r,o+1))}}).on(yde,this._boundHandleError);return new Promise(d=>u.once(Q6e,()=>{if(this.fsw.closed){u=void 0;return}let f=a?a.clear():!1;d(),c.getChildren().filter(m=>m!==e&&!l.has(m)&&(!r.hasGlob||r.filterPath({fullPath:Vr.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),u=void 0,f&&this._handleRead(e,!1,r,i,s,o,a)}))}async _handleDir(e,n,r,i,s,o,a){let c=this.fsw._getWatchedDir(Vr.dirname(e)),l=c.has(Vr.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(X6e,e,n),c.add(Vr.basename(e)),this.fsw._getWatchedDir(e);let u,d,f=this.fsw.options.depth;if((f==null||i<=f)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,o,s,e,i,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,o,s,e,i,u)})}return d}async _addToNodeFs(e,n,r,i,s){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,i);!a.hasGlob&&r&&(a.hasGlob=r.hasGlob,a.globFilter=r.globFilter,a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await sVe[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let l=this.fsw.options.followSymlinks&&!e.includes(eVe)&&!e.includes(Z6e),u;if(c.isDirectory()){let d=Vr.resolve(e),f=l?await G2(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,i,s,a,f),this.fsw.closed))return;d!==f&&f!==void 0&&this.fsw._symlinkPaths.set(d,f)}else if(c.isSymbolicLink()){let d=l?await G2(e):e;if(this.fsw.closed)return;let f=Vr.dirname(a.watchPath);if(this.fsw._getWatchedDir(f).add(a.watchPath),this.fsw._emit(iI,a.watchPath,c),u=await this._handleDir(f,c,n,i,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(Vr.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return o(),this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};Ede.exports=W2});var Rde=B((sRt,Z2)=>{"use strict";var J2=require("fs"),zr=require("path"),{promisify:Q2}=require("util"),t_;try{t_=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(t_){let t=process.version.match(/v(\d+)\.(\d+)/);if(t&&t[1]&&t[2]){let e=Number.parseInt(t[1],10),n=Number.parseInt(t[2],10);e===8&&n<16&&(t_=void 0)}}var{EV_ADD:V2,EV_CHANGE:lVe,EV_ADD_DIR:Sde,EV_UNLINK:cI,EV_ERROR:uVe,STR_DATA:dVe,STR_END:fVe,FSEVENT_CREATED:pVe,FSEVENT_MODIFIED:hVe,FSEVENT_DELETED:mVe,FSEVENT_MOVED:gVe,FSEVENT_UNKNOWN:yVe,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:_Ve,FSEVENT_TYPE_FILE:vVe,FSEVENT_TYPE_DIRECTORY:mw,FSEVENT_TYPE_SYMLINK:Cde,ROOT_GLOBSTAR:xde,DIR_SUFFIX:EVe,DOT_SLASH:bde,FUNCTION_TYPE:z2,EMPTY_FN:wVe,IDENTITY_FN:SVe}=rI(),xVe=t=>isNaN(t)?{}:{depth:t},Y2=Q2(J2.stat),bVe=Q2(J2.lstat),Tde=Q2(J2.realpath),TVe={stat:Y2,lstat:bVe},Mh=new Map,AVe=10,CVe=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),RVe=(t,e)=>({stop:t_.watch(t,e)});function IVe(t,e,n,r){let i=zr.extname(e)?zr.dirname(e):e,s=zr.dirname(i),o=Mh.get(i);kVe(s)&&(i=s);let a=zr.resolve(t),c=a!==e,l=(d,f,m)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+zr.sep))&&n(d,f,m)},u=!1;for(let d of Mh.keys())if(e.indexOf(zr.resolve(d)+zr.sep)===0){i=d,o=Mh.get(i),u=!0;break}return o||u?o.listeners.add(l):(o={listeners:new Set([l]),rawEmitter:r,watcher:RVe(i,(d,f)=>{if(!o.listeners.size||f&_Ve)return;let m=t_.getInfo(d,f);o.listeners.forEach(g=>{g(d,f,m)}),o.rawEmitter(m.event,d,m)})},Mh.set(i,o)),()=>{let d=o.listeners;if(d.delete(l),!d.size&&(Mh.delete(i),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var kVe=t=>{let e=0;for(let n of Mh.keys())if(n.indexOf(t)===0&&(e++,e>=AVe))return!0;return!1},PVe=()=>t_&&Mh.size<128,K2=(t,e)=>{let n=0;for(;!t.indexOf(e)&&(t=zr.dirname(t))!==e;)n++;return n},Ade=(t,e)=>t.type===mw&&e.isDirectory()||t.type===Cde&&e.isSymbolicLink()||t.type===vVe&&e.isFile(),X2=class{constructor(e){this.fsw=e}checkIgnored(e,n){let r=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,n))return r.add(e),n&&n.isDirectory()&&r.add(e+xde),!0;r.delete(e),r.delete(e+xde)}addOrChange(e,n,r,i,s,o,a,c){let l=s.has(o)?lVe:V2;this.handleEvent(l,e,n,r,i,s,o,a,c)}async checkExists(e,n,r,i,s,o,a,c){try{let l=await Y2(e);if(this.fsw.closed)return;Ade(a,l)?this.addOrChange(e,n,r,i,s,o,a,c):this.handleEvent(cI,e,n,r,i,s,o,a,c)}catch(l){l.code==="EACCES"?this.addOrChange(e,n,r,i,s,o,a,c):this.handleEvent(cI,e,n,r,i,s,o,a,c)}}handleEvent(e,n,r,i,s,o,a,c,l){if(!(this.fsw.closed||this.checkIgnored(n)))if(e===cI){let u=c.type===mw;(u||o.has(a))&&this.fsw._remove(s,a,u)}else{if(e===V2){if(c.type===mw&&this.fsw._getWatchedDir(n),c.type===Cde&&l.followSymlinks){let d=l.depth===void 0?void 0:K2(r,i)+1;return this._addToFsEvents(n,!1,!0,d)}this.fsw._getWatchedDir(s).add(a)}let u=c.type===mw?e+EVe:e;this.fsw._emit(u,n),u===Sde&&this._addToFsEvents(n,!1,!0)}}_watchWithFsEvents(e,n,r,i){if(this.fsw.closed||this.fsw._isIgnored(e))return;let s=this.fsw.options,a=IVe(e,n,async(c,l,u)=>{if(this.fsw.closed||s.depth!==void 0&&K2(c,n)>s.depth)return;let d=r(zr.join(e,zr.relative(e,c)));if(i&&!i(d))return;let f=zr.dirname(d),m=zr.basename(d),g=this.fsw._getWatchedDir(u.type===mw?d:f);if(CVe.has(l)||u.event===yVe)if(typeof s.ignored===z2){let y;try{y=await Y2(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,y))return;Ade(u,y)?this.addOrChange(d,c,n,f,g,m,u,s):this.handleEvent(cI,d,c,n,f,g,m,u,s)}else this.checkExists(d,c,n,f,g,m,u,s);else switch(u.event){case pVe:case hVe:return this.addOrChange(d,c,n,f,g,m,u,s);case mVe:case gVe:return this.checkExists(d,c,n,f,g,m,u,s)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,n,r,i){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(n))){this.fsw._symlinkPaths.set(n,!0),this.fsw._incrReadyCount();try{let s=await Tde(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(s))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(s||e,o=>{let a=e;return s&&s!==bde?a=o.replace(s,e):o!==bde&&(a=zr.join(e,o)),r(a)},!1,i)}catch(s){if(this.fsw._handleError(s))return this.fsw._emitReady()}}}emitAdd(e,n,r,i,s){let o=r(e),a=n.isDirectory(),c=this.fsw._getWatchedDir(zr.dirname(o)),l=zr.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(l)&&(c.add(l),(!i.ignoreInitial||s===!0)&&this.fsw._emit(a?Sde:V2,o,n))}initWatch(e,n,r,i){if(this.fsw.closed)return;let s=this._watchWithFsEvents(r.watchPath,zr.resolve(e||r.watchPath),i,r.globFilter);this.fsw._addPathCloser(n,s)}async _addToFsEvents(e,n,r,i){if(this.fsw.closed)return;let s=this.fsw.options,o=typeof n===z2?n:SVe,a=this.fsw._getWatchHelpers(e);try{let c=await TVe[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,s,r),i&&i>s.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:l=>a.filterPath(l),directoryFilter:l=>a.filterDir(l),...xVe(s.depth-(i||0))}).on(dVe,l=>{if(this.fsw.closed||l.stats.isDirectory()&&!a.filterPath(l))return;let u=zr.join(a.watchPath,l.path),{fullPath:d}=l;if(a.followSymlinks&&l.stats.isSymbolicLink()){let f=s.depth===void 0?void 0:K2(u,zr.resolve(a.watchPath))+1;this._handleFsEventsSymlink(u,d,o,f)}else this.emitAdd(u,l.stats,o,s,r)}).on(uVe,wVe).on(fVe,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,s,r),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(s.persistent&&r!==!0)if(typeof n===z2)this.initWatch(void 0,e,a,o);else{let c;try{c=await Tde(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};Z2.exports=X2;Z2.exports.canUse=PVe});var Bde=B(h$=>{"use strict";var{EventEmitter:OVe}=require("events"),f$=require("fs"),pn=require("path"),{promisify:Dde}=require("util"),MVe=mue(),s$=Sue().default,NVe=Rue(),e$=M2(),DVe=ude(),LVe=Qy(),UVe=wde(),Ide=Rde(),{EV_ALL:t$,EV_READY:FVe,EV_ADD:lI,EV_CHANGE:gw,EV_UNLINK:kde,EV_ADD_DIR:BVe,EV_UNLINK_DIR:qVe,EV_RAW:$Ve,EV_ERROR:n$,STR_CLOSE:GVe,STR_END:HVe,BACK_SLASH_RE:jVe,DOUBLE_SLASH_RE:Pde,SLASH_OR_BACK_SLASH_RE:WVe,DOT_RE:VVe,REPLACER_RE:zVe,SLASH:r$,SLASH_SLASH:KVe,BRACE_START:YVe,BANG:o$,ONE_DOT:Lde,TWO_DOTS:XVe,GLOBSTAR:JVe,SLASH_GLOBSTAR:i$,ANYMATCH_OPTS:a$,STRING_TYPE:p$,FUNCTION_TYPE:QVe,EMPTY_STR:c$,EMPTY_FN:ZVe,isWindows:eze,isMacos:tze,isIBMi:nze}=rI(),rze=Dde(f$.stat),ize=Dde(f$.readdir),l$=(t=[])=>Array.isArray(t)?t:[t],Ude=(t,e=[])=>(t.forEach(n=>{Array.isArray(n)?Ude(n,e):e.push(n)}),e),Ode=t=>{let e=Ude(l$(t));if(!e.every(n=>typeof n===p$))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Fde)},Mde=t=>{let e=t.replace(jVe,r$),n=!1;for(e.startsWith(KVe)&&(n=!0);e.match(Pde);)e=e.replace(Pde,r$);return n&&(e=r$+e),e},Fde=t=>Mde(pn.normalize(Mde(t))),Nde=(t=c$)=>e=>typeof e!==p$?e:Fde(pn.isAbsolute(e)?e:pn.join(t,e)),sze=(t,e)=>pn.isAbsolute(t)?t:t.startsWith(o$)?o$+pn.join(e,t.slice(1)):pn.join(e,t),ja=(t,e)=>t[e]===void 0,u$=class{constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==Lde&&e!==XVe&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await ize(r)}catch{this._removeWatcher&&this._removeWatcher(pn.dirname(r),pn.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},oze="stat",aze="lstat",d$=class{constructor(e,n,r,i){this.fsw=i,this.path=e=e.replace(zVe,c$),this.watchPath=n,this.fullWatchPath=pn.resolve(n),this.hasGlob=n!==e,e===c$&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&r?void 0:!1,this.globFilter=this.hasGlob?s$(e,void 0,a$):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=r,this.statMethod=r?oze:aze}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return pn.join(this.watchPath,pn.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===QVe?this.globFilter(r):!0)&&this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}getDirParts(e){if(!this.hasGlob)return[];let n=[];return(e.includes(YVe)?DVe.expand(e):[e]).forEach(i=>{n.push(pn.relative(this.watchPath,i).split(WVe))}),n}filterDir(e){if(this.hasGlob){let n=this.getDirParts(this.checkGlobSymlink(e)),r=!1;this.unmatchedGlob=!this.dirParts.some(i=>i.every((s,o)=>(s===JVe&&(r=!0),r||!n[0][o]||s$(s,n[0][o],a$))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},uI=class extends OVe{constructor(e){super();let n={};e&&Object.assign(n,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,ja(n,"persistent")&&(n.persistent=!0),ja(n,"ignoreInitial")&&(n.ignoreInitial=!1),ja(n,"ignorePermissionErrors")&&(n.ignorePermissionErrors=!1),ja(n,"interval")&&(n.interval=100),ja(n,"binaryInterval")&&(n.binaryInterval=300),ja(n,"disableGlobbing")&&(n.disableGlobbing=!1),n.enableBinaryInterval=n.binaryInterval!==n.interval,ja(n,"useFsEvents")&&(n.useFsEvents=!n.usePolling),Ide.canUse()||(n.useFsEvents=!1),ja(n,"usePolling")&&!n.useFsEvents&&(n.usePolling=tze),nze&&(n.usePolling=!0);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?n.usePolling=!1:c==="true"||c==="1"?n.usePolling=!0:n.usePolling=!!c}let s=process.env.CHOKIDAR_INTERVAL;s&&(n.interval=Number.parseInt(s,10)),ja(n,"atomic")&&(n.atomic=!n.usePolling&&!n.useFsEvents),n.atomic&&(this._pendingUnlinks=new Map),ja(n,"followSymlinks")&&(n.followSymlinks=!0),ja(n,"awaitWriteFinish")&&(n.awaitWriteFinish=!1),n.awaitWriteFinish===!0&&(n.awaitWriteFinish={});let o=n.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),n.ignored&&(n.ignored=l$(n.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=ZVe,this._readyEmitted=!0,process.nextTick(()=>this.emit(FVe)))},this._emitRaw=(...c)=>this.emit($Ve,...c),this._readyEmitted=!1,this.options=n,n.useFsEvents?this._fsEventsHandler=new Ide(this):this._nodeFsHandler=new UVe(this),Object.freeze(n)}add(e,n,r){let{cwd:i,disableGlobbing:s}=this.options;this.closed=!1;let o=Ode(e);return i&&(o=o.map(a=>{let c=sze(a,i);return s||!e$(a)?c:LVe(c)})),o=o.filter(a=>a.startsWith(o$)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+i$),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!r,0,0,n);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(pn.dirname(c),pn.basename(n||c))})})),this}unwatch(e){if(this.closed)return this;let n=Ode(e),{cwd:r}=this.options;return n.forEach(i=>{!pn.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=pn.join(r,i)),i=pn.resolve(i)),this._closePath(i),this._ignoredPaths.add(i),this._watched.has(i)&&this._ignoredPaths.add(i+i$),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(n=>{this[`_${n}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let i=this.options.cwd?pn.relative(this.options.cwd,r):r;e[i||Lde]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(...n),e!==n$&&this.emit(t$,...n)}async _emit(e,n,r,i,s){if(this.closed)return;let o=this.options;eze&&(n=pn.normalize(n)),o.cwd&&(n=pn.relative(o.cwd,n));let a=[e,n];s!==void 0?a.push(r,i,s):i!==void 0?a.push(r,i):r!==void 0&&a.push(r);let c=o.awaitWriteFinish,l;if(c&&(l=this._pendingWrites.get(n)))return l.lastChange=new Date,this;if(o.atomic){if(e===kde)return this._pendingUnlinks.set(n,a),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(t$,...u),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===lI&&this._pendingUnlinks.has(n)&&(e=a[0]=gw,this._pendingUnlinks.delete(n))}if(c&&(e===lI||e===gw)&&this._readyEmitted){let u=(d,f)=>{d?(e=a[0]=n$,a[1]=d,this.emitWithAll(e,a)):f&&(a.length>2?a[2]=f:a.push(f),this.emitWithAll(e,a))};return this._awaitWriteFinish(n,c.stabilityThreshold,e,u),this}if(e===gw&&!this._throttle(gw,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===lI||e===BVe||e===gw)){let u=o.cwd?pn.join(o.cwd,n):n,d;try{d=await rze(u)}catch{}if(!d||this.closed)return;a.push(d)}return this.emitWithAll(e,a),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(n$,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e),s=i.get(n);if(s)return s.count++,!1;let o,a=()=>{let l=i.get(n),u=l?l.count:0;return i.delete(n),clearTimeout(o),l&&clearTimeout(l.timeoutObject),u};o=setTimeout(a,r);let c={timeoutObject:o,clear:a,count:0};return i.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s,o=e;this.options.cwd&&!pn.isAbsolute(e)&&(o=pn.join(this.options.cwd,e));let a=new Date,c=l=>{f$.stat(o,(u,d)=>{if(u||!this._pendingWrites.has(e)){u&&u.code!=="ENOENT"&&i(u);return}let f=Number(new Date);l&&d.size!==l.size&&(this._pendingWrites.get(e).lastChange=f);let m=this._pendingWrites.get(e);f-m.lastChange>=n?(this._pendingWrites.delete(e),i(void 0,d)):s=setTimeout(c,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(s),r)}),s=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,n){if(this.options.atomic&&VVe.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=this.options.ignored,s=i&&i.map(Nde(r)),o=l$(s).filter(c=>typeof c===p$&&!e$(c)).map(c=>c+i$),a=this._getGlobIgnored().map(Nde(r)).concat(s,o);this._userIgnored=s$(a,void 0,a$)}return this._userIgnored([e,n])}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e,n){let r=n||this.options.disableGlobbing||!e$(e)?e:NVe(e),i=this.options.followSymlinks;return new d$(e,r,i,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let n=pn.resolve(e);return this._watched.has(n)||this._watched.set(n,new u$(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let r=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(r.toString(8)[0],10))}_remove(e,n,r){let i=pn.join(e,n),s=pn.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(f=>this._remove(i,f));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=pn.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===lI)return;this._watched.delete(i),this._watched.delete(s);let d=r?qVe:kde;l&&!this._isIgnored(i)&&this._emit(d,i),this.options.useFsEvents||this._closePath(i)}_closePath(e){this._closeFile(e);let n=pn.dirname(e);this._getWatchedDir(n).remove(pn.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:t$,alwaysStat:!0,lstat:!0,...n},i=MVe(e,r);return this._streams.add(i),i.once(GVe,()=>{i=void 0}),i.once(HVe,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};h$.FSWatcher=uI;var cze=(t,e)=>{let n=new uI(e);return n.add(t),n};h$.watch=cze});function Wde(t){return DB.includes(t)}function r_(t){return UC.includes(Ws.default.extname(t).toLowerCase())}function yze(t,e){return t.isDirectory()?"folder":r_(e)?"binary":"file"}function rf(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function _ze(t){if(!m$.has(t)){let e=process.platform==="win32"?"where":"which";m$.set(t,(0,wu.spawnSync)(e,[t],{stdio:"ignore"}).status===0)}return m$.get(t)}function vze(t){let e=_se.find(r=>_ze(r.cmd));if(!e)throw new Error("HEIC needs a system converter (macOS has sips; on Linux install libheif-examples or imagemagick)");let n=Ws.default.join(Wa.default.tmpdir(),`9r-heic-${process.pid}-${Date.now()}.jpg`);try{let r=(0,wu.spawnSync)(e.cmd,e.args(t,n),{timeout:vse});if(r.status!==0||!st.default.existsSync(n))throw new Error(`HEIC decode failed (${e.cmd}): ${r.stderr?.toString().trim()||"unknown error"}`);return st.default.readFileSync(n)}finally{try{st.default.unlinkSync(n)}catch{}}}async function i_(t,e){let n=FC(e)?vze(e):t,r=await(0,dI.default)(n).metadata(),i=r.orientation>=5,s=(i?r.height:r.width)||0,o=(i?r.width:r.height)||0,a=[80,60,40],c=[1600,1200,800],l=n,u=s,d=o;for(let f of c)for(let m of a){l=await(0,dI.default)(n).rotate().resize({width:f,height:f,fit:"inside",withoutEnlargement:!0}).jpeg({quality:m,mozjpeg:!0}).toBuffer();let g=await(0,dI.default)(l).metadata();if(u=g.width||f,d=g.height||f,l.length<=3145728)return{buffer:l,width:u,height:d,originalWidth:s,originalHeight:o}}return{buffer:l,width:u,height:d,originalWidth:s,originalHeight:o}}function Vde(t,e,n,r=50){if(!(n.length>=r))try{for(let i of st.default.readdirSync(t)){if(n.length>=r)return;if(i.startsWith(".")||Wde(i))continue;let s=Ws.default.join(t,i);try{let o=st.default.statSync(s);o.isDirectory()?Vde(s,e,n,r):i.toLowerCase().includes(e.toLowerCase())&&n.push({name:i,path:s,type:r_(i)?"binary":"file",size:o.size,sizeFormatted:rf(o.size)})}catch{}}}catch{}}function Hde(t){if(!t)return null;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::ANY::").replace(/\*/g,"[^/]*").replace(/::ANY::/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`)}function zde(t,e,n,r,i,s){if(s.length>=200)return;let o;try{o=st.default.readdirSync(t,{withFileTypes:!0})}catch{return}for(let a of o){if(s.length>=200)return;if(Wde(a.name))continue;let c=Ws.default.join(t,a.name),l=Ws.default.relative(e,c);if(a.isDirectory()){zde(c,e,n,r,i,s);continue}if(a.isFile()&&!r_(a.name)&&!wt(c)&&!(i&&i.test(l))&&!(r&&!r.test(l)))try{if(st.default.statSync(c).size>1048576)continue;let f=st.default.readFileSync(c,"utf-8").split(`
414
414
  `),m=[];for(let g=0;g<f.length&&m.length<10;g++){let y=f[g],w=n(y);for(let S of w){if(m.length>=10)break;m.push({line:g+1,column:S.column+1,lineText:y,matchLength:S.length})}}m.length&&s.push({path:c,matches:m})}catch{}}}function Kde(t,e,n){let r;try{r=st.default.readdirSync(t,{withFileTypes:!0})}catch{return[]}let i=[];for(let s of r){if(!n&&s.name.startsWith(".")&&s.name!==".env"&&s.name!==".env.example")continue;let o=Ws.default.join(t,s.name);if(s.isDirectory()){let a={name:s.name,path:o,type:"folder"};e>0&&(a.children=Kde(o,e-1,n)),i.push(a)}else s.isFile()&&i.push({name:s.name,path:o,type:r_(s.name)?"binary":"file"})}return i.sort((s,o)=>s.type==="folder"&&o.type!=="folder"?-1:s.type!=="folder"&&o.type==="folder"?1:s.name.localeCompare(o.name)),i}function Eze(){if(process.platform!=="win32")return[];try{return(0,wu.execSync)("wmic logicaldisk get name",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).split(/\r?\n/).map(e=>e.trim()).filter(e=>/^[A-Z]:$/.test(e)).map(e=>({letter:e[0],path:e+"\\"}))}catch{return"CDEFGHIJ".split("").map(t=>`${t}:\\`).filter(t=>st.default.existsSync(t)).map(t=>({letter:t[0],path:t}))}}function Yde(t){t.on("getSystemInfo",n=>{let r=process.platform;n({success:!0,platform:r,isWindows:r==="win32",drives:r==="win32"?Eze():[],homedir:Wa.default.homedir()})}),t.on("getFiles",({dirPath:n,showHidden:r},i)=>{try{let s=n||Wa.default.homedir(),o=s.startsWith("~")?s.replace("~",Wa.default.homedir()):s;if(wt(o))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(o))return i({success:!1,error:"Directory not found"});let a;try{a=st.default.readdirSync(o,{withFileTypes:!0})}catch(d){return i({success:!1,error:d.message})}r||(a=a.filter(d=>!(d.name.startsWith(".")&&d.name!==".env"&&d.name!==".env.example"))),a.sort((d,f)=>{let m=d.isDirectory(),g=f.isDirectory();return m&&!g?-1:!m&&g?1:d.name.localeCompare(f.name)});let c=a.length>300,l=c?a.slice(0,300):a,u=[];for(let d of l)try{let f=Ws.default.join(o,d.name),m=st.default.statSync(f);u.push({name:d.name,path:f,type:yze(m,d.name),size:m.isFile()?m.size:null,sizeFormatted:m.isFile()?rf(m.size):null,modified:m.mtime.getTime()})}catch{}i({success:!0,files:u,currentPath:o,parentPath:Ws.default.dirname(o),truncated:c})}catch(s){i({success:!1,error:s.message})}}),t.on("searchFiles",({workspace:n,query:r},i)=>{try{if(!r||r.length<2)return i({success:!0,files:[]});let s=(n||Wa.default.homedir()).replace(/^~/,Wa.default.homedir());if(!st.default.existsSync(s))return i({success:!1,error:"Workspace not found"});let o=[];Vde(s,r,o,50),o.sort((a,c)=>{let l=a.name.toLowerCase()===r.toLowerCase(),u=c.name.toLowerCase()===r.toLowerCase();return l&&!u?-1:!l&&u?1:a.path.length-c.path.length}),i({success:!0,files:o})}catch(s){i({success:!1,error:s.message})}}),t.on("readFile",({filePath:n},r)=>{try{if(wt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"File not found"});let i=st.default.statSync(n);if(i.size>1048576)return r({success:!1,error:`File too large (${rf(i.size)}). Max ${rf(1048576)}`});if(r_(n))return r({success:!1,error:"Cannot open binary file"});if(i.size>h0)return r({success:!0,content:"",streamInstead:!0,size:i.size});r({success:!0,content:st.default.readFileSync(n,"utf-8")})}catch(i){r({success:!1,error:i.message})}}),t.on("readMedia",async({filePath:n},r)=>{try{if(wt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"File not found"});let i=st.default.statSync(n),s=Ws.default.extname(n).toLowerCase().slice(1),o=mh[s]||"application/octet-stream",a=o.startsWith("image/"),c=a?20971520:5242880;if(i.size>c)return r({success:!1,error:`File too large (${rf(i.size)}). Max ${rf(c)}`});let l=st.default.readFileSync(n);if(a){let u=await i_(l,n),d=`data:image/jpeg;base64,${u.buffer.toString("base64")}`;r({success:!0,dataUrl:d,size:i.size,mime:o,originalSize:i.size,originalWidth:u.originalWidth,originalHeight:u.originalHeight,width:u.width,height:u.height,scaled:u.buffer.length<i.size})}else{let u=`data:${o};base64,${l.toString("base64")}`;r({success:!0,dataUrl:u,size:i.size,mime:o})}}catch(i){r({success:!1,error:i.message})}}),t.on("readImage",async({filePath:n},r)=>{try{if(wt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"File not found"});let i=st.default.statSync(n);if(i.size>20971520)return r({success:!1,error:`Image too large (${rf(i.size)}). Max ${rf(20971520)}`});let s=st.default.readFileSync(n),o=await i_(s,n),a=`data:image/jpeg;base64,${o.buffer.toString("base64")}`;r({success:!0,dataUrl:a,size:i.size,mime:"image/jpeg",originalSize:i.size,originalWidth:o.originalWidth,originalHeight:o.originalHeight,width:o.width,height:o.height,scaled:o.buffer.length<i.size})}catch(i){r({success:!1,error:i.message})}}),t.on("writeFile",({filePath:n,content:r},i)=>{try{if(wt(n))return i({success:!1,error:"Access denied"});st.default.writeFileSync(n,r,"utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("createItem",({itemPath:n,type:r},i)=>{try{if(wt(n))return i({success:!1,error:"Access denied"});if(st.default.existsSync(n))return i({success:!1,error:"Item already exists"});r==="folder"?st.default.mkdirSync(n,{recursive:!0}):st.default.writeFileSync(n,"","utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("deleteItem",({itemPath:n},r)=>{try{if(wt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"Item not found"});st.default.statSync(n).isDirectory()?st.default.rmSync(n,{recursive:!0}):st.default.unlinkSync(n),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("copyItem",({srcPath:n,destPath:r},i)=>{try{if(wt(n)||wt(r))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return i({success:!1,error:"Item not found"});if(st.default.existsSync(r))return i({success:!1,error:"Target already exists"});if(r.startsWith(n+"/"))return i({success:!1,error:"Cannot copy into itself"});st.default.cpSync(n,r,{recursive:!0}),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("renameItem",({oldPath:n,newPath:r},i)=>{try{if(wt(n)||wt(r))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return i({success:!1,error:"Item not found"});if(st.default.existsSync(r))return i({success:!1,error:"Target already exists"});st.default.renameSync(n,r),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("searchInFiles",({workspace:n,query:r,caseSensitive:i,regex:s,includeGlob:o,excludeGlob:a},c)=>{try{if(!r)return c({success:!0,results:[]});let l=(n||Wa.default.homedir()).replace(/^~/,Wa.default.homedir());if(!st.default.existsSync(l))return c({success:!1,error:"Workspace not found"});let u;if(s){let g;try{g=new RegExp(r,i?"g":"gi")}catch(y){return c({success:!1,error:`Invalid regex: ${y.message}`})}u=y=>{let w=[],S;for(g.lastIndex=0;(S=g.exec(y))!==null;)w.push({column:S.index,length:S[0].length}),S.index===g.lastIndex&&g.lastIndex++;return w}}else{let g=i?r:r.toLowerCase();u=y=>{let w=i?y:y.toLowerCase(),S=[],T=0;for(;(T=w.indexOf(g,T))!==-1;)S.push({column:T,length:g.length}),T+=g.length||1;return S}}let d=Hde(o),f=Hde(a),m=[];zde(l,l,u,d,f,m),c({success:!0,results:m})}catch(l){c({success:!1,error:l.message})}}),t.on("replaceInFiles",({workspace:n,query:r,replacement:i,caseSensitive:s,regex:o,files:a},c)=>{try{if(!r||!Array.isArray(a)||!a.length)return c({success:!0,replacedCount:0,fileCount:0});let l;if(o){let f;try{f=new RegExp(r,s?"g":"gi")}catch(m){return c({success:!1,error:`Invalid regex: ${m.message}`})}l=m=>{let g=0;return{next:m.replace(f,w=>(g++,i)),count:g}}}else l=f=>{let m=0,g=s?"g":"gi",y=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),w=new RegExp(y,g);return{next:f.replace(w,()=>(m++,i)),count:m}};let u=0,d=0;for(let f of a)try{if(!st.default.existsSync(f)||r_(f)||wt(f))continue;let m=st.default.statSync(f);if(!m.isFile()||m.size>1048576)continue;let g=st.default.readFileSync(f,"utf-8"),{next:y,count:w}=l(g);w>0&&(st.default.writeFileSync(f,y,"utf-8"),u+=w,d++)}catch{}c({success:!0,replacedCount:u,fileCount:d})}catch(l){c({success:!1,error:l.message})}});let e=new Map;t.on("watchDir",({dirPath:n},r)=>{try{if(!n||!st.default.existsSync(n))return r({success:!1,error:"Directory not found"});let i=e.get(n);if(i)return i.count++,r({success:!0});if(e.size>=60)return r({success:!0,watching:!1});let s=jde.default.watch(n,{depth:0,ignoreInitial:!0,persistent:!0,ignored:c=>DB.includes(Ws.default.basename(c))}),o={w:s,count:1,burstStart:0,burstCount:0,mutedUntil:0},a=c=>l=>{let u=Date.now();if(!(u<o.mutedUntil)){if(u-o.burstStart>1e3&&(o.burstStart=u,o.burstCount=0),++o.burstCount>30)return o.mutedUntil=u+3e3,t.emit("fileChange",{type:"flooded",path:n});t.emit("fileChange",{type:c,path:l})}};s.on("add",a("add")).on("change",a("change")).on("unlink",a("unlink")).on("addDir",a("addDir")).on("unlinkDir",a("unlinkDir")),e.set(n,o),r({success:!0,watching:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("unwatchDir",({dirPath:n},r)=>{try{let i=e.get(n);i&&--i.count<=0&&(i.w.close(),e.delete(n)),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.once("disconnect",()=>{for(let{w:n}of e.values())try{n.close()}catch{}e.clear()}),t.on("revealInOS",({filePath:n},r)=>{try{if(!n)return r({success:!1,error:"No path"});let i=process.platform,s,o;i==="darwin"?(s="open",o=["-R",n]):i==="win32"?(s="explorer",o=[`/select,${n}`]):(s="xdg-open",o=[Ws.default.dirname(n)]);let a=(0,wu.spawn)(s,o,{detached:!0,stdio:"ignore",windowsHide:!0});a.on("error",c=>r({success:!1,error:c.message})),a.unref(),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("openInTerminal",({dirPath:n},r)=>{try{if(!n||!st.default.existsSync(n))return r({success:!1,error:"Directory not found"});let i=process.platform,s,o,a={detached:!0,stdio:"ignore",windowsHide:!0};i==="darwin"?(s="open",o=["-a","Terminal",n]):i==="win32"?(s="cmd",o=["/C","start",'"9Remote"',"cmd","/K"],a.shell=!1,a.cwd=n):(s="gnome-terminal",o=["--working-directory",n]);let c=(0,wu.spawn)(s,o,a);c.on("error",()=>{if(i==="linux"){let l=(0,wu.spawn)("xterm",["-e","bash"],{...a,cwd:n});l.on("error",u=>r({success:!1,error:u.message})),l.unref()}else r({success:!1,error:"Failed to open terminal"})}),c.unref(),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("getFileTree",({dirPath:n,depth:r,showHidden:i},s)=>{try{let o=(n||Wa.default.homedir()).replace(/^~/,Wa.default.homedir());if(!st.default.existsSync(o))return s({success:!1,error:"Directory not found"});let c=Kde(o,typeof r=="number"?r:3,!!i);s({success:!0,tree:{name:Ws.default.basename(o)||o,path:o,type:"folder",children:c}})}catch(o){s({success:!1,error:o.message})}})}var st,Ws,Wa,wu,jde,dI,m$,fI=ae(()=>{st=ce(require("fs"),1),Ws=ce(require("path"),1),Wa=ce(require("os"),1),wu=require("child_process"),jde=ce(Bde(),1),dI=ce(require("sharp"),1);Ry();Ji();yh();m$=new Map});function xze(t,{maxDepth:e=pI.maxDepth,timeoutMs:n=pI.timeoutMs,now:r=()=>Date.now(),io:i=g$.default}={}){if(!t)return[];let s=Jc.default.resolve(t),o=r()+n,a=[],c=[{dir:s,depth:0}];for(;c.length&&!(r()>o);){let{dir:l,depth:u}=c.shift();if(Sze(l,i)&&a.push({path:l,relPath:l===s?"":Jc.default.relative(s,l),depth:u}),u>=e)continue;let d;try{d=i.readdirSync(l,{withFileTypes:!0})}catch{continue}for(let f of d)!f.isDirectory()||f.isSymbolicLink()||wze.has(f.name)||c.push({dir:Jc.default.join(l,f.name),depth:u+1})}return a}function y$(t,e={}){let n=e.now||(()=>Date.now()),r=e.cacheTtlMs??pI.cacheTtlMs,i=bze(t,e.maxDepth),s=yw.get(i);if(s&&n()-s.ts<r)return s.repos;let o=xze(t,e);return yw.set(i,{ts:n(),repos:o}),o}function _w(t){if(!t)return yw.clear();let e=`${Jc.default.resolve(t)}::`;for(let n of yw.keys())n.startsWith(e)&&yw.delete(n)}function _$(t=""){let e=[],n=null;for(let r of t.split(`
415
415
  `)){let i=r.trimEnd();if(!i){n&&(e.push(n),n=null);continue}let[s,...o]=i.split(" "),a=o.join(" ");if(s==="worktree")n={path:a,branch:null,head:null,detached:!1,locked:!1,bare:!1};else if(n)s==="HEAD"?n.head=a:s==="branch"?n.branch=a.replace(/^refs\/heads\//,""):s==="detached"?n.detached=!0:s==="locked"?n.locked=!0:s==="bare"&&(n.bare=!0);else continue}return n&&e.push(n),e.map((r,i)=>({...r,isMain:i===0}))}function Xde(t="",e=[]){let n=new Set(e.map(s=>s.branch).filter(Boolean)),r=new Set,i=[];for(let s of t.split(`
@@ -499,7 +499,7 @@ Content-Type: ${s}\r
499
499
  `+r+w.join(`,
500
500
  `+r)+`
501
501
  `+y+"}":"{"+w.join(",")+"}",r=y,m}}typeof Cwe.stringify!="function"&&(Cwe.stringify=function(l,u,d){var f;if(r="",i="",typeof d=="number")for(f=0;f<d;f+=1)i+=" ";else typeof d=="string"&&(i=d);if(o=u,u&&typeof u!="function"&&(typeof u!="object"||typeof u.length!="number"))throw new Error("JSON.stringify");return c("",{"":l})})})()});var Pwe=B((Y1t,kwe)=>{var hP=null,Pnt=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Ont=/(?: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)/,Mnt=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:`
502
- `,r:"\r",t:" "},s,o=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},a=function(y){return y&&y!==r&&o("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},c=function(){var y,w="";for(r==="-"&&(w="-",a("-"));r>="0"&&r<="9";)w+=r,a();if(r===".")for(w+=".";a()&&r>="0"&&r<="9";)w+=r;if(r==="e"||r==="E")for(w+=r,a(),(r==="-"||r==="+")&&(w+=r,a());r>="0"&&r<="9";)w+=r,a();if(y=+w,!isFinite(y))o("Bad number");else return hP==null&&(hP=l4()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new hP(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new hP(y):y},l=function(){var y,w,S="",T;if(r==='"')for(var R=n;a();){if(r==='"')return n-1>R&&(S+=s.substring(R,n-1)),a(),S;if(r==="\\"){if(n-1>R&&(S+=s.substring(R,n-1)),a(),r==="u"){for(T=0,w=0;w<4&&(y=parseInt(a(),16),!!isFinite(y));w+=1)T=T*16+y;S+=String.fromCharCode(T)}else if(typeof i[r]=="string")S+=i[r];else break;R=n}}o("Bad string")},u=function(){for(;r&&r<=" ";)a()},d=function(){switch(r){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}o("Unexpected '"+r+"'")},f,m=function(){var y=[];if(r==="["){if(a("["),u(),r==="]")return a("]"),y;for(;r;){if(y.push(f()),u(),r==="]")return a("]"),y;a(","),u()}}o("Bad array")},g=function(){var y,w=Object.create(null);if(r==="{"){if(a("{"),u(),r==="}")return a("}"),w;for(;r;){if(y=l(),u(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(w,y)&&o('Duplicate key "'+y+'"'),Pnt.test(y)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?f():w[y]=f():Ont.test(y)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?f():w[y]=f():w[y]=f(),u(),r==="}")return a("}"),w;a(","),u()}}o("Bad object")};return f=function(){switch(u(),r){case"{":return g();case"[":return m();case'"':return l();case"-":return c();default:return r>="0"&&r<="9"?c():d()}},function(y,w){var S;return s=y+"",n=0,r=" ",S=f(),u(),r&&o("Syntax error"),typeof w=="function"?(function T(R,C){var D,$,G=R[C];return G&&typeof G=="object"&&Object.keys(G).forEach(function(V){$=T(G,V),$!==void 0?G[V]=$:delete G[V]}),w.call(R,C,G)})({"":S},""):S}};kwe.exports=Mnt});var Nwe=B((X1t,mP)=>{var Owe=Iwe().stringify,Mwe=Pwe();mP.exports=function(t){return{parse:Mwe(t),stringify:Owe}};mP.exports.parse=Mwe();mP.exports.stringify=Owe});var u4=B(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.GCE_LINUX_BIOS_PATHS=void 0;Qa.isGoogleCloudServerless=Uwe;Qa.isGoogleComputeEngineLinux=Fwe;Qa.isGoogleComputeEngineMACAddress=Bwe;Qa.isGoogleComputeEngine=qwe;Qa.detectGCPResidency=Dnt;var Dwe=require("fs"),Lwe=require("os");Qa.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Nnt=/^42:01/;function Uwe(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Fwe(){if((0,Lwe.platform)()!=="linux")return!1;try{(0,Dwe.statSync)(Qa.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Dwe.readFileSync)(Qa.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Bwe(){let t=(0,Lwe.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(Nnt.test(n))return!0}return!1}function qwe(){return Fwe()||Bwe()}function Dnt(){return Uwe()||qwe()}});var $we=B(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Colours=void 0;var Ci=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="")}};gP.Colours=Ci;Ci.enabled=!1;Ci.reset="";Ci.bright="";Ci.dim="";Ci.red="";Ci.green="";Ci.yellow="";Ci.blue="";Ci.magenta="";Ci.cyan="";Ci.white="";Ci.grey="";Ci.refresh()});var Wwe=B(wn=>{"use strict";var Lnt=wn&&wn.__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]})),Unt=wn&&wn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gwe=wn&&wn.__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"&&Lnt(n,e,r[i]);return Unt(n,e),n}})();Object.defineProperty(wn,"__esModule",{value:!0});wn.env=wn.DebugLogBackendBase=wn.placeholder=wn.AdhocDebugLogger=wn.LogSeverity=void 0;wn.getNodeBackend=f4;wn.getDebugBackend=Bnt;wn.getStructuredBackend=qnt;wn.setBackend=$nt;wn.log=jwe;var Fnt=require("events"),bS=Gwe(require("process")),Hwe=Gwe(require("util")),eo=$we(),Za;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Za||(wn.LogSeverity=Za={}));var TS=class extends Fnt.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(Za.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Za.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Za.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Za.ERROR,...r),this.func.sublog=r=>jwe(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)}};wn.AdhocDebugLogger=TS;wn.placeholder=new TS("",()=>{}).func;var H_=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=bS.env[wn.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)}}};wn.DebugLogBackendBase=H_;var d4=class extends H_{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 s=`${eo.Colours.green}${e}${eo.Colours.reset}`,o=`${eo.Colours.yellow}${bS.pid}${eo.Colours.reset}`,a;switch(n.severity){case Za.ERROR:a=`${eo.Colours.red}${n.severity}${eo.Colours.reset}`;break;case Za.INFO:a=`${eo.Colours.magenta}${n.severity}${eo.Colours.reset}`;break;case Za.WARNING:a=`${eo.Colours.yellow}${n.severity}${eo.Colours.reset}`;break;default:a=(i=n.severity)!==null&&i!==void 0?i:Za.DEFAULT;break}let c=Hwe.formatWithOptions({colors:eo.Colours.enabled},...r),l=Object.assign({},n);delete l.severity;let u=Object.getOwnPropertyNames(l).length?JSON.stringify(l):"",d=u?`${eo.Colours.grey}${u}${eo.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",o,s,a,c,u?` ${d}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function f4(){return new d4}var p4=class extends H_{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=bS.env.NODE_DEBUG)!==null&&e!==void 0?e:"";bS.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function Bnt(t){return new p4(t)}var h4=class extends H_{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,...s)=>{var o;let a=(o=i.severity)!==null&&o!==void 0?o:Za.INFO,c=Object.assign({severity:a,message:Hwe.format(...s)},i),l=JSON.stringify(c);r?r(i,l):console.log("%s",l)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function qnt(t){return new h4(t)}wn.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var m4=new Map,to;function $nt(t){to=t,m4.clear()}function jwe(t,e){if(!to&&!bS.env[wn.env.nodeEnables]||!t)return wn.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=m4.get(t);if(n)return n.func;if(to===null)return wn.placeholder;to===void 0&&(to=f4());let r=(()=>{let i;return new TS(t,(o,...a)=>{if(i!==to){if(to===null)return;to===void 0&&(to=f4()),i=to}to?.log(t,o,...a)})})();return m4.set(t,r),r.func}});var g4=B(cm=>{"use strict";var Gnt=cm&&cm.__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]})),Hnt=cm&&cm.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Gnt(e,t,n)};Object.defineProperty(cm,"__esModule",{value:!0});Hnt(Wwe(),cm)});var CS=B(Je=>{"use strict";var zwe=Je&&Je.__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]})),jnt=Je&&Je.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wnt=Je&&Je.__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"&&zwe(n,e,r[i]);return jnt(n,e),n}})(),Vnt=Je&&Je.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zwe(e,t,n)};Object.defineProperty(Je,"__esModule",{value:!0});Je.gcpResidencyCache=Je.METADATA_SERVER_DETECTION=Je.HEADERS=Je.HEADER_VALUE=Je.HEADER_NAME=Je.SECONDARY_HOST_ADDRESS=Je.HOST_ADDRESS=Je.BASE_PATH=void 0;Je.instance=Qnt;Je.project=Znt;Je.universe=ert;Je.bulk=trt;Je.isAvailable=rrt;Je.resetIsAvailableCache=irt;Je.getGCPResidency=v4;Je.setGCPResidency=Kwe;Je.requestTimeout=Ywe;var y4=di(),znt=Nwe(),Knt=u4(),Ynt=Wnt(g4());Je.BASE_PATH="/computeMetadata/v1";Je.HOST_ADDRESS="http://169.254.169.254";Je.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Je.HEADER_NAME="Metadata-Flavor";Je.HEADER_VALUE="Google";Je.HEADERS=Object.freeze({[Je.HEADER_NAME]:Je.HEADER_VALUE});var Vwe=Ynt.log("gcp-metadata");Je.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 _4(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Je.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(Je.BASE_PATH,t).href}function Xnt(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 AS(t,e={},n=3,r=!1){let i=new Headers(Je.HEADERS),s="",o={};if(typeof t=="object"){let d=t;new Headers(d.headers).forEach((f,m)=>i.set(m,f)),s=d.metadataKey,o=d.params||o,n=d.noResponseRetries||n,r=d.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(Xnt(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((d,f)=>i.set(f,d)),o=e.params||o);let a=r?Jnt:y4.request,c={url:`${_4()}/${s}`,headers:i,retryConfig:{noResponseRetries:n},params:o,responseType:"text",timeout:Ywe()};Vwe.info("instance request %j",c);let l=await a(c);Vwe.info("instance metadata is %s",l.data);let u=l.headers.get(Je.HEADER_NAME);if(u!==Je.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${Je.HEADER_NAME} header. Expected '${Je.HEADER_VALUE}', got ${u?`'${u}'`:"no header"}`);if(typeof l.data=="string")try{return znt.parse(l.data)}catch{}return l.data}async function Jnt(t){let e={...t,url:t.url?.toString().replace(_4(),_4(Je.SECONDARY_HOST_ADDRESS))},n=(0,y4.request)(t),r=(0,y4.request)(e);return Promise.any([n,r])}function Qnt(t){return AS("instance",t)}function Znt(t){return AS("project",t)}function ert(t){return AS("universe",t)}async function trt(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await AS(n),i=n.metadataKey;e[i]=r})())),e}function nrt(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var yP;async function rrt(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in Je.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(Je.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return v4();case"ping-only":}}try{return yP===void 0&&(yP=AS("instance",void 0,nrt(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await yP,!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 irt(){yP=void 0}Je.gcpResidencyCache=null;function v4(){return Je.gcpResidencyCache===null&&Kwe(),Je.gcpResidencyCache}function Kwe(t=null){Je.gcpResidencyCache=t!==null?t:(0,Knt.detectGCPResidency)()}function Ywe(){return v4()?0:3e3}Vnt(u4(),Je)});var Qwe=B(_P=>{"use strict";_P.byteLength=ort;_P.toByteArray=crt;_P.fromByteArray=drt;var ol=[],Yo=[],srt=typeof Uint8Array<"u"?Uint8Array:Array,E4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(lm=0,Xwe=E4.length;lm<Xwe;++lm)ol[lm]=E4[lm],Yo[E4.charCodeAt(lm)]=lm;var lm,Xwe;Yo[45]=62;Yo[95]=63;function Jwe(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 ort(t){var e=Jwe(t),n=e[0],r=e[1];return(n+r)*3/4-r}function art(t,e,n){return(e+n)*3/4-n}function crt(t){var e,n=Jwe(t),r=n[0],i=n[1],s=new srt(art(t,r,i)),o=0,a=i>0?r-4:r,c;for(c=0;c<a;c+=4)e=Yo[t.charCodeAt(c)]<<18|Yo[t.charCodeAt(c+1)]<<12|Yo[t.charCodeAt(c+2)]<<6|Yo[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Yo[t.charCodeAt(c)]<<2|Yo[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Yo[t.charCodeAt(c)]<<10|Yo[t.charCodeAt(c+1)]<<4|Yo[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function lrt(t){return ol[t>>18&63]+ol[t>>12&63]+ol[t>>6&63]+ol[t&63]}function urt(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(lrt(r));return i.join("")}function drt(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,a=n-r;o<a;o+=s)i.push(urt(t,o,o+s>a?a:o+s));return r===1?(e=t[n-1],i.push(ol[e>>2]+ol[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(ol[e>>10]+ol[e>>4&63]+ol[e<<2&63]+"=")),i.join("")}});var S4=B(w4=>{"use strict";Object.defineProperty(w4,"__esModule",{value:!0});w4.fromArrayBufferToHex=frt;function frt(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Zwe=B(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.BrowserCrypto=void 0;var j_=Qwe(),prt=S4(),x4=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 j_.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),j_.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"}},s=new TextEncoder().encode(n),o=j_.toByteArray(t.padBase64(r)),a=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,a,Buffer.from(o),s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),o=await window.crypto.subtle.sign(r,s,i);return j_.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(e){let n=j_.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return j_.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,prt.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,s=await window.crypto.subtle.importKey("raw",i.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,i.encode(n))}};vP.BrowserCrypto=x4});var eSe=B(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.NodeCrypto=void 0;var W_=require("crypto"),b4=class{async sha256DigestBase64(e){return W_.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return W_.randomBytes(e).toString("base64")}async verify(e,n,r){let i=W_.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,r,"base64")}async sign(e,n){let r=W_.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 W_.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:mrt(e);return hrt(W_.createHmac("sha256",r).update(n).digest())}};EP.NodeCrypto=b4;function hrt(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 mrt(t){return Buffer.from(t)}});var RS=B(Uu=>{"use strict";var grt=Uu&&Uu.__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]})),yrt=Uu&&Uu.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&grt(e,t,n)};Object.defineProperty(Uu,"__esModule",{value:!0});Uu.createCrypto=Ert;Uu.hasBrowserCrypto=tSe;var _rt=Zwe(),vrt=eSe();yrt(S4(),Uu);function Ert(){return tSe()?new _rt.BrowserCrypto:new vrt.NodeCrypto}function tSe(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var ec=B(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.LRUCache=void 0;Fu.snakeToCamel=rSe;Fu.originalOrCamelOptions=brt;Fu.removeUndefinedValuesInObject=Trt;Fu.isValidFile=Art;Fu.getWellKnownCertificateConfigFileLocation=Crt;var wrt=require("fs"),Srt=require("os"),T4=require("path"),xrt="certificate_config.json",nSe="gcloud";function rSe(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function brt(t){function e(n){let r=t||{};return r[n]??r[rSe(n)]}return{get:e}}var A4=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()}};Fu.LRUCache=A4;function Trt(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Art(t){try{return(await wrt.promises.lstat(t)).isFile()}catch{return!1}}function Crt(){let t=process.env.CLOUDSDK_CONFIG||(Rrt()?T4.join(process.env.APPDATA||"",nSe):T4.join(process.env.HOME||"",".config",nSe));return T4.join(t,xrt)}function Rrt(){return Srt.platform().startsWith("win")}});var iSe=B((cMt,Irt)=>{Irt.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 C4=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});Of.USER_AGENT=Of.PRODUCT_NAME=Of.pkg=void 0;var sSe=iSe();Of.pkg=sSe;var oSe="google-api-nodejs-client";Of.PRODUCT_NAME=oSe;var krt=`${oSe}/${sSe.version}`;Of.USER_AGENT=krt});var no=B(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.AuthClient=tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=tc.DEFAULT_UNIVERSE=void 0;var Prt=require("events"),R4=di(),Ort=ec(),Mrt=g4(),I4=C4();tc.DEFAULT_UNIVERSE="googleapis.com";tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var k4=class t extends Prt.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=tc.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,Ort.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")??tc.DEFAULT_UNIVERSE,this.transporter=e.transporter??new R4.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,s=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&&R4.Gaxios.mergeHeaders(s,n.headers),r&&R4.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:i}):this.request({...r,headers:s,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,Mrt.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(`${I4.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${I4.USER_AGENT}`):e.headers.set("User-Agent",I4.USER_AGENT);try{let r=e,i=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let o={url:e.url,headers:e.headers};i?t.log.info("%s [%s] request %j",i,s,o):t.log.info("[%s] request %j",s,o)}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"]}}}};tc.AuthClient=k4});var O4=B(wP=>{"use strict";Object.defineProperty(wP,"__esModule",{value:!0});wP.LoginTicket=void 0;var P4=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()}}};wP.LoginTicket=P4});var Mf=B(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.OAuth2Client=al.ClientAuthentication=al.CertificateFormat=al.CodeChallengeMethod=void 0;var aSe=di(),Nrt=require("querystring"),Drt=require("stream"),Lrt=hq(),cSe=ec(),M4=RS(),V_=no(),Urt=O4(),lSe;(function(t){t.Plain="plain",t.S256="S256"})(lSe||(al.CodeChallengeMethod=lSe={}));var Bu;(function(t){t.PEM="PEM",t.JWK="JWK"})(Bu||(al.CertificateFormat=Bu={}));var IS;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(IS||(al.ClientAuthentication=IS={}));var N4=class t extends V_.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Bu.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||IS.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()+"?"+Nrt.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,M4.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}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===IS.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===IS.ClientSecretPost&&(i.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,cSe.removeUndefinedValuesInObject)(i)),headers:r};V_.AuthClient.setMethodName(s,"getTokenAsync");let o=await this.transporter.request(s),a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}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 o={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,cSe.removeUndefinedValuesInObject)(r))};V_.AuthClient.setMethodName(o,"refreshTokenNoCache"),i=await this.transporter.request(o)}catch(o){throw o instanceof aSe.GaxiosError&&o.message==="invalid_grant"&&o.response?.data&&/ReAuth/i.test(o.response.data.error_description)&&(o.message=JSON.stringify(o.response.data)),o}let s=i.data;return i.data&&i.data.expires_in&&(s.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,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 a=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(a)}}if(this.refreshHandler){let a=await this.processAndValidateRefreshHandler();if(a?.access_token){this.setCredentials(a);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(a){let c=a;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let s=this.credentials;s.token_type=s.token_type||"Bearer",i.refresh_token=s.refresh_token,this.credentials=i;let o=new Headers({authorization:s.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(o),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(V_.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=aSe.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 s=i.status,o=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),a=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=i.config.data instanceof Drt.Readable,l=s===401||s===403;if(!n&&l&&!c&&o)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&l&&!c&&a){let u=await this.processAndValidateRefreshHandler();return u?.access_token&&this.setCredentials(u),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,M4.hasBrowserCrypto)()?Bu.JWK:Bu.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case Bu.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Bu.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let l={...t.RETRY_CONFIG,url:i};V_.AuthClient.setMethodName(l,"getFederatedSignonCertsAsync"),r=await this.transporter.request(l)}catch(l){throw l instanceof Error&&(l.message=`Failed to retrieve verification certificates: ${l.message}`),l}let s=r?.headers.get("cache-control"),o=-1;if(s){let l=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;l&&(o=Number(l)*1e3)}let a={};switch(n){case Bu.PEM:a=r.data;break;case Bu.JWK:for(let l of r.data.keys)a[l.kid]=l;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=o===-1?null:new Date(c.getTime()+o),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,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};V_.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,s){let o=(0,M4.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let a=e.split(".");if(a.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=a[0]+"."+a[1],l=a[2],u,d;try{u=JSON.parse(o.decodeBase64StringUtf8(a[0]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token envelope: ${a[0]}': ${R.message}`),R}if(!u)throw new Error("Can't parse token envelope: "+a[0]);try{d=JSON.parse(o.decodeBase64StringUtf8(a[1]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token payload '${a[0]}`),R}if(!d)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(n,u.kid))throw new Error("No pem found for envelope: "+JSON.stringify(u));let f=n[u.kid];if(u.alg==="ES256"&&(l=Lrt.joseToDer(l,"ES256").toString("base64")),!await o.verify(f,c,l))throw new Error("Invalid token signature: "+e);if(!d.iat)throw new Error("No issue time in token: "+JSON.stringify(d));if(!d.exp)throw new Error("No expiration time in token: "+JSON.stringify(d));let g=Number(d.iat);if(isNaN(g))throw new Error("iat field using invalid format");let y=Number(d.exp);if(isNaN(y))throw new Error("exp field using invalid format");let w=new Date().getTime()/1e3;if(y>=w+s)throw new Error("Expiration time too far in future: "+JSON.stringify(d));let S=g-t.CLOCK_SKEW_SECS_,T=y+t.CLOCK_SKEW_SECS_;if(w<S)throw new Error("Token used too early, "+w+" < "+S+": "+JSON.stringify(d));if(w>T)throw new Error("Token used too late, "+w+" > "+T+": "+JSON.stringify(d));if(i&&i.indexOf(d.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+d.iss);if(typeof r<"u"&&r!==null){let R=d.aud,C=!1;if(r.constructor===Array?C=r.indexOf(R)>-1:C=R===r,!C)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Urt.LoginTicket(u,d)}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}};al.OAuth2Client=N4});var L4=B(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.Compute=void 0;var Frt=di(),uSe=CS(),Brt=Mf(),D4=class extends Brt.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 uSe.instance(i)}catch(i){throw i instanceof Frt.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 uSe.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))}};SP.Compute=D4});var F4=B(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.IdTokenClient=void 0;var qrt=Mf(),U4=class extends qrt.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}};xP.IdTokenClient=U4});var B4=B(z_=>{"use strict";Object.defineProperty(z_,"__esModule",{value:!0});z_.GCPEnv=void 0;z_.clear=$rt;z_.getEnv=Grt;var dSe=CS(),cl;(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"})(cl||(z_.GCPEnv=cl={}));var kS;function $rt(){kS=void 0}async function Grt(){return kS||(kS=Hrt(),kS)}async function Hrt(){let t=cl.NONE;return jrt()?t=cl.APP_ENGINE:Wrt()?t=cl.CLOUD_FUNCTIONS:await Yrt()?await Krt()?t=cl.KUBERNETES_ENGINE:Vrt()?t=cl.CLOUD_RUN:zrt()?t=cl.CLOUD_RUN_JOBS:t=cl.COMPUTE_ENGINE:t=cl.NONE,t}function jrt(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Wrt(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Vrt(){return!!process.env.K_CONFIGURATION}function zrt(){return!!process.env.CLOUD_RUN_JOB}async function Krt(){try{return await dSe.instance("attributes/cluster-name"),!0}catch{return!1}}async function Yrt(){return dSe.isAvailable()}});var pSe=B(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.buildPayloadForJwsSign=fSe;bP.getJwsSign=Zrt;var Xrt=dR(),Jrt="RS256",Qrt="https://oauth2.googleapis.com/token";function fSe(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:Qrt,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function Zrt(t){let e=fSe(t);return(0,Xrt.sign)({header:{alg:Jrt},payload:e,secret:t.key})}});var hSe=B(q4=>{"use strict";Object.defineProperty(q4,"__esModule",{value:!0});q4.getToken=iit;var eit=pSe(),tit="https://oauth2.googleapis.com/token",nit="urn:ietf:params:oauth:grant-type:jwt-bearer",rit=t=>({method:"POST",url:tit,data:new URLSearchParams({grant_type:nit,assertion:(0,eit.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function iit(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=rit(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 mSe=B(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.ErrorWithCode=void 0;var $4=class extends Error{code;constructor(e,n){super(e),this.code=n}};TP.ErrorWithCode=$4});var z4=B(V4=>{"use strict";Object.defineProperty(V4,"__esModule",{value:!0});V4.getCredentials=ait;var sit=require("path"),gSe=require("fs"),oit=require("util"),AP=mSe(),ySe=gSe.readFile?(0,oit.promisify)(gSe.readFile):async()=>{throw new AP.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Nf;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Nf||(Nf={}));var G4=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await ySe(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let o=s;throw new Error(`Invalid JSON key file: ${o.message}`)}let r=n.private_key,i=n.client_email;if(!r||!i)throw new AP.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:i}}},H4=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await ySe(this.keyFilePath,"utf8")}}},j4=class{async getCredentials(){throw new AP.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")}},W4=class{static create(e){switch(sit.extname(e)){case Nf.JSON:return new G4(e);case Nf.DER:case Nf.CRT:case Nf.PEM:return new H4(e);case Nf.P12:case Nf.PFX:return new j4;default:throw new AP.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function ait(t){return W4.create(t).getCredentials()}});var _Se=B(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.TokenHandler=void 0;var cit=hSe(),lit=z4(),K4=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,lit.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,cit.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}}};CP.TokenHandler=K4});var vSe=B(Y4=>{"use strict";Object.defineProperty(Y4,"__esModule",{value:!0});Y4.revokeToken=fit;var uit="https://oauth2.googleapis.com/revoke?token=",dit=!0;async function fit(t,e){let n=uit+t;return await e.request({url:n,retry:dit})}});var J4=B(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.GoogleToken=void 0;var pit=di(),ESe=_Se(),hit=vSe(),X4=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,pit.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 ESe.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(s=>r(null,s),r),i}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,hit.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new ESe.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};RP.GoogleToken=X4});var Z4=B(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.JWTAccess=void 0;var mit=dR(),git=ec(),wSe={alg:"RS256",typ:"JWT"},Q4=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new git.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),s=this.cache.get(i),o=Date.now();if(s&&s.expiration-o>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let a=Math.floor(Date.now()/1e3),c=t.getExpirationTime(a),l;if(Array.isArray(r)&&(r=r.join(" ")),r?l={iss:this.email,sub:this.email,scope:r,exp:c,iat:a}:l={iss:this.email,sub:this.email,aud:e,exp:c,iat:a},n){for(let g in l)if(n[g])throw new Error(`The '${g}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let u=this.keyId?{...wSe,kid:this.keyId}:wSe,d=Object.assign(l,n),f=mit.sign({header:u,payload:d,secret:this.key}),m=new Headers({authorization:`Bearer ${f}`});return this.cache.set(i,{expiration:c*1e3,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",s=>i+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(i);this.fromJSON(s),n()}catch(s){r(s)}})})}};IP.JWTAccess=Q4});var tW=B(PP=>{"use strict";Object.defineProperty(PP,"__esModule",{value:!0});PP.JWT=void 0;var SSe=J4(),yit=z4(),_it=Z4(),vit=Mf(),kP=no(),eW=class t extends vit.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!==kP.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==kP.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${kP.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 _it.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!==kP.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new SSe.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 SSe.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",s=>i+=s).on("end",()=>{try{let s=JSON.parse(i);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,yit.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.")}};PP.JWT=eW});var rW=B(K_=>{"use strict";Object.defineProperty(K_,"__esModule",{value:!0});K_.UserRefreshClient=K_.USER_REFRESH_ACCOUNT_TYPE=void 0;var Eit=Mf(),wit=no();K_.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var nW=class t extends Eit.OAuth2Client{_refreshToken;constructor(e,n,r,i,s){let o=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:s};super(o),this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.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 wit.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",s=>i+=s).on("end",()=>{try{let s=JSON.parse(i);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};K_.UserRefreshClient=nW});var sW=B(Y_=>{"use strict";Object.defineProperty(Y_,"__esModule",{value:!0});Y_.Impersonated=Y_.IMPERSONATED_ACCOUNT_TYPE=void 0;var xSe=Mf(),Sit=di(),xit=ec();Y_.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var iW=class t extends xSe.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 xSe.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,xit.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"}),s=i.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof Sit.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`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:s,method:"POST"})).data.token}};Y_.Impersonated=iW});var aW=B(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});PS.OAuthClientAuthHandler=void 0;PS.getErrorFromOAuthErrorResponse=Ait;var X_=di(),bit=RS(),Tit=["PUT","POST","PATCH"],oW=class{#e=(0,bit.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new X_.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new X_.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=X_.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=X_.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=X_.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,i=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${i}`);X_.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!Tit.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 s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}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"]}}}};PS.OAuthClientAuthHandler=oW;function Ait(t,e){let n=t.error,r=t.error_description,i=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof i<"u"&&(s+=` - ${i}`);let o=new Error(s);if(e){let a=Object.keys(e);e.stack&&a.push("stack"),a.forEach(c=>{c!=="message"&&Object.defineProperty(o,c,{value:e[c],writable:!1,enumerable:!0})})}return o}});var MP=B(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.StsCredentials=void 0;var Cit=di(),Rit=no(),bSe=aW(),Iit=ec(),cW=class t extends bSe.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)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,Iit.removeUndefinedValuesInObject)(i)),responseType:"json"};Rit.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let o=await this.transporter.request(s),a=o.data;return a.res=o,a}catch(o){throw o instanceof Cit.GaxiosError&&o.response?(0,bSe.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}};OP.StsCredentials=cW});var Df=B(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.BaseExternalAccountClient=Xo.CLOUD_RESOURCE_MANAGER=Xo.EXTERNAL_ACCOUNT_TYPE=Xo.EXPIRATION_TIME_OFFSET=void 0;var kit=di(),Pit=require("stream"),lW=no(),Oit=MP(),TSe=ec(),Mit=C4(),Nit="urn:ietf:params:oauth:grant-type:token-exchange",Dit="urn:ietf:params:oauth:token-type:access_token",uW="https://www.googleapis.com/auth/cloud-platform",Lit=3600;Xo.EXPIRATION_TIME_OFFSET=300*1e3;Xo.EXTERNAL_ACCOUNT_TYPE="external_account";Xo.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Uit="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Fit="https://sts.{universeDomain}/v1/token",dW=class t extends lW.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,TSe.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Xo.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Xo.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??Fit.replace("{universeDomain}",this.universeDomain);let o=n.get("subject_token_type"),a=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),l=n.get("service_account_impersonation"),u=(0,TSe.originalOrCamelOptions)(l).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:s}),this.stsCredential=new Oit.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[uW],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=o,this.workforcePoolUserProject=a;let d=new RegExp(Uit);if(this.workforcePoolUserProject&&!this.audience.match(d))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=u,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Lit),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"};lW.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=kit.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof Pit.Readable;if(!n&&(o===401||o===403)&&!a&&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:Nit,audience:this.audience,requestedTokenType:Dit,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[uW]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,i,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};lW.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||[uW]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Mit.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Xo.BaseExternalAccountClient=dW});var ASe=B(NP=>{"use strict";Object.defineProperty(NP,"__esModule",{value:!0});NP.FileSubjectTokenSupplier=void 0;var pW=require("util"),hW=require("fs"),Bit=(0,pW.promisify)(hW.readFile??(()=>{})),qit=(0,pW.promisify)(hW.realpath??(()=>{})),$it=(0,pW.promisify)(hW.lstat??(()=>{})),fW=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 qit(e),!(await $it(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 Bit(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}};NP.FileSubjectTokenSupplier=fW});var CSe=B(DP=>{"use strict";Object.defineProperty(DP,"__esModule",{value:!0});DP.UrlSubjectTokenSupplier=void 0;var Git=no(),mW=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};Git.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}};DP.UrlSubjectTokenSupplier=mW});var RSe=B(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.CertificateSubjectTokenSupplier=ro.InvalidConfigurationError=ro.CertificateSourceUnavailableError=ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var LP=ec(),UP=require("fs"),FP=require("crypto"),Hit=require("https");ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var ll=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};ro.CertificateSourceUnavailableError=ll;var Jo=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};ro.InvalidConfigurationError=Jo;var gW=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Jo("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Jo("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Jo("Cannot create mTLS Agent with missing certificate or key");return new Hit.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,LP.isValidFile)(e))return e;throw new ll(`Provided certificate config path is invalid: ${e}`)}let n=process.env[ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,LP.isValidFile)(n))return n;throw new ll(`Path from environment variable "${ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,LP.getWellKnownCertificateConfigFileLocation)();if(await(0,LP.isValidFile)(r))return r;throw new ll(`Could not find certificate configuration file. Searched override path, the "${ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await UP.promises.readFile(e,"utf8")}catch{throw new ll(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),i=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!i||!s)throw new Jo(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:s}}catch(r){throw r instanceof Jo?r:new Jo(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,i;try{r=await UP.promises.readFile(e),new FP.X509Certificate(r)}catch(s){let o=s instanceof Error?s.message:String(s);throw new ll(`Failed to read certificate file at ${e}: ${o}`)}try{i=await UP.promises.readFile(n),(0,FP.createPrivateKey)(i)}catch(s){let o=s instanceof Error?s.message:String(s);throw new ll(`Failed to read private key file at ${n}: ${o}`)}return{cert:r,key:i}}async#r(e){let n=new FP.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await UP.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,l)=>{try{return new FP.X509Certificate(c)}catch(u){let d=u instanceof Error?u.message:String(u);throw new Jo(`Failed to parse certificate at index ${l} in trust chain file ${this.trustChainPath}: ${d}`)}}),o=s.findIndex(c=>n.raw.equals(c.raw)),a;if(o===-1)a=[n,...s];else if(o===0)a=s;else throw new Jo(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);return JSON.stringify(a.map(c=>c.raw.toString("base64")))}catch(r){if(r instanceof Jo)throw r;let i=r instanceof Error?r.message:String(r);throw new ll(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};ro.CertificateSubjectTokenSupplier=gW});var vW=B(BP=>{"use strict";Object.defineProperty(BP,"__esModule",{value:!0});BP.IdentityPoolClient=void 0;var jit=Df(),yW=ec(),Wit=ASe(),Vit=CSe(),ISe=RSe(),zit=MP(),kSe=di(),_W=class t extends jit.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,yW.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 s=(0,yW.originalOrCamelOptions)(r),o=(0,yW.originalOrCamelOptions)(s.get("format")),a=o.get("type")||"text",c=o.get("subject_token_field_name");if(a!=="json"&&a!=="text")throw new Error(`Invalid credential_source format "${a}"`);if(a==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let l=s.get("file"),u=s.get("url"),d=s.get("certificate"),f=s.get("headers");if(l&&u||u&&d||l&&d)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(l)this.credentialSourceType="file",this.subjectTokenSupplier=new Wit.FileSubjectTokenSupplier({filePath:l,formatType:a,subjectTokenFieldName:c});else if(u)this.credentialSourceType="url",this.subjectTokenSupplier=new Vit.UrlSubjectTokenSupplier({url:u,formatType:a,subjectTokenFieldName:c,headers:f,additionalGaxiosOptions:t.RETRY_CONFIG});else if(d){this.credentialSourceType="certificate";let m=new ISe.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:d.use_default_certificate_config,certificateConfigLocation:d.certificate_config_location,trustChainPath:d.trust_chain_path});this.subjectTokenSupplier=m}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof ISe.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new zit.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new kSe.Gaxios({agent:n})}),this.transporter=new kSe.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};BP.IdentityPoolClient=_W});var wW=B($P=>{"use strict";Object.defineProperty($P,"__esModule",{value:!0});$P.AwsRequestSigner=void 0;var qP=di(),OSe=RS(),PSe="AWS4-HMAC-SHA256",Kit="aws4_request",EW=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,OSe.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",s=e.body||n,o=e.headers,a=await this.getCredentials(),c=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let l=await Xit({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:i,region:this.region,securityCredentials:a,requestPayload:s,additionalAmzHeaders:o}),u=qP.Gaxios.mergeHeaders(l.amzDate?{"x-amz-date":l.amzDate}:{},{authorization:l.authorizationHeader,host:c.host},o||{});a.token&&qP.Gaxios.mergeHeaders(u,{"x-amz-security-token":a.token});let d={url:r,method:i,headers:u};return s!==void 0&&(d.body=s),d}};$P.AwsRequestSigner=EW;async function OS(t,e,n){return await t.signWithHmacSha256(e,n)}async function Yit(t,e,n,r,i){let s=await OS(t,`AWS4${e}`,n),o=await OS(t,s,r),a=await OS(t,o,i);return await OS(t,a,"aws4_request")}async function Xit(t){let e=qP.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],i=new Date,s=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),o=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let a=qP.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),c="",l=[...a.keys()].sort();l.forEach(T=>{c+=`${T}:${a.get(T)}
502
+ `,r:"\r",t:" "},s,o=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},a=function(y){return y&&y!==r&&o("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},c=function(){var y,w="";for(r==="-"&&(w="-",a("-"));r>="0"&&r<="9";)w+=r,a();if(r===".")for(w+=".";a()&&r>="0"&&r<="9";)w+=r;if(r==="e"||r==="E")for(w+=r,a(),(r==="-"||r==="+")&&(w+=r,a());r>="0"&&r<="9";)w+=r,a();if(y=+w,!isFinite(y))o("Bad number");else return hP==null&&(hP=l4()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new hP(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new hP(y):y},l=function(){var y,w,S="",T;if(r==='"')for(var R=n;a();){if(r==='"')return n-1>R&&(S+=s.substring(R,n-1)),a(),S;if(r==="\\"){if(n-1>R&&(S+=s.substring(R,n-1)),a(),r==="u"){for(T=0,w=0;w<4&&(y=parseInt(a(),16),!!isFinite(y));w+=1)T=T*16+y;S+=String.fromCharCode(T)}else if(typeof i[r]=="string")S+=i[r];else break;R=n}}o("Bad string")},u=function(){for(;r&&r<=" ";)a()},d=function(){switch(r){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}o("Unexpected '"+r+"'")},f,m=function(){var y=[];if(r==="["){if(a("["),u(),r==="]")return a("]"),y;for(;r;){if(y.push(f()),u(),r==="]")return a("]"),y;a(","),u()}}o("Bad array")},g=function(){var y,w=Object.create(null);if(r==="{"){if(a("{"),u(),r==="}")return a("}"),w;for(;r;){if(y=l(),u(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(w,y)&&o('Duplicate key "'+y+'"'),Pnt.test(y)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?f():w[y]=f():Ont.test(y)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?f():w[y]=f():w[y]=f(),u(),r==="}")return a("}"),w;a(","),u()}}o("Bad object")};return f=function(){switch(u(),r){case"{":return g();case"[":return m();case'"':return l();case"-":return c();default:return r>="0"&&r<="9"?c():d()}},function(y,w){var S;return s=y+"",n=0,r=" ",S=f(),u(),r&&o("Syntax error"),typeof w=="function"?(function T(R,C){var D,$,G=R[C];return G&&typeof G=="object"&&Object.keys(G).forEach(function(V){$=T(G,V),$!==void 0?G[V]=$:delete G[V]}),w.call(R,C,G)})({"":S},""):S}};kwe.exports=Mnt});var Nwe=B((X1t,mP)=>{var Owe=Iwe().stringify,Mwe=Pwe();mP.exports=function(t){return{parse:Mwe(t),stringify:Owe}};mP.exports.parse=Mwe();mP.exports.stringify=Owe});var u4=B(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.GCE_LINUX_BIOS_PATHS=void 0;Qa.isGoogleCloudServerless=Uwe;Qa.isGoogleComputeEngineLinux=Fwe;Qa.isGoogleComputeEngineMACAddress=Bwe;Qa.isGoogleComputeEngine=qwe;Qa.detectGCPResidency=Dnt;var Dwe=require("fs"),Lwe=require("os");Qa.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Nnt=/^42:01/;function Uwe(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Fwe(){if((0,Lwe.platform)()!=="linux")return!1;try{(0,Dwe.statSync)(Qa.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Dwe.readFileSync)(Qa.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Bwe(){let t=(0,Lwe.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(Nnt.test(n))return!0}return!1}function qwe(){return Fwe()||Bwe()}function Dnt(){return Uwe()||qwe()}});var $we=B(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Colours=void 0;var Ci=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="")}};gP.Colours=Ci;Ci.enabled=!1;Ci.reset="";Ci.bright="";Ci.dim="";Ci.red="";Ci.green="";Ci.yellow="";Ci.blue="";Ci.magenta="";Ci.cyan="";Ci.white="";Ci.grey="";Ci.refresh()});var Wwe=B(wn=>{"use strict";var Lnt=wn&&wn.__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]})),Unt=wn&&wn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gwe=wn&&wn.__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"&&Lnt(n,e,r[i]);return Unt(n,e),n}})();Object.defineProperty(wn,"__esModule",{value:!0});wn.env=wn.DebugLogBackendBase=wn.placeholder=wn.AdhocDebugLogger=wn.LogSeverity=void 0;wn.getNodeBackend=f4;wn.getDebugBackend=Bnt;wn.getStructuredBackend=qnt;wn.setBackend=$nt;wn.log=jwe;var Fnt=require("events"),bS=Gwe(require("process")),Hwe=Gwe(require("util")),eo=$we(),Za;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Za||(wn.LogSeverity=Za={}));var TS=class extends Fnt.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(Za.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Za.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Za.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Za.ERROR,...r),this.func.sublog=r=>jwe(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)}};wn.AdhocDebugLogger=TS;wn.placeholder=new TS("",()=>{}).func;var H_=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=bS.env[wn.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)}}};wn.DebugLogBackendBase=H_;var d4=class extends H_{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 s=`${eo.Colours.green}${e}${eo.Colours.reset}`,o=`${eo.Colours.yellow}${bS.pid}${eo.Colours.reset}`,a;switch(n.severity){case Za.ERROR:a=`${eo.Colours.red}${n.severity}${eo.Colours.reset}`;break;case Za.INFO:a=`${eo.Colours.magenta}${n.severity}${eo.Colours.reset}`;break;case Za.WARNING:a=`${eo.Colours.yellow}${n.severity}${eo.Colours.reset}`;break;default:a=(i=n.severity)!==null&&i!==void 0?i:Za.DEFAULT;break}let c=Hwe.formatWithOptions({colors:eo.Colours.enabled},...r),l=Object.assign({},n);delete l.severity;let u=Object.getOwnPropertyNames(l).length?JSON.stringify(l):"",d=u?`${eo.Colours.grey}${u}${eo.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",o,s,a,c,u?` ${d}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function f4(){return new d4}var p4=class extends H_{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=bS.env.NODE_DEBUG)!==null&&e!==void 0?e:"";bS.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function Bnt(t){return new p4(t)}var h4=class extends H_{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,...s)=>{var o;let a=(o=i.severity)!==null&&o!==void 0?o:Za.INFO,c=Object.assign({severity:a,message:Hwe.format(...s)},i),l=JSON.stringify(c);r?r(i,l):console.log("%s",l)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function qnt(t){return new h4(t)}wn.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var m4=new Map,to;function $nt(t){to=t,m4.clear()}function jwe(t,e){if(!to&&!bS.env[wn.env.nodeEnables]||!t)return wn.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=m4.get(t);if(n)return n.func;if(to===null)return wn.placeholder;to===void 0&&(to=f4());let r=(()=>{let i;return new TS(t,(o,...a)=>{if(i!==to){if(to===null)return;to===void 0&&(to=f4()),i=to}to?.log(t,o,...a)})})();return m4.set(t,r),r.func}});var g4=B(cm=>{"use strict";var Gnt=cm&&cm.__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]})),Hnt=cm&&cm.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Gnt(e,t,n)};Object.defineProperty(cm,"__esModule",{value:!0});Hnt(Wwe(),cm)});var CS=B(Je=>{"use strict";var zwe=Je&&Je.__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]})),jnt=Je&&Je.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wnt=Je&&Je.__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"&&zwe(n,e,r[i]);return jnt(n,e),n}})(),Vnt=Je&&Je.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zwe(e,t,n)};Object.defineProperty(Je,"__esModule",{value:!0});Je.gcpResidencyCache=Je.METADATA_SERVER_DETECTION=Je.HEADERS=Je.HEADER_VALUE=Je.HEADER_NAME=Je.SECONDARY_HOST_ADDRESS=Je.HOST_ADDRESS=Je.BASE_PATH=void 0;Je.instance=Qnt;Je.project=Znt;Je.universe=ert;Je.bulk=trt;Je.isAvailable=rrt;Je.resetIsAvailableCache=irt;Je.getGCPResidency=v4;Je.setGCPResidency=Kwe;Je.requestTimeout=Ywe;var y4=di(),znt=Nwe(),Knt=u4(),Ynt=Wnt(g4());Je.BASE_PATH="/computeMetadata/v1";Je.HOST_ADDRESS="http://169.254.169.254";Je.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Je.HEADER_NAME="Metadata-Flavor";Je.HEADER_VALUE="Google";Je.HEADERS=Object.freeze({[Je.HEADER_NAME]:Je.HEADER_VALUE});var Vwe=Ynt.log("gcp-metadata");Je.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 _4(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Je.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(Je.BASE_PATH,t).href}function Xnt(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 AS(t,e={},n=3,r=!1){let i=new Headers(Je.HEADERS),s="",o={};if(typeof t=="object"){let d=t;new Headers(d.headers).forEach((f,m)=>i.set(m,f)),s=d.metadataKey,o=d.params||o,n=d.noResponseRetries||n,r=d.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(Xnt(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((d,f)=>i.set(f,d)),o=e.params||o);let a=r?Jnt:y4.request,c={url:`${_4()}/${s}`,headers:i,retryConfig:{noResponseRetries:n},params:o,responseType:"text",timeout:Ywe()};Vwe.info("instance request %j",c);let l=await a(c);Vwe.info("instance metadata is %s",l.data);let u=l.headers.get(Je.HEADER_NAME);if(u!==Je.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${Je.HEADER_NAME} header. Expected '${Je.HEADER_VALUE}', got ${u?`'${u}'`:"no header"}`);if(typeof l.data=="string")try{return znt.parse(l.data)}catch{}return l.data}async function Jnt(t){let e={...t,url:t.url?.toString().replace(_4(),_4(Je.SECONDARY_HOST_ADDRESS))},n=(0,y4.request)(t),r=(0,y4.request)(e);return Promise.any([n,r])}function Qnt(t){return AS("instance",t)}function Znt(t){return AS("project",t)}function ert(t){return AS("universe",t)}async function trt(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await AS(n),i=n.metadataKey;e[i]=r})())),e}function nrt(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var yP;async function rrt(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in Je.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(Je.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return v4();case"ping-only":}}try{return yP===void 0&&(yP=AS("instance",void 0,nrt(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await yP,!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 irt(){yP=void 0}Je.gcpResidencyCache=null;function v4(){return Je.gcpResidencyCache===null&&Kwe(),Je.gcpResidencyCache}function Kwe(t=null){Je.gcpResidencyCache=t!==null?t:(0,Knt.detectGCPResidency)()}function Ywe(){return v4()?0:3e3}Vnt(u4(),Je)});var Qwe=B(_P=>{"use strict";_P.byteLength=ort;_P.toByteArray=crt;_P.fromByteArray=drt;var ol=[],Yo=[],srt=typeof Uint8Array<"u"?Uint8Array:Array,E4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(lm=0,Xwe=E4.length;lm<Xwe;++lm)ol[lm]=E4[lm],Yo[E4.charCodeAt(lm)]=lm;var lm,Xwe;Yo[45]=62;Yo[95]=63;function Jwe(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 ort(t){var e=Jwe(t),n=e[0],r=e[1];return(n+r)*3/4-r}function art(t,e,n){return(e+n)*3/4-n}function crt(t){var e,n=Jwe(t),r=n[0],i=n[1],s=new srt(art(t,r,i)),o=0,a=i>0?r-4:r,c;for(c=0;c<a;c+=4)e=Yo[t.charCodeAt(c)]<<18|Yo[t.charCodeAt(c+1)]<<12|Yo[t.charCodeAt(c+2)]<<6|Yo[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Yo[t.charCodeAt(c)]<<2|Yo[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Yo[t.charCodeAt(c)]<<10|Yo[t.charCodeAt(c+1)]<<4|Yo[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function lrt(t){return ol[t>>18&63]+ol[t>>12&63]+ol[t>>6&63]+ol[t&63]}function urt(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(lrt(r));return i.join("")}function drt(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,a=n-r;o<a;o+=s)i.push(urt(t,o,o+s>a?a:o+s));return r===1?(e=t[n-1],i.push(ol[e>>2]+ol[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(ol[e>>10]+ol[e>>4&63]+ol[e<<2&63]+"=")),i.join("")}});var S4=B(w4=>{"use strict";Object.defineProperty(w4,"__esModule",{value:!0});w4.fromArrayBufferToHex=frt;function frt(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Zwe=B(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.BrowserCrypto=void 0;var j_=Qwe(),prt=S4(),x4=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 j_.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),j_.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"}},s=new TextEncoder().encode(n),o=j_.toByteArray(t.padBase64(r)),a=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,a,Buffer.from(o),s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),o=await window.crypto.subtle.sign(r,s,i);return j_.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(e){let n=j_.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return j_.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,prt.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,s=await window.crypto.subtle.importKey("raw",i.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,i.encode(n))}};vP.BrowserCrypto=x4});var eSe=B(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.NodeCrypto=void 0;var W_=require("crypto"),b4=class{async sha256DigestBase64(e){return W_.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return W_.randomBytes(e).toString("base64")}async verify(e,n,r){let i=W_.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,r,"base64")}async sign(e,n){let r=W_.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 W_.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:mrt(e);return hrt(W_.createHmac("sha256",r).update(n).digest())}};EP.NodeCrypto=b4;function hrt(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 mrt(t){return Buffer.from(t)}});var RS=B(Uu=>{"use strict";var grt=Uu&&Uu.__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]})),yrt=Uu&&Uu.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&grt(e,t,n)};Object.defineProperty(Uu,"__esModule",{value:!0});Uu.createCrypto=Ert;Uu.hasBrowserCrypto=tSe;var _rt=Zwe(),vrt=eSe();yrt(S4(),Uu);function Ert(){return tSe()?new _rt.BrowserCrypto:new vrt.NodeCrypto}function tSe(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var ec=B(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.LRUCache=void 0;Fu.snakeToCamel=rSe;Fu.originalOrCamelOptions=brt;Fu.removeUndefinedValuesInObject=Trt;Fu.isValidFile=Art;Fu.getWellKnownCertificateConfigFileLocation=Crt;var wrt=require("fs"),Srt=require("os"),T4=require("path"),xrt="certificate_config.json",nSe="gcloud";function rSe(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function brt(t){function e(n){let r=t||{};return r[n]??r[rSe(n)]}return{get:e}}var A4=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()}};Fu.LRUCache=A4;function Trt(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Art(t){try{return(await wrt.promises.lstat(t)).isFile()}catch{return!1}}function Crt(){let t=process.env.CLOUDSDK_CONFIG||(Rrt()?T4.join(process.env.APPDATA||"",nSe):T4.join(process.env.HOME||"",".config",nSe));return T4.join(t,xrt)}function Rrt(){return Srt.platform().startsWith("win")}});var iSe=B((cMt,Irt)=>{Irt.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 C4=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});Of.USER_AGENT=Of.PRODUCT_NAME=Of.pkg=void 0;var sSe=iSe();Of.pkg=sSe;var oSe="google-api-nodejs-client";Of.PRODUCT_NAME=oSe;var krt=`${oSe}/${sSe.version}`;Of.USER_AGENT=krt});var no=B(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.AuthClient=tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=tc.DEFAULT_UNIVERSE=void 0;var Prt=require("events"),R4=di(),Ort=ec(),Mrt=g4(),I4=C4();tc.DEFAULT_UNIVERSE="googleapis.com";tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var k4=class t extends Prt.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=tc.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=tc.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,Ort.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")??tc.DEFAULT_UNIVERSE,this.transporter=e.transporter??new R4.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,s=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&&R4.Gaxios.mergeHeaders(s,n.headers),r&&R4.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:i}):this.request({...r,headers:s,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,Mrt.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(`${I4.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${I4.USER_AGENT}`):e.headers.set("User-Agent",I4.USER_AGENT);try{let r=e,i=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let o={url:e.url,headers:e.headers};i?t.log.info("%s [%s] request %j",i,s,o):t.log.info("[%s] request %j",s,o)}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"]}}}};tc.AuthClient=k4});var O4=B(wP=>{"use strict";Object.defineProperty(wP,"__esModule",{value:!0});wP.LoginTicket=void 0;var P4=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()}}};wP.LoginTicket=P4});var Mf=B(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.OAuth2Client=al.ClientAuthentication=al.CertificateFormat=al.CodeChallengeMethod=void 0;var aSe=di(),Nrt=require("querystring"),Drt=require("stream"),Lrt=hq(),cSe=ec(),M4=RS(),V_=no(),Urt=O4(),lSe;(function(t){t.Plain="plain",t.S256="S256"})(lSe||(al.CodeChallengeMethod=lSe={}));var Bu;(function(t){t.PEM="PEM",t.JWK="JWK"})(Bu||(al.CertificateFormat=Bu={}));var IS;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(IS||(al.ClientAuthentication=IS={}));var N4=class t extends V_.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Bu.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||IS.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()+"?"+Nrt.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,M4.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}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===IS.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===IS.ClientSecretPost&&(i.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,cSe.removeUndefinedValuesInObject)(i)),headers:r};V_.AuthClient.setMethodName(s,"getTokenAsync");let o=await this.transporter.request(s),a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}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 o={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,cSe.removeUndefinedValuesInObject)(r))};V_.AuthClient.setMethodName(o,"refreshTokenNoCache"),i=await this.transporter.request(o)}catch(o){throw o instanceof aSe.GaxiosError&&o.message==="invalid_grant"&&o.response?.data&&/ReAuth/i.test(o.response.data.error_description)&&(o.message=JSON.stringify(o.response.data)),o}let s=i.data;return i.data&&i.data.expires_in&&(s.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,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 a=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(a)}}if(this.refreshHandler){let a=await this.processAndValidateRefreshHandler();if(a?.access_token){this.setCredentials(a);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(a){let c=a;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let s=this.credentials;s.token_type=s.token_type||"Bearer",i.refresh_token=s.refresh_token,this.credentials=i;let o=new Headers({authorization:s.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(o),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(V_.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=aSe.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 s=i.status,o=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),a=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=i.config.data instanceof Drt.Readable,l=s===401||s===403;if(!n&&l&&!c&&o)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&l&&!c&&a){let u=await this.processAndValidateRefreshHandler();return u?.access_token&&this.setCredentials(u),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,M4.hasBrowserCrypto)()?Bu.JWK:Bu.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case Bu.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Bu.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let l={...t.RETRY_CONFIG,url:i};V_.AuthClient.setMethodName(l,"getFederatedSignonCertsAsync"),r=await this.transporter.request(l)}catch(l){throw l instanceof Error&&(l.message=`Failed to retrieve verification certificates: ${l.message}`),l}let s=r?.headers.get("cache-control"),o=-1;if(s){let l=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;l&&(o=Number(l)*1e3)}let a={};switch(n){case Bu.PEM:a=r.data;break;case Bu.JWK:for(let l of r.data.keys)a[l.kid]=l;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=o===-1?null:new Date(c.getTime()+o),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,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};V_.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,s){let o=(0,M4.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let a=e.split(".");if(a.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=a[0]+"."+a[1],l=a[2],u,d;try{u=JSON.parse(o.decodeBase64StringUtf8(a[0]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token envelope: ${a[0]}': ${R.message}`),R}if(!u)throw new Error("Can't parse token envelope: "+a[0]);try{d=JSON.parse(o.decodeBase64StringUtf8(a[1]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token payload '${a[0]}`),R}if(!d)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(n,u.kid))throw new Error("No pem found for envelope: "+JSON.stringify(u));let f=n[u.kid];if(u.alg==="ES256"&&(l=Lrt.joseToDer(l,"ES256").toString("base64")),!await o.verify(f,c,l))throw new Error("Invalid token signature: "+e);if(!d.iat)throw new Error("No issue time in token: "+JSON.stringify(d));if(!d.exp)throw new Error("No expiration time in token: "+JSON.stringify(d));let g=Number(d.iat);if(isNaN(g))throw new Error("iat field using invalid format");let y=Number(d.exp);if(isNaN(y))throw new Error("exp field using invalid format");let w=new Date().getTime()/1e3;if(y>=w+s)throw new Error("Expiration time too far in future: "+JSON.stringify(d));let S=g-t.CLOCK_SKEW_SECS_,T=y+t.CLOCK_SKEW_SECS_;if(w<S)throw new Error("Token used too early, "+w+" < "+S+": "+JSON.stringify(d));if(w>T)throw new Error("Token used too late, "+w+" > "+T+": "+JSON.stringify(d));if(i&&i.indexOf(d.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+d.iss);if(typeof r<"u"&&r!==null){let R=d.aud,C=!1;if(r.constructor===Array?C=r.indexOf(R)>-1:C=R===r,!C)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Urt.LoginTicket(u,d)}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}};al.OAuth2Client=N4});var L4=B(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.Compute=void 0;var Frt=di(),uSe=CS(),Brt=Mf(),D4=class extends Brt.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 uSe.instance(i)}catch(i){throw i instanceof Frt.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 uSe.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))}};SP.Compute=D4});var F4=B(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.IdTokenClient=void 0;var qrt=Mf(),U4=class extends qrt.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}};xP.IdTokenClient=U4});var B4=B(z_=>{"use strict";Object.defineProperty(z_,"__esModule",{value:!0});z_.GCPEnv=void 0;z_.clear=$rt;z_.getEnv=Grt;var dSe=CS(),cl;(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"})(cl||(z_.GCPEnv=cl={}));var kS;function $rt(){kS=void 0}async function Grt(){return kS||(kS=Hrt(),kS)}async function Hrt(){let t=cl.NONE;return jrt()?t=cl.APP_ENGINE:Wrt()?t=cl.CLOUD_FUNCTIONS:await Yrt()?await Krt()?t=cl.KUBERNETES_ENGINE:Vrt()?t=cl.CLOUD_RUN:zrt()?t=cl.CLOUD_RUN_JOBS:t=cl.COMPUTE_ENGINE:t=cl.NONE,t}function jrt(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Wrt(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Vrt(){return!!process.env.K_CONFIGURATION}function zrt(){return!!process.env.CLOUD_RUN_JOB}async function Krt(){try{return await dSe.instance("attributes/cluster-name"),!0}catch{return!1}}async function Yrt(){return dSe.isAvailable()}});var pSe=B(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.buildPayloadForJwsSign=fSe;bP.getJwsSign=Zrt;var Xrt=dR(),Jrt="RS256",Qrt="https://oauth2.googleapis.com/token";function fSe(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:Qrt,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function Zrt(t){let e=fSe(t);return(0,Xrt.sign)({header:{alg:Jrt},payload:e,secret:t.key})}});var hSe=B(q4=>{"use strict";Object.defineProperty(q4,"__esModule",{value:!0});q4.getToken=iit;var eit=pSe(),tit="https://oauth2.googleapis.com/token",nit="urn:ietf:params:oauth:grant-type:jwt-bearer",rit=t=>({method:"POST",url:tit,data:new URLSearchParams({grant_type:nit,assertion:(0,eit.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function iit(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=rit(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 mSe=B(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.ErrorWithCode=void 0;var $4=class extends Error{code;constructor(e,n){super(e),this.code=n}};TP.ErrorWithCode=$4});var z4=B(V4=>{"use strict";Object.defineProperty(V4,"__esModule",{value:!0});V4.getCredentials=ait;var sit=require("path"),gSe=require("fs"),oit=require("util"),AP=mSe(),ySe=gSe.readFile?(0,oit.promisify)(gSe.readFile):async()=>{throw new AP.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Nf;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Nf||(Nf={}));var G4=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await ySe(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let o=s;throw new Error(`Invalid JSON key file: ${o.message}`)}let r=n.private_key,i=n.client_email;if(!r||!i)throw new AP.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:i}}},H4=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await ySe(this.keyFilePath,"utf8")}}},j4=class{async getCredentials(){throw new AP.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")}},W4=class{static create(e){switch(sit.extname(e)){case Nf.JSON:return new G4(e);case Nf.DER:case Nf.CRT:case Nf.PEM:return new H4(e);case Nf.P12:case Nf.PFX:return new j4;default:throw new AP.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function ait(t){return W4.create(t).getCredentials()}});var _Se=B(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.TokenHandler=void 0;var cit=hSe(),lit=z4(),K4=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,lit.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,cit.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}}};CP.TokenHandler=K4});var vSe=B(Y4=>{"use strict";Object.defineProperty(Y4,"__esModule",{value:!0});Y4.revokeToken=fit;var uit="https://oauth2.googleapis.com/revoke?token=",dit=!0;async function fit(t,e){let n=uit+t;return await e.request({url:n,retry:dit})}});var J4=B(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.GoogleToken=void 0;var pit=di(),ESe=_Se(),hit=vSe(),X4=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,pit.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 ESe.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(s=>r(null,s),r),i}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,hit.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new ESe.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};RP.GoogleToken=X4});var Z4=B(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.JWTAccess=void 0;var mit=dR(),git=ec(),wSe={alg:"RS256",typ:"JWT"},Q4=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new git.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),s=this.cache.get(i),o=Date.now();if(s&&s.expiration-o>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let a=Math.floor(Date.now()/1e3),c=t.getExpirationTime(a),l;if(Array.isArray(r)&&(r=r.join(" ")),r?l={iss:this.email,sub:this.email,scope:r,exp:c,iat:a}:l={iss:this.email,sub:this.email,aud:e,exp:c,iat:a},n){for(let g in l)if(n[g])throw new Error(`The '${g}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let u=this.keyId?{...wSe,kid:this.keyId}:wSe,d=Object.assign(l,n),f=mit.sign({header:u,payload:d,secret:this.key}),m=new Headers({authorization:`Bearer ${f}`});return this.cache.set(i,{expiration:c*1e3,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",s=>i+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(i);this.fromJSON(s),n()}catch(s){r(s)}})})}};IP.JWTAccess=Q4});var t3=B(PP=>{"use strict";Object.defineProperty(PP,"__esModule",{value:!0});PP.JWT=void 0;var SSe=J4(),yit=z4(),_it=Z4(),vit=Mf(),kP=no(),e3=class t extends vit.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!==kP.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==kP.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${kP.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 _it.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!==kP.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new SSe.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 SSe.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",s=>i+=s).on("end",()=>{try{let s=JSON.parse(i);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,yit.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.")}};PP.JWT=e3});var r3=B(K_=>{"use strict";Object.defineProperty(K_,"__esModule",{value:!0});K_.UserRefreshClient=K_.USER_REFRESH_ACCOUNT_TYPE=void 0;var Eit=Mf(),wit=no();K_.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var n3=class t extends Eit.OAuth2Client{_refreshToken;constructor(e,n,r,i,s){let o=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:s};super(o),this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.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 wit.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",s=>i+=s).on("end",()=>{try{let s=JSON.parse(i);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};K_.UserRefreshClient=n3});var s3=B(Y_=>{"use strict";Object.defineProperty(Y_,"__esModule",{value:!0});Y_.Impersonated=Y_.IMPERSONATED_ACCOUNT_TYPE=void 0;var xSe=Mf(),Sit=di(),xit=ec();Y_.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var i3=class t extends xSe.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 xSe.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,xit.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"}),s=i.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof Sit.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`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:s,method:"POST"})).data.token}};Y_.Impersonated=i3});var a3=B(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});PS.OAuthClientAuthHandler=void 0;PS.getErrorFromOAuthErrorResponse=Ait;var X_=di(),bit=RS(),Tit=["PUT","POST","PATCH"],o3=class{#e=(0,bit.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new X_.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new X_.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=X_.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=X_.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=X_.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,i=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${i}`);X_.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!Tit.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 s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}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"]}}}};PS.OAuthClientAuthHandler=o3;function Ait(t,e){let n=t.error,r=t.error_description,i=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof i<"u"&&(s+=` - ${i}`);let o=new Error(s);if(e){let a=Object.keys(e);e.stack&&a.push("stack"),a.forEach(c=>{c!=="message"&&Object.defineProperty(o,c,{value:e[c],writable:!1,enumerable:!0})})}return o}});var MP=B(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.StsCredentials=void 0;var Cit=di(),Rit=no(),bSe=a3(),Iit=ec(),c3=class t extends bSe.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)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,Iit.removeUndefinedValuesInObject)(i)),responseType:"json"};Rit.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let o=await this.transporter.request(s),a=o.data;return a.res=o,a}catch(o){throw o instanceof Cit.GaxiosError&&o.response?(0,bSe.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}};OP.StsCredentials=c3});var Df=B(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.BaseExternalAccountClient=Xo.CLOUD_RESOURCE_MANAGER=Xo.EXTERNAL_ACCOUNT_TYPE=Xo.EXPIRATION_TIME_OFFSET=void 0;var kit=di(),Pit=require("stream"),l3=no(),Oit=MP(),TSe=ec(),Mit=C4(),Nit="urn:ietf:params:oauth:grant-type:token-exchange",Dit="urn:ietf:params:oauth:token-type:access_token",u3="https://www.googleapis.com/auth/cloud-platform",Lit=3600;Xo.EXPIRATION_TIME_OFFSET=300*1e3;Xo.EXTERNAL_ACCOUNT_TYPE="external_account";Xo.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Uit="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Fit="https://sts.{universeDomain}/v1/token",d3=class t extends l3.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,TSe.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Xo.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Xo.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??Fit.replace("{universeDomain}",this.universeDomain);let o=n.get("subject_token_type"),a=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),l=n.get("service_account_impersonation"),u=(0,TSe.originalOrCamelOptions)(l).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:s}),this.stsCredential=new Oit.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[u3],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=o,this.workforcePoolUserProject=a;let d=new RegExp(Uit);if(this.workforcePoolUserProject&&!this.audience.match(d))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=u,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Lit),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"};l3.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=kit.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof Pit.Readable;if(!n&&(o===401||o===403)&&!a&&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:Nit,audience:this.audience,requestedTokenType:Dit,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[u3]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,i,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};l3.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||[u3]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Mit.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Xo.BaseExternalAccountClient=d3});var ASe=B(NP=>{"use strict";Object.defineProperty(NP,"__esModule",{value:!0});NP.FileSubjectTokenSupplier=void 0;var p3=require("util"),h3=require("fs"),Bit=(0,p3.promisify)(h3.readFile??(()=>{})),qit=(0,p3.promisify)(h3.realpath??(()=>{})),$it=(0,p3.promisify)(h3.lstat??(()=>{})),f3=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 qit(e),!(await $it(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 Bit(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}};NP.FileSubjectTokenSupplier=f3});var CSe=B(DP=>{"use strict";Object.defineProperty(DP,"__esModule",{value:!0});DP.UrlSubjectTokenSupplier=void 0;var Git=no(),m3=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};Git.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}};DP.UrlSubjectTokenSupplier=m3});var RSe=B(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.CertificateSubjectTokenSupplier=ro.InvalidConfigurationError=ro.CertificateSourceUnavailableError=ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var LP=ec(),UP=require("fs"),FP=require("crypto"),Hit=require("https");ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var ll=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};ro.CertificateSourceUnavailableError=ll;var Jo=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};ro.InvalidConfigurationError=Jo;var g3=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Jo("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Jo("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Jo("Cannot create mTLS Agent with missing certificate or key");return new Hit.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,LP.isValidFile)(e))return e;throw new ll(`Provided certificate config path is invalid: ${e}`)}let n=process.env[ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,LP.isValidFile)(n))return n;throw new ll(`Path from environment variable "${ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,LP.getWellKnownCertificateConfigFileLocation)();if(await(0,LP.isValidFile)(r))return r;throw new ll(`Could not find certificate configuration file. Searched override path, the "${ro.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await UP.promises.readFile(e,"utf8")}catch{throw new ll(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),i=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!i||!s)throw new Jo(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:s}}catch(r){throw r instanceof Jo?r:new Jo(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,i;try{r=await UP.promises.readFile(e),new FP.X509Certificate(r)}catch(s){let o=s instanceof Error?s.message:String(s);throw new ll(`Failed to read certificate file at ${e}: ${o}`)}try{i=await UP.promises.readFile(n),(0,FP.createPrivateKey)(i)}catch(s){let o=s instanceof Error?s.message:String(s);throw new ll(`Failed to read private key file at ${n}: ${o}`)}return{cert:r,key:i}}async#r(e){let n=new FP.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await UP.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,l)=>{try{return new FP.X509Certificate(c)}catch(u){let d=u instanceof Error?u.message:String(u);throw new Jo(`Failed to parse certificate at index ${l} in trust chain file ${this.trustChainPath}: ${d}`)}}),o=s.findIndex(c=>n.raw.equals(c.raw)),a;if(o===-1)a=[n,...s];else if(o===0)a=s;else throw new Jo(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);return JSON.stringify(a.map(c=>c.raw.toString("base64")))}catch(r){if(r instanceof Jo)throw r;let i=r instanceof Error?r.message:String(r);throw new ll(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};ro.CertificateSubjectTokenSupplier=g3});var v3=B(BP=>{"use strict";Object.defineProperty(BP,"__esModule",{value:!0});BP.IdentityPoolClient=void 0;var jit=Df(),y3=ec(),Wit=ASe(),Vit=CSe(),ISe=RSe(),zit=MP(),kSe=di(),_3=class t extends jit.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,y3.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 s=(0,y3.originalOrCamelOptions)(r),o=(0,y3.originalOrCamelOptions)(s.get("format")),a=o.get("type")||"text",c=o.get("subject_token_field_name");if(a!=="json"&&a!=="text")throw new Error(`Invalid credential_source format "${a}"`);if(a==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let l=s.get("file"),u=s.get("url"),d=s.get("certificate"),f=s.get("headers");if(l&&u||u&&d||l&&d)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(l)this.credentialSourceType="file",this.subjectTokenSupplier=new Wit.FileSubjectTokenSupplier({filePath:l,formatType:a,subjectTokenFieldName:c});else if(u)this.credentialSourceType="url",this.subjectTokenSupplier=new Vit.UrlSubjectTokenSupplier({url:u,formatType:a,subjectTokenFieldName:c,headers:f,additionalGaxiosOptions:t.RETRY_CONFIG});else if(d){this.credentialSourceType="certificate";let m=new ISe.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:d.use_default_certificate_config,certificateConfigLocation:d.certificate_config_location,trustChainPath:d.trust_chain_path});this.subjectTokenSupplier=m}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof ISe.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new zit.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new kSe.Gaxios({agent:n})}),this.transporter=new kSe.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};BP.IdentityPoolClient=_3});var w3=B($P=>{"use strict";Object.defineProperty($P,"__esModule",{value:!0});$P.AwsRequestSigner=void 0;var qP=di(),OSe=RS(),PSe="AWS4-HMAC-SHA256",Kit="aws4_request",E3=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,OSe.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",s=e.body||n,o=e.headers,a=await this.getCredentials(),c=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let l=await Xit({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:i,region:this.region,securityCredentials:a,requestPayload:s,additionalAmzHeaders:o}),u=qP.Gaxios.mergeHeaders(l.amzDate?{"x-amz-date":l.amzDate}:{},{authorization:l.authorizationHeader,host:c.host},o||{});a.token&&qP.Gaxios.mergeHeaders(u,{"x-amz-security-token":a.token});let d={url:r,method:i,headers:u};return s!==void 0&&(d.body=s),d}};$P.AwsRequestSigner=E3;async function OS(t,e,n){return await t.signWithHmacSha256(e,n)}async function Yit(t,e,n,r,i){let s=await OS(t,`AWS4${e}`,n),o=await OS(t,s,r),a=await OS(t,o,i);return await OS(t,a,"aws4_request")}async function Xit(t){let e=qP.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],i=new Date,s=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),o=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let a=qP.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),c="",l=[...a.keys()].sort();l.forEach(T=>{c+=`${T}:${a.get(T)}
503
503
  `});let u=l.join(";"),d=await t.crypto.sha256DigestHex(n),f=`${t.method.toUpperCase()}
504
504
  ${t.canonicalUri}
505
505
  ${t.canonicalQuerystring}
@@ -508,30 +508,30 @@ ${u}
508
508
  ${d}`,m=`${o}/${t.region}/${r}/${Kit}`,g=`${PSe}
509
509
  ${s}
510
510
  ${m}
511
- `+await t.crypto.sha256DigestHex(f),y=await Yit(t.crypto,t.securityCredentials.secretAccessKey,o,t.region,r),w=await OS(t.crypto,y,g),S=`${PSe} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${u}, Signature=${(0,OSe.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:S,canonicalQuerystring:t.canonicalQuerystring}}});var MSe=B(HP=>{"use strict";Object.defineProperty(HP,"__esModule",{value:!0});HP.DefaultAwsSecurityCredentialsSupplier=void 0;var GP=no(),SW=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};GP.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 GP.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 GP.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 GP.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}};HP.DefaultAwsSecurityCredentialsSupplier=SW});var bW=B(jP=>{"use strict";Object.defineProperty(jP,"__esModule",{value:!0});jP.AwsClient=void 0;var Jit=wW(),Qit=Df(),Zit=MSe(),NSe=ec(),est=di(),xW=class t extends Qit.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,NSe.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 s=(0,NSe.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let o=s.get("region_url"),a=s.get("url"),c=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Zit.DefaultAwsSecurityCredentialsSupplier({regionUrl:o,securityCredentialsUrl:a,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Jit.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 est.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,s)=>n.push({key:s,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};jP.AwsClient=xW});var IW=B(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.InvalidSubjectTokenError=Ar.InvalidMessageFieldError=Ar.InvalidCodeFieldError=Ar.InvalidTokenTypeFieldError=Ar.InvalidExpirationTimeFieldError=Ar.InvalidSuccessFieldError=Ar.InvalidVersionFieldError=Ar.ExecutableResponseError=Ar.ExecutableResponse=void 0;var WP="urn:ietf:params:oauth:token-type:saml2",TW="urn:ietf:params:oauth:token-type:id_token",AW="urn:ietf:params:oauth:token-type:jwt",CW=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new VP("Executable response must contain a 'version' field.");if(e.success===void 0)throw new zP("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!==WP&&this.tokenType!==TW&&this.tokenType!==AW)throw new KP(`Executable response must contain a 'token_type' field when successful and it must be one of ${TW}, ${AW}, or ${WP}.`);if(this.tokenType===WP){if(!e.saml_response)throw new MS(`Executable response must contain a 'saml_response' field when token_type=${WP}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new MS(`Executable response must contain a 'id_token' field when token_type=${TW} or ${AW}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new YP("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new XP("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)}};Ar.ExecutableResponse=CW;var ul=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Ar.ExecutableResponseError=ul;var VP=class extends ul{};Ar.InvalidVersionFieldError=VP;var zP=class extends ul{};Ar.InvalidSuccessFieldError=zP;var RW=class extends ul{};Ar.InvalidExpirationTimeFieldError=RW;var KP=class extends ul{};Ar.InvalidTokenTypeFieldError=KP;var YP=class extends ul{};Ar.InvalidCodeFieldError=YP;var XP=class extends ul{};Ar.InvalidMessageFieldError=XP;var MS=class extends ul{};Ar.InvalidSubjectTokenError=MS});var OW=B(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});J_.PluggableAuthHandler=J_.ExecutableError=void 0;var um=IW(),tst=require("child_process"),kW=require("fs"),JP=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)}};J_.ExecutableError=JP;var PW=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=tst.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";i.stdout.on("data",a=>{s+=a}),i.stderr.on("data",a=>{s+=a});let o=setTimeout(()=>(i.removeAllListeners(),i.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",a=>{if(clearTimeout(o),a===0)try{let c=JSON.parse(s),l=new um.ExecutableResponse(c);return n(l)}catch(c){return c instanceof um.ExecutableResponseError?r(c):r(new um.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new JP(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await kW.promises.realpath(this.outputFile)}catch{return}if(!(await kW.promises.lstat(e)).isFile())return;let n=await kW.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new um.ExecutableResponse(r).isValid()?new um.ExecutableResponse(r):void 0}catch(r){throw r instanceof um.ExecutableResponseError?r:new um.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}};J_.PluggableAuthHandler=PW});var NW=B(Q_=>{"use strict";Object.defineProperty(Q_,"__esModule",{value:!0});Q_.PluggableAuthClient=Q_.ExecutableError=void 0;var nst=Df(),rst=IW(),DSe=OW(),ist=OW();Object.defineProperty(Q_,"ExecutableError",{enumerable:!0,get:function(){return ist.ExecutableError}});var sst=30*1e3,LSe=5*1e3,USe=120*1e3,ost="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",FSe=1,MW=class extends nst.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=sst;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<LSe||this.timeoutMillis>USe)throw new Error(`Timeout must be between ${LSe} and ${USe} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new DSe.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[ost]!=="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>FSe)throw new Error(`Version of executable is not currently supported, maximum supported version is ${FSe}.`);if(!e.success)throw new DSe.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new rst.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}};Q_.PluggableAuthClient=MW});var LW=B(QP=>{"use strict";Object.defineProperty(QP,"__esModule",{value:!0});QP.ExternalAccountClient=void 0;var ast=Df(),cst=vW(),lst=bW(),ust=NW(),DW=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===ast.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new lst.AwsClient(e):e.credential_source?.executable?new ust.PluggableAuthClient(e):new cst.IdentityPoolClient(e):null}};QP.ExternalAccountClient=DW});var BW=B(Z_=>{"use strict";Object.defineProperty(Z_,"__esModule",{value:!0});Z_.ExternalAccountAuthorizedUserClient=Z_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var qSe=no(),BSe=aW(),$Se=di(),dst=require("stream"),fst=Df();Z_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var pst="https://sts.{universeDomain}/v1/oauthtoken",UW=class t extends BSe.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"};qSe.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let i=await this.transporter.request(r),s=i.data;return s.res=i,s}catch(i){throw i instanceof $Se.GaxiosError&&i.response?(0,BSe.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},FW=class extends qSe.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 UW({tokenRefreshEndpoint:e.token_url??pst.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=fst.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=$Se.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof dst.Readable;if(!n&&(o===401||o===403)&&!a&&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}};Z_.ExternalAccountAuthorizedUserClient=FW});var $W=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});Lf.GdchClient=Lf.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var hst=require("crypto"),mst=require("fs"),gst=require("https"),yst=Mf(),_st=3600;Lf.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var qW=class t extends yst.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||_st,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!==Lf.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Lf.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),s=i.data;if(!s.access_token)throw new Error("Token response did not contain an access_token.");if(!s.expires_in)throw new Error("Token response did not contain an expires_in field.");let o={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1e3};return this.emit("tokens",o),{res:i,tokens:o}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data=="string"){let s=JSON.parse(i.config.data);s.subject_token&&(s.subject_token="***REDACTED***",i.config.data=JSON.stringify(s))}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},s=this.base64UrlEncode(JSON.stringify(e)),o=this.base64UrlEncode(JSON.stringify(i)),a=`${s}.${o}`,c=hst.sign("sha256",Buffer.from(a),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),l=this.base64UrlEncode(c);return`${a}.${l}`}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 mst.promises.readFile(r);return new gst.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")}};Lf.GdchClient=qW});var WSe=B(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.GoogleAuth=nc.GoogleAuthExceptionMessages=void 0;var vst=require("child_process"),NS=require("fs"),Est=di(),DS=CS(),wst=require("os"),ZP=require("path"),Sst=RS(),xst=L4(),bst=F4(),Tst=B4(),ev=tW(),GSe=rW(),tv=sW(),Ast=LW(),LS=Df(),GW=no(),HSe=BW(),HW=$W(),jSe=ec();nc.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.
511
+ `+await t.crypto.sha256DigestHex(f),y=await Yit(t.crypto,t.securityCredentials.secretAccessKey,o,t.region,r),w=await OS(t.crypto,y,g),S=`${PSe} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${u}, Signature=${(0,OSe.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:S,canonicalQuerystring:t.canonicalQuerystring}}});var MSe=B(HP=>{"use strict";Object.defineProperty(HP,"__esModule",{value:!0});HP.DefaultAwsSecurityCredentialsSupplier=void 0;var GP=no(),S3=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};GP.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 GP.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 GP.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 GP.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}};HP.DefaultAwsSecurityCredentialsSupplier=S3});var b3=B(jP=>{"use strict";Object.defineProperty(jP,"__esModule",{value:!0});jP.AwsClient=void 0;var Jit=w3(),Qit=Df(),Zit=MSe(),NSe=ec(),est=di(),x3=class t extends Qit.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,NSe.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 s=(0,NSe.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let o=s.get("region_url"),a=s.get("url"),c=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Zit.DefaultAwsSecurityCredentialsSupplier({regionUrl:o,securityCredentialsUrl:a,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Jit.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 est.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,s)=>n.push({key:s,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};jP.AwsClient=x3});var I3=B(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.InvalidSubjectTokenError=Ar.InvalidMessageFieldError=Ar.InvalidCodeFieldError=Ar.InvalidTokenTypeFieldError=Ar.InvalidExpirationTimeFieldError=Ar.InvalidSuccessFieldError=Ar.InvalidVersionFieldError=Ar.ExecutableResponseError=Ar.ExecutableResponse=void 0;var WP="urn:ietf:params:oauth:token-type:saml2",T3="urn:ietf:params:oauth:token-type:id_token",A3="urn:ietf:params:oauth:token-type:jwt",C3=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new VP("Executable response must contain a 'version' field.");if(e.success===void 0)throw new zP("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!==WP&&this.tokenType!==T3&&this.tokenType!==A3)throw new KP(`Executable response must contain a 'token_type' field when successful and it must be one of ${T3}, ${A3}, or ${WP}.`);if(this.tokenType===WP){if(!e.saml_response)throw new MS(`Executable response must contain a 'saml_response' field when token_type=${WP}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new MS(`Executable response must contain a 'id_token' field when token_type=${T3} or ${A3}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new YP("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new XP("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)}};Ar.ExecutableResponse=C3;var ul=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Ar.ExecutableResponseError=ul;var VP=class extends ul{};Ar.InvalidVersionFieldError=VP;var zP=class extends ul{};Ar.InvalidSuccessFieldError=zP;var R3=class extends ul{};Ar.InvalidExpirationTimeFieldError=R3;var KP=class extends ul{};Ar.InvalidTokenTypeFieldError=KP;var YP=class extends ul{};Ar.InvalidCodeFieldError=YP;var XP=class extends ul{};Ar.InvalidMessageFieldError=XP;var MS=class extends ul{};Ar.InvalidSubjectTokenError=MS});var O3=B(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});J_.PluggableAuthHandler=J_.ExecutableError=void 0;var um=I3(),tst=require("child_process"),k3=require("fs"),JP=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)}};J_.ExecutableError=JP;var P3=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=tst.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";i.stdout.on("data",a=>{s+=a}),i.stderr.on("data",a=>{s+=a});let o=setTimeout(()=>(i.removeAllListeners(),i.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",a=>{if(clearTimeout(o),a===0)try{let c=JSON.parse(s),l=new um.ExecutableResponse(c);return n(l)}catch(c){return c instanceof um.ExecutableResponseError?r(c):r(new um.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new JP(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await k3.promises.realpath(this.outputFile)}catch{return}if(!(await k3.promises.lstat(e)).isFile())return;let n=await k3.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new um.ExecutableResponse(r).isValid()?new um.ExecutableResponse(r):void 0}catch(r){throw r instanceof um.ExecutableResponseError?r:new um.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}};J_.PluggableAuthHandler=P3});var N3=B(Q_=>{"use strict";Object.defineProperty(Q_,"__esModule",{value:!0});Q_.PluggableAuthClient=Q_.ExecutableError=void 0;var nst=Df(),rst=I3(),DSe=O3(),ist=O3();Object.defineProperty(Q_,"ExecutableError",{enumerable:!0,get:function(){return ist.ExecutableError}});var sst=30*1e3,LSe=5*1e3,USe=120*1e3,ost="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",FSe=1,M3=class extends nst.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=sst;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<LSe||this.timeoutMillis>USe)throw new Error(`Timeout must be between ${LSe} and ${USe} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new DSe.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[ost]!=="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>FSe)throw new Error(`Version of executable is not currently supported, maximum supported version is ${FSe}.`);if(!e.success)throw new DSe.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new rst.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}};Q_.PluggableAuthClient=M3});var L3=B(QP=>{"use strict";Object.defineProperty(QP,"__esModule",{value:!0});QP.ExternalAccountClient=void 0;var ast=Df(),cst=v3(),lst=b3(),ust=N3(),D3=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===ast.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new lst.AwsClient(e):e.credential_source?.executable?new ust.PluggableAuthClient(e):new cst.IdentityPoolClient(e):null}};QP.ExternalAccountClient=D3});var B3=B(Z_=>{"use strict";Object.defineProperty(Z_,"__esModule",{value:!0});Z_.ExternalAccountAuthorizedUserClient=Z_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var qSe=no(),BSe=a3(),$Se=di(),dst=require("stream"),fst=Df();Z_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var pst="https://sts.{universeDomain}/v1/oauthtoken",U3=class t extends BSe.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"};qSe.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let i=await this.transporter.request(r),s=i.data;return s.res=i,s}catch(i){throw i instanceof $Se.GaxiosError&&i.response?(0,BSe.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},F3=class extends qSe.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 U3({tokenRefreshEndpoint:e.token_url??pst.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=fst.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=$Se.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof dst.Readable;if(!n&&(o===401||o===403)&&!a&&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}};Z_.ExternalAccountAuthorizedUserClient=F3});var $3=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});Lf.GdchClient=Lf.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var hst=require("crypto"),mst=require("fs"),gst=require("https"),yst=Mf(),_st=3600;Lf.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var q3=class t extends yst.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||_st,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!==Lf.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Lf.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),s=i.data;if(!s.access_token)throw new Error("Token response did not contain an access_token.");if(!s.expires_in)throw new Error("Token response did not contain an expires_in field.");let o={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1e3};return this.emit("tokens",o),{res:i,tokens:o}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data=="string"){let s=JSON.parse(i.config.data);s.subject_token&&(s.subject_token="***REDACTED***",i.config.data=JSON.stringify(s))}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},s=this.base64UrlEncode(JSON.stringify(e)),o=this.base64UrlEncode(JSON.stringify(i)),a=`${s}.${o}`,c=hst.sign("sha256",Buffer.from(a),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),l=this.base64UrlEncode(c);return`${a}.${l}`}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 mst.promises.readFile(r);return new gst.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")}};Lf.GdchClient=q3});var WSe=B(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.GoogleAuth=nc.GoogleAuthExceptionMessages=void 0;var vst=require("child_process"),NS=require("fs"),Est=di(),DS=CS(),wst=require("os"),ZP=require("path"),Sst=RS(),xst=L4(),bst=F4(),Tst=B4(),ev=t3(),GSe=r3(),tv=s3(),Ast=L3(),LS=Df(),G3=no(),HSe=B3(),H3=$3(),jSe=ec();nc.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.
512
512
  To learn more about authentication and Google APIs, visit:
513
513
  https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
514
514
  To learn more about authentication and Google APIs, visit:
515
515
  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.
516
516
  To learn more about Universe Domain retrieval, visit:
517
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var jW=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(nc.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===nc.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(nc.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 DS.universe("universe-domain"),e||=GW.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=GW.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,jSe.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=GW.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 ev.JWT?n.scopes=this.scopes:n instanceof LS.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof ev.JWT?n.scopes=this.scopes:n instanceof LS.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new xst.Compute(e));throw new Error(nc.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=DS.getGCPResidency()||await DS.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=ZP.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=ZP.join(s,".config","gcloud"))}if(!n)return null;let r=ZP.join(n,"application_default_credentials.json");return NS.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=NS.realpathSync(e),!NS.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=NS.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!==tv.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${tv.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 tv.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let r,i=(0,jSe.originalOrCamelOptions)(n).get("universe_domain");return e.type===GSe.USER_REFRESH_ACCOUNT_TYPE?(r=new GSe.UserRefreshClient(n),r.fromJSON(e)):e.type===tv.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===LS.EXTERNAL_ACCOUNT_TYPE?(r=Ast.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===HSe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new HSe.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===HW.GDCH_SERVICE_ACCOUNT_TYPE?(r=new HW.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new ev.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(s=>r(null,s),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 s=[];e.setEncoding("utf8").on("error",i).on("data",o=>s.push(o)).on("end",()=>{try{try{let o=JSON.parse(s.join("")),a=this._cacheClientFromJSON(o,n);return r(a)}catch(o){if(!this.keyFilename)throw o;let a=new ev.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),r(a)}}catch(o){return i(o)}})})}fromAPIKey(e,n={}){return new ev.JWT({...n,apiKey:e})}_isWindows(){let e=wst.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,vst.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!==LS.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await DS.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 tv.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof LS.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([DS.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(nc.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 HW.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),o=e.createWithGdchAudience(s);return this.cachedCredential=o,o}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=ZP.resolve(this.keyFilename),n=NS.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 bst.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=Est.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,Tst.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 tv.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,Sst.createCrypto)();if(r instanceof ev.JWT&&r.key)return await s.sign(r.key,e);let o=await this.getCredentials();if(!o.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,o.client_email,e,n)}async signBlob(e,n,r,i){let s=new URL(i+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};nc.GoogleAuth=jW});var VSe=B(eO=>{"use strict";Object.defineProperty(eO,"__esModule",{value:!0});eO.IAMAuth=void 0;var WW=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}}};eO.IAMAuth=WW});var zSe=B(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});dl.DownscopedClient=dl.EXPIRATION_TIME_OFFSET=dl.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Cst=di(),Rst=require("stream"),VW=no(),Ist=MP(),kst="urn:ietf:params:oauth:grant-type:token-exchange",Pst="urn:ietf:params:oauth:token-type:access_token",Ost="urn:ietf:params:oauth:token-type:access_token";dl.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;dl.EXPIRATION_TIME_OFFSET=300*1e3;var zW=class extends VW.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof VW.AuthClient?{}:e),e instanceof VW.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>dl.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${dl.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 Ist.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=Cst.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof Rst.Readable;if(!n&&(o===401||o===403)&&!a&&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:kst,requestedTokenType:Pst,subjectToken:e,subjectTokenType:Ost},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:i;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,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}};dl.DownscopedClient=zW});var KSe=B(tO=>{"use strict";Object.defineProperty(tO,"__esModule",{value:!0});tO.PassThroughClient=void 0;var Mst=no(),KW=class extends Mst.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};tO.PassThroughClient=KW});var exe=B(Ie=>{"use strict";var Nst=Ie&&Ie.__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]})),Dst=Ie&&Ie.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Nst(e,t,n)};Object.defineProperty(Ie,"__esModule",{value:!0});Ie.GoogleAuth=Ie.auth=Ie.GDCH_SERVICE_ACCOUNT_TYPE=Ie.GdchClient=Ie.PassThroughClient=Ie.ExternalAccountAuthorizedUserClient=Ie.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Ie.ExecutableError=Ie.PluggableAuthClient=Ie.DownscopedClient=Ie.BaseExternalAccountClient=Ie.ExternalAccountClient=Ie.IdentityPoolClient=Ie.AwsRequestSigner=Ie.AwsClient=Ie.UserRefreshClient=Ie.LoginTicket=Ie.ClientAuthentication=Ie.OAuth2Client=Ie.CodeChallengeMethod=Ie.Impersonated=Ie.JWT=Ie.JWTAccess=Ie.IdTokenClient=Ie.IAMAuth=Ie.GCPEnv=Ie.Compute=Ie.DEFAULT_UNIVERSE=Ie.AuthClient=Ie.gaxios=Ie.gcpMetadata=void 0;var YSe=WSe();Object.defineProperty(Ie,"GoogleAuth",{enumerable:!0,get:function(){return YSe.GoogleAuth}});Ie.gcpMetadata=CS();Ie.gaxios=di();var XSe=no();Object.defineProperty(Ie,"AuthClient",{enumerable:!0,get:function(){return XSe.AuthClient}});Object.defineProperty(Ie,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return XSe.DEFAULT_UNIVERSE}});var Lst=L4();Object.defineProperty(Ie,"Compute",{enumerable:!0,get:function(){return Lst.Compute}});var Ust=B4();Object.defineProperty(Ie,"GCPEnv",{enumerable:!0,get:function(){return Ust.GCPEnv}});var Fst=VSe();Object.defineProperty(Ie,"IAMAuth",{enumerable:!0,get:function(){return Fst.IAMAuth}});var Bst=F4();Object.defineProperty(Ie,"IdTokenClient",{enumerable:!0,get:function(){return Bst.IdTokenClient}});var qst=Z4();Object.defineProperty(Ie,"JWTAccess",{enumerable:!0,get:function(){return qst.JWTAccess}});var $st=tW();Object.defineProperty(Ie,"JWT",{enumerable:!0,get:function(){return $st.JWT}});var Gst=sW();Object.defineProperty(Ie,"Impersonated",{enumerable:!0,get:function(){return Gst.Impersonated}});var YW=Mf();Object.defineProperty(Ie,"CodeChallengeMethod",{enumerable:!0,get:function(){return YW.CodeChallengeMethod}});Object.defineProperty(Ie,"OAuth2Client",{enumerable:!0,get:function(){return YW.OAuth2Client}});Object.defineProperty(Ie,"ClientAuthentication",{enumerable:!0,get:function(){return YW.ClientAuthentication}});var Hst=O4();Object.defineProperty(Ie,"LoginTicket",{enumerable:!0,get:function(){return Hst.LoginTicket}});var jst=rW();Object.defineProperty(Ie,"UserRefreshClient",{enumerable:!0,get:function(){return jst.UserRefreshClient}});var Wst=bW();Object.defineProperty(Ie,"AwsClient",{enumerable:!0,get:function(){return Wst.AwsClient}});var Vst=wW();Object.defineProperty(Ie,"AwsRequestSigner",{enumerable:!0,get:function(){return Vst.AwsRequestSigner}});var zst=vW();Object.defineProperty(Ie,"IdentityPoolClient",{enumerable:!0,get:function(){return zst.IdentityPoolClient}});var Kst=LW();Object.defineProperty(Ie,"ExternalAccountClient",{enumerable:!0,get:function(){return Kst.ExternalAccountClient}});var Yst=Df();Object.defineProperty(Ie,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Yst.BaseExternalAccountClient}});var Xst=zSe();Object.defineProperty(Ie,"DownscopedClient",{enumerable:!0,get:function(){return Xst.DownscopedClient}});var JSe=NW();Object.defineProperty(Ie,"PluggableAuthClient",{enumerable:!0,get:function(){return JSe.PluggableAuthClient}});Object.defineProperty(Ie,"ExecutableError",{enumerable:!0,get:function(){return JSe.ExecutableError}});var QSe=BW();Object.defineProperty(Ie,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return QSe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Ie,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return QSe.ExternalAccountAuthorizedUserClient}});var Jst=KSe();Object.defineProperty(Ie,"PassThroughClient",{enumerable:!0,get:function(){return Jst.PassThroughClient}});var ZSe=$W();Object.defineProperty(Ie,"GdchClient",{enumerable:!0,get:function(){return ZSe.GdchClient}});Object.defineProperty(Ie,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return ZSe.GDCH_SERVICE_ACCOUNT_TYPE}});Dst(J4(),Ie);var Qst=new YSe.GoogleAuth;Ie.auth=Qst});var qu=B((KMt,rxe)=>{"use strict";var txe=["nodebuffer","arraybuffer","fragments"],nxe=typeof Blob<"u";nxe&&txe.push("blob");rxe.exports={BINARY_TYPES:txe,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nxe,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var US=B((YMt,nO)=>{"use strict";var{EMPTY_BUFFER:Zst}=qu(),XW=Buffer[Symbol.species];function eot(t,e){if(t.length===0)return Zst;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let s=t[i];n.set(s,r),r+=s.length}return r<e?new XW(n.buffer,n.byteOffset,r):n}function ixe(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function sxe(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function tot(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function JW(t){if(JW.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new XW(t):ArrayBuffer.isView(t)?e=new XW(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),JW.readOnly=!1),e}nO.exports={concat:eot,mask:ixe,toArrayBuffer:tot,toBuffer:JW,unmask:sxe};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");nO.exports.mask=function(e,n,r,i,s){s<48?ixe(e,n,r,i,s):t.mask(e,n,r,i,s)},nO.exports.unmask=function(e,n){e.length<32?sxe(e,n):t.unmask(e,n)}}catch{}});var cxe=B((XMt,axe)=>{"use strict";var oxe=Symbol("kDone"),QW=Symbol("kRun"),ZW=class{constructor(e){this[oxe]=()=>{this.pending--,this[QW]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[QW]()}[QW](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[oxe])}}};axe.exports=ZW});var iv=B((JMt,fxe)=>{"use strict";var FS=require("zlib"),lxe=US(),not=cxe(),{kStatusCode:uxe}=qu(),rot=Buffer[Symbol.species],iot=Buffer.from([0,0,255,255]),iO=Symbol("permessage-deflate"),$u=Symbol("total-length"),nv=Symbol("callback"),Uf=Symbol("buffers"),rv=Symbol("error"),rO,e3=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,!rO){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;rO=new not(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[nv];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"&&!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 s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}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){rO.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){rO.add(i=>{this._compress(e,n,(s,o)=>{i(),r(s,o)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?FS.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=FS.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[iO]=this,this._inflate[$u]=0,this._inflate[Uf]=[],this._inflate.on("error",oot),this._inflate.on("data",dxe)}this._inflate[nv]=r,this._inflate.write(e),n&&this._inflate.write(iot),this._inflate.flush(()=>{let s=this._inflate[rv];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=lxe.concat(this._inflate[Uf],this._inflate[$u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$u]=0,this._inflate[Uf]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?FS.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=FS.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[$u]=0,this._deflate[Uf]=[],this._deflate.on("data",sot)}this._deflate[nv]=r,this._deflate.write(e),this._deflate.flush(FS.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=lxe.concat(this._deflate[Uf],this._deflate[$u]);n&&(s=new rot(s.buffer,s.byteOffset,s.length-4)),this._deflate[nv]=null,this._deflate[$u]=0,this._deflate[Uf]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};fxe.exports=e3;function sot(t){this[Uf].push(t),this[$u]+=t.length}function dxe(t){if(this[$u]+=t.length,this[iO]._maxPayload<1||this[$u]<=this[iO]._maxPayload){this[Uf].push(t);return}this[rv]=new RangeError("Max payload size exceeded"),this[rv].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rv][uxe]=1009,this.removeListener("data",dxe),this.reset()}function oot(t){if(this[iO]._inflate=null,this[rv]){this[nv](this[rv]);return}t[uxe]=1007,this[nv](t)}});var sv=B((QMt,sO)=>{"use strict";var{isUtf8:pxe}=require("buffer"),{hasBlob:aot}=qu(),cot=[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 lot(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function t3(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 uot(t){return aot&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}sO.exports={isBlob:uot,isValidStatusCode:lot,isValidUTF8:t3,tokenChars:cot};if(pxe)sO.exports.isValidUTF8=function(t){return t.length<24?t3(t):pxe(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");sO.exports.isValidUTF8=function(e){return e.length<32?t3(e):t(e)}}catch{}});var o3=B((ZMt,Exe)=>{"use strict";var{Writable:dot}=require("stream"),hxe=iv(),{BINARY_TYPES:fot,EMPTY_BUFFER:mxe,kStatusCode:pot,kWebSocket:hot}=qu(),{concat:n3,toArrayBuffer:mot,unmask:got}=US(),{isValidStatusCode:yot,isValidUTF8:gxe}=sv(),oO=Buffer[Symbol.species],Qo=0,yxe=1,_xe=2,vxe=3,r3=4,i3=5,aO=6,s3=class extends dot{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||fot[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[hot]=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._fragments=[],this._errored=!1,this._loop=!1,this._state=Qo}_write(e,n,r){if(this._opcode===8&&this._state==Qo)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 oO(r.buffer,r.byteOffset+e,r.length-e),new oO(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 oO(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 Qo:this.getInfo(e);break;case yxe:this.getPayloadLength16(e);break;case _xe:this.getPayloadLength64(e);break;case vxe:this.getMask();break;case r3:this.getData(e);break;case i3:case aO: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[hxe.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=yxe:this._payloadLength===127?this._state=_xe: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=vxe:this._state=r3}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=r3}getData(e){let n=mxe;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&&got(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=i3,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[hxe.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return n(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(o);return}this._fragments.push(s)}this.dataMessage(n),this._state===Qo&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qo;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=n3(r,n):this._binaryType==="arraybuffer"?i=mot(n3(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit("message",i,!0),this._state=Qo,this.startLoop(e)}))}else{let i=n3(r,n);if(!this._skipUTF8Validation&&!gxe(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===i3||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit("message",i,!1),this._state=Qo,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,mxe),this.end();else{let r=e.readUInt16BE(0);if(!yot(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new oO(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gxe(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=Qo;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qo,this.startLoop(n)}))}createError(e,n,r,i,s){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=s,o[pot]=i,o}};Exe.exports=s3});var l3=B((tNt,xxe)=>{"use strict";var{Duplex:eNt}=require("stream"),{randomFillSync:_ot}=require("crypto"),{types:{isUint8Array:vot}}=require("util"),wxe=iv(),{EMPTY_BUFFER:Eot,kWebSocket:wot,NOOP:Sot}=qu(),{isBlob:ov,isValidStatusCode:xot}=sv(),{mask:Sxe,toBuffer:dm}=US(),Zo=Symbol("kByteLength"),bot=Buffer.alloc(4),cO=8*1024,fm,av=cO,rc=0,Tot=1,Aot=2,a3=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=rc,this.onerror=Sot,this[wot]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||bot,n.generateMask?n.generateMask(r):(av===cO&&(fm===void 0&&(fm=Buffer.alloc(cO)),_ot(fm,0,cO),av=0),r[0]=fm[av++],r[1]=fm[av++],r[2]=fm[av++],r[3]=fm[av++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[Zo]!==void 0?a=n[Zo]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?a+s:s);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],o?[l,e]:i?(Sxe(e,r,l,s,a),[l]):(Sxe(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,i){let s;if(e===void 0)s=Eot;else{if(typeof e!="number"||!xot(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof n=="string")s.write(n,2);else if(vot(n))s.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Zo]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==rc?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ov(e)?(i=e.size,s=!1):(e=dm(e),i=e.length,s=dm.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Zo]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==rc?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ov(e)?(i=e.size,s=!1):(e=dm(e),i=e.length,s=dm.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Zo]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==rc?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[wxe.extensionName],s=n.binary?2:1,o=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ov(e)?(a=e.size,c=!1):(e=dm(e),a=e.length,c=dm.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),n.fin&&(this._firstFragment=!0);let l={[Zo]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==rc?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[Zo],this._state=Aot,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(c3,this,a,i);return}this._bufferedBytes-=r[Zo];let o=dm(s);n?this.dispatch(o,n,r,i):(this._state=rc,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Cot,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[wxe.extensionName];this._bufferedBytes+=r[Zo],this._state=Tot,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");c3(this,c,i);return}this._bufferedBytes-=r[Zo],this._state=rc,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===rc&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Zo],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Zo],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)}};xxe.exports=a3;function c3(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],s=i[i.length-1];typeof s=="function"&&s(e)}}function Cot(t,e,n){c3(t,e,n),t.onerror(e)}});var Oxe=B((nNt,Pxe)=>{"use strict";var{kForOnEventAttribute:BS,kListener:u3}=qu(),bxe=Symbol("kCode"),Txe=Symbol("kData"),Axe=Symbol("kError"),Cxe=Symbol("kMessage"),Rxe=Symbol("kReason"),cv=Symbol("kTarget"),Ixe=Symbol("kType"),kxe=Symbol("kWasClean"),Gu=class{constructor(e){this[cv]=null,this[Ixe]=e}get target(){return this[cv]}get type(){return this[Ixe]}};Object.defineProperty(Gu.prototype,"target",{enumerable:!0});Object.defineProperty(Gu.prototype,"type",{enumerable:!0});var pm=class extends Gu{constructor(e,n={}){super(e),this[bxe]=n.code===void 0?0:n.code,this[Rxe]=n.reason===void 0?"":n.reason,this[kxe]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[bxe]}get reason(){return this[Rxe]}get wasClean(){return this[kxe]}};Object.defineProperty(pm.prototype,"code",{enumerable:!0});Object.defineProperty(pm.prototype,"reason",{enumerable:!0});Object.defineProperty(pm.prototype,"wasClean",{enumerable:!0});var lv=class extends Gu{constructor(e,n={}){super(e),this[Axe]=n.error===void 0?null:n.error,this[Cxe]=n.message===void 0?"":n.message}get error(){return this[Axe]}get message(){return this[Cxe]}};Object.defineProperty(lv.prototype,"error",{enumerable:!0});Object.defineProperty(lv.prototype,"message",{enumerable:!0});var qS=class extends Gu{constructor(e,n={}){super(e),this[Txe]=n.data===void 0?null:n.data}get data(){return this[Txe]}};Object.defineProperty(qS.prototype,"data",{enumerable:!0});var Rot={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[BS]&&i[u3]===e&&!i[BS])return;let r;if(t==="message")r=function(s,o){let a=new qS("message",{data:o?s:s.toString()});a[cv]=this,lO(e,this,a)};else if(t==="close")r=function(s,o){let a=new pm("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[cv]=this,lO(e,this,a)};else if(t==="error")r=function(s){let o=new lv("error",{error:s,message:s.message});o[cv]=this,lO(e,this,o)};else if(t==="open")r=function(){let s=new Gu("open");s[cv]=this,lO(e,this,s)};else return;r[BS]=!!n[BS],r[u3]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[u3]===e&&!n[BS]){this.removeListener(t,n);break}}};Pxe.exports={CloseEvent:pm,ErrorEvent:lv,Event:Gu,EventTarget:Rot,MessageEvent:qS};function lO(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var uO=B((rNt,Mxe)=>{"use strict";var{tokenChars:$S}=sv();function fl(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Iot(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,s=!1,o,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),o===void 0)if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);l===44?(fl(e,m,n),n=Object.create(null)):o=m,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),fl(n,t.slice(c,u),!0),l===44&&(fl(e,o,n),n=Object.create(null),o=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if($S[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(s)if($S[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)s=!1,u=d;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)s=!0;else if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);r&&(m=m.replace(/\\/g,""),r=!1),fl(n,a,m),l===44&&(fl(e,o,n),n=Object.create(null),o=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(c,u);return o===void 0?fl(e,f,n):(a===void 0?fl(n,f,!0):r?fl(n,a,f.replace(/\\/g,"")):fl(n,a,f),fl(e,o,n)),e}function kot(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 s=r[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Mxe.exports={format:kot,parse:Iot}});var hO=B((oNt,Wxe)=>{"use strict";var Pot=require("events"),Oot=require("https"),Mot=require("http"),Lxe=require("net"),Not=require("tls"),{randomBytes:Dot,createHash:Lot}=require("crypto"),{Duplex:iNt,Readable:sNt}=require("stream"),{URL:d3}=require("url"),Ff=iv(),Uot=o3(),Fot=l3(),{isBlob:Bot}=sv(),{BINARY_TYPES:Nxe,CLOSE_TIMEOUT:qot,EMPTY_BUFFER:dO,GUID:$ot,kForOnEventAttribute:f3,kListener:Got,kStatusCode:Hot,kWebSocket:Jr,NOOP:Uxe}=qu(),{EventTarget:{addEventListener:jot,removeEventListener:Wot}}=Oxe(),{format:Vot,parse:zot}=uO(),{toBuffer:Kot}=US(),Fxe=Symbol("kAborted"),p3=[8,13],Hu=["CONNECTING","OPEN","CLOSING","CLOSED"],Yot=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Jn=class t extends Pot{constructor(e,n,r){super(),this._binaryType=Nxe[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=dO,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?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Bxe(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Nxe.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 Uot({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Fot(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[Jr]=this,s[Jr]=this,e[Jr]=this,i.on("conclude",Qot),i.on("drain",Zot),i.on("error",eat),i.on("message",tat),i.on("ping",nat),i.on("pong",rat),s.onerror=iat,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Gxe),e.on("data",pO),e.on("end",Hxe),e.on("error",jxe),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[Ff.extensionName]&&this._extensions[Ff.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){io(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._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$xe(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){h3(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||dO,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){h3(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||dO,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){h3(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ff.extensionName]||(i.compress=!1),this._sender.send(e||dO,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){io(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Jn,"CONNECTING",{enumerable:!0,value:Hu.indexOf("CONNECTING")});Object.defineProperty(Jn.prototype,"CONNECTING",{enumerable:!0,value:Hu.indexOf("CONNECTING")});Object.defineProperty(Jn,"OPEN",{enumerable:!0,value:Hu.indexOf("OPEN")});Object.defineProperty(Jn.prototype,"OPEN",{enumerable:!0,value:Hu.indexOf("OPEN")});Object.defineProperty(Jn,"CLOSING",{enumerable:!0,value:Hu.indexOf("CLOSING")});Object.defineProperty(Jn.prototype,"CLOSING",{enumerable:!0,value:Hu.indexOf("CLOSING")});Object.defineProperty(Jn,"CLOSED",{enumerable:!0,value:Hu.indexOf("CLOSED")});Object.defineProperty(Jn.prototype,"CLOSED",{enumerable:!0,value:Hu.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Jn.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Jn.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[f3])return e[Got];return null},set(e){for(let n of this.listeners(t))if(n[f3]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[f3]:!0})}})});Jn.prototype.addEventListener=jot;Jn.prototype.removeEventListener=Wot;Wxe.exports=Jn;function Bxe(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qot,protocolVersion:p3[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol: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,!p3.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${p3.join(", ")})`);let s;if(e instanceof d3)s=e;else try{s=new d3(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let y=new SyntaxError(c);if(t._redirects===0)throw y;fO(t,y);return}let l=o?443:80,u=Dot(16).toString("base64"),d=o?Oot.request:Mot.request,f=new Set,m;if(i.createConnection=i.createConnection||(o?Jot:Xot),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(m=new Ff({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Vot({[Ff.extensionName]:m.offer()})),n.length){for(let y of n){if(typeof y!="string"||!Yot.test(y)||f.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(y)}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),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let y=i.path.split(":");i.socketPath=y[0],i.path=y[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[w,S]of Object.entries(y))r.headers[w.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,y||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=t._req=d(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(i);i.timeout&&g.on("timeout",()=>{io(t,g,"Opening handshake has timed out")}),g.on("error",y=>{g===null||g[Fxe]||(g=t._req=null,fO(t,y))}),g.on("response",y=>{let w=y.headers.location,S=y.statusCode;if(w&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){io(t,g,"Maximum redirects exceeded");return}g.abort();let T;try{T=new d3(w,e)}catch{let C=new SyntaxError(`Invalid URL: ${w}`);fO(t,C);return}Bxe(t,T,n,r)}else t.emit("unexpected-response",g,y)||io(t,g,`Unexpected server response: ${y.statusCode}`)}),g.on("upgrade",(y,w,S)=>{if(t.emit("upgrade",y),t.readyState!==Jn.CONNECTING)return;g=t._req=null;let T=y.headers.upgrade;if(T===void 0||T.toLowerCase()!=="websocket"){io(t,w,"Invalid Upgrade header");return}let R=Lot("sha1").update(u+$ot).digest("base64");if(y.headers["sec-websocket-accept"]!==R){io(t,w,"Invalid Sec-WebSocket-Accept header");return}let C=y.headers["sec-websocket-protocol"],D;if(C!==void 0?f.size?f.has(C)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":f.size&&(D="Server sent no subprotocol"),D){io(t,w,D);return}C&&(t._protocol=C);let $=y.headers["sec-websocket-extensions"];if($!==void 0){if(!m){io(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let G;try{G=zot($)}catch{io(t,w,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(G);if(V.length!==1||V[0]!==Ff.extensionName){io(t,w,"Server indicated an extension that was not requested");return}try{m.accept(G[Ff.extensionName])}catch{io(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ff.extensionName]=m}t.setSocket(w,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function fO(t,e){t._readyState=Jn.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Xot(t){return t.path=t.socketPath,Lxe.connect(t)}function Jot(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Lxe.isIP(t.host)?"":t.host),Not.connect(t)}function io(t,e,n){t._readyState=Jn.CLOSING;let r=new Error(n);Error.captureStackTrace(r,io),e.setHeader?(e[Fxe]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(fO,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function h3(t,e,n){if(e){let r=Bot(e)?e.size:Kot(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Hu[t.readyState]})`);process.nextTick(n,r)}}function Qot(t,e){let n=this[Jr];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Jr]!==void 0&&(n._socket.removeListener("data",pO),process.nextTick(qxe,n._socket),t===1005?n.close():n.close(t,e))}function Zot(){let t=this[Jr];t.isPaused||t._socket.resume()}function eat(t){let e=this[Jr];e._socket[Jr]!==void 0&&(e._socket.removeListener("data",pO),process.nextTick(qxe,e._socket),e.close(t[Hot])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Dxe(){this[Jr].emitClose()}function tat(t,e){this[Jr].emit("message",t,e)}function nat(t){let e=this[Jr];e._autoPong&&e.pong(t,!this._isServer,Uxe),e.emit("ping",t)}function rat(t){this[Jr].emit("pong",t)}function qxe(t){t.resume()}function iat(t){let e=this[Jr];e.readyState!==Jn.CLOSED&&(e.readyState===Jn.OPEN&&(e._readyState=Jn.CLOSING,$xe(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $xe(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Gxe(){let t=this[Jr];if(this.removeListener("close",Gxe),this.removeListener("data",pO),this.removeListener("end",Hxe),t._readyState=Jn.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[Jr]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Dxe),t._receiver.on("finish",Dxe))}function pO(t){this[Jr]._receiver.write(t)||this.pause()}function Hxe(){let t=this[Jr];t._readyState=Jn.CLOSING,t._receiver.end(),this.end()}function jxe(){let t=this[Jr];this.removeListener("error",jxe),this.on("error",Uxe),t&&(t._readyState=Jn.CLOSING,this.destroy())}});var Yxe=B((cNt,Kxe)=>{"use strict";var aNt=hO(),{Duplex:sat}=require("stream");function Vxe(t){t.emit("close")}function oat(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zxe(t){this.removeListener("error",zxe),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function aat(t,e){let n=!0,r=new sat({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&r._readableState.objectMode?s.toString():s;r.push(a)||t.pause()}),t.once("error",function(s){r.destroyed||(n=!1,r.destroy(s))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Vxe,r);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Vxe,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,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,s,o)});return}t.send(i,o)},r.on("end",oat),r.on("error",zxe),r}Kxe.exports=aat});var m3=B((lNt,Xxe)=>{"use strict";var{tokenChars:cat}=sv();function lat(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&cat[o]===1)n===-1&&(n=i);else if(i!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=i);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),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 s=t.slice(n,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Xxe.exports={parse:lat}});var rbe=B((dNt,nbe)=>{"use strict";var uat=require("events"),mO=require("http"),{Duplex:uNt}=require("stream"),{createHash:dat}=require("crypto"),Jxe=uO(),hm=iv(),fat=m3(),pat=hO(),{CLOSE_TIMEOUT:hat,GUID:mat,kWebSocket:gat}=qu(),yat=/^[+/0-9A-Za-z]{22}==$/,Qxe=0,Zxe=1,tbe=2,g3=class extends uat{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:hat,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pat,...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=mO.createServer((r,i)=>{let s=mO.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),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=_at(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Qxe}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===tbe){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(GS,this);return}if(e&&this.once("close",e),this._state!==Zxe)if(this._state=Zxe,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(GS,this):process.nextTick(GS,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{GS(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",ebe);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){mm(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){mm(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!yat.test(s)){mm(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){mm(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){HS(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=fat.parse(c)}catch{mm(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new hm({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=Jxe.parse(u);m[hm.extensionName]&&(f.accept(m[hm.extensionName]),d[hm.extensionName]=f)}catch{mm(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(m,g,y,w)=>{if(!m)return HS(n,g||401,y,w);this.completeUpgrade(d,s,l,e,n,r,i)});return}if(!this.options.verifyClient(f))return HS(n,401)}this.completeUpgrade(d,s,l,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[gat])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Qxe)return HS(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dat("sha1").update(n+mat).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[hm.extensionName]){let d=e[hm.extensionName].params,f=Jxe.format({[hm.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
517
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var j3=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(nc.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===nc.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(nc.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 DS.universe("universe-domain"),e||=G3.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=G3.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,jSe.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=G3.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 ev.JWT?n.scopes=this.scopes:n instanceof LS.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof ev.JWT?n.scopes=this.scopes:n instanceof LS.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new xst.Compute(e));throw new Error(nc.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=DS.getGCPResidency()||await DS.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=ZP.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=ZP.join(s,".config","gcloud"))}if(!n)return null;let r=ZP.join(n,"application_default_credentials.json");return NS.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=NS.realpathSync(e),!NS.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=NS.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!==tv.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${tv.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 tv.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let r,i=(0,jSe.originalOrCamelOptions)(n).get("universe_domain");return e.type===GSe.USER_REFRESH_ACCOUNT_TYPE?(r=new GSe.UserRefreshClient(n),r.fromJSON(e)):e.type===tv.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===LS.EXTERNAL_ACCOUNT_TYPE?(r=Ast.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===HSe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new HSe.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===H3.GDCH_SERVICE_ACCOUNT_TYPE?(r=new H3.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new ev.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(s=>r(null,s),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 s=[];e.setEncoding("utf8").on("error",i).on("data",o=>s.push(o)).on("end",()=>{try{try{let o=JSON.parse(s.join("")),a=this._cacheClientFromJSON(o,n);return r(a)}catch(o){if(!this.keyFilename)throw o;let a=new ev.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),r(a)}}catch(o){return i(o)}})})}fromAPIKey(e,n={}){return new ev.JWT({...n,apiKey:e})}_isWindows(){let e=wst.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,vst.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!==LS.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await DS.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 tv.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof LS.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([DS.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(nc.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 H3.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),o=e.createWithGdchAudience(s);return this.cachedCredential=o,o}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=ZP.resolve(this.keyFilename),n=NS.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 bst.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=Est.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,Tst.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 tv.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,Sst.createCrypto)();if(r instanceof ev.JWT&&r.key)return await s.sign(r.key,e);let o=await this.getCredentials();if(!o.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,o.client_email,e,n)}async signBlob(e,n,r,i){let s=new URL(i+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};nc.GoogleAuth=j3});var VSe=B(eO=>{"use strict";Object.defineProperty(eO,"__esModule",{value:!0});eO.IAMAuth=void 0;var W3=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}}};eO.IAMAuth=W3});var zSe=B(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});dl.DownscopedClient=dl.EXPIRATION_TIME_OFFSET=dl.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Cst=di(),Rst=require("stream"),V3=no(),Ist=MP(),kst="urn:ietf:params:oauth:grant-type:token-exchange",Pst="urn:ietf:params:oauth:token-type:access_token",Ost="urn:ietf:params:oauth:token-type:access_token";dl.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;dl.EXPIRATION_TIME_OFFSET=300*1e3;var z3=class extends V3.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof V3.AuthClient?{}:e),e instanceof V3.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>dl.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${dl.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 Ist.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=Cst.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let s=i.response;if(s){let o=s.status,a=s.config.data instanceof Rst.Readable;if(!n&&(o===401||o===403)&&!a&&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:kst,requestedTokenType:Pst,subjectToken:e,subjectTokenType:Ost},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:i;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,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}};dl.DownscopedClient=z3});var KSe=B(tO=>{"use strict";Object.defineProperty(tO,"__esModule",{value:!0});tO.PassThroughClient=void 0;var Mst=no(),K3=class extends Mst.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};tO.PassThroughClient=K3});var exe=B(Ie=>{"use strict";var Nst=Ie&&Ie.__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]})),Dst=Ie&&Ie.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Nst(e,t,n)};Object.defineProperty(Ie,"__esModule",{value:!0});Ie.GoogleAuth=Ie.auth=Ie.GDCH_SERVICE_ACCOUNT_TYPE=Ie.GdchClient=Ie.PassThroughClient=Ie.ExternalAccountAuthorizedUserClient=Ie.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Ie.ExecutableError=Ie.PluggableAuthClient=Ie.DownscopedClient=Ie.BaseExternalAccountClient=Ie.ExternalAccountClient=Ie.IdentityPoolClient=Ie.AwsRequestSigner=Ie.AwsClient=Ie.UserRefreshClient=Ie.LoginTicket=Ie.ClientAuthentication=Ie.OAuth2Client=Ie.CodeChallengeMethod=Ie.Impersonated=Ie.JWT=Ie.JWTAccess=Ie.IdTokenClient=Ie.IAMAuth=Ie.GCPEnv=Ie.Compute=Ie.DEFAULT_UNIVERSE=Ie.AuthClient=Ie.gaxios=Ie.gcpMetadata=void 0;var YSe=WSe();Object.defineProperty(Ie,"GoogleAuth",{enumerable:!0,get:function(){return YSe.GoogleAuth}});Ie.gcpMetadata=CS();Ie.gaxios=di();var XSe=no();Object.defineProperty(Ie,"AuthClient",{enumerable:!0,get:function(){return XSe.AuthClient}});Object.defineProperty(Ie,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return XSe.DEFAULT_UNIVERSE}});var Lst=L4();Object.defineProperty(Ie,"Compute",{enumerable:!0,get:function(){return Lst.Compute}});var Ust=B4();Object.defineProperty(Ie,"GCPEnv",{enumerable:!0,get:function(){return Ust.GCPEnv}});var Fst=VSe();Object.defineProperty(Ie,"IAMAuth",{enumerable:!0,get:function(){return Fst.IAMAuth}});var Bst=F4();Object.defineProperty(Ie,"IdTokenClient",{enumerable:!0,get:function(){return Bst.IdTokenClient}});var qst=Z4();Object.defineProperty(Ie,"JWTAccess",{enumerable:!0,get:function(){return qst.JWTAccess}});var $st=t3();Object.defineProperty(Ie,"JWT",{enumerable:!0,get:function(){return $st.JWT}});var Gst=s3();Object.defineProperty(Ie,"Impersonated",{enumerable:!0,get:function(){return Gst.Impersonated}});var Y3=Mf();Object.defineProperty(Ie,"CodeChallengeMethod",{enumerable:!0,get:function(){return Y3.CodeChallengeMethod}});Object.defineProperty(Ie,"OAuth2Client",{enumerable:!0,get:function(){return Y3.OAuth2Client}});Object.defineProperty(Ie,"ClientAuthentication",{enumerable:!0,get:function(){return Y3.ClientAuthentication}});var Hst=O4();Object.defineProperty(Ie,"LoginTicket",{enumerable:!0,get:function(){return Hst.LoginTicket}});var jst=r3();Object.defineProperty(Ie,"UserRefreshClient",{enumerable:!0,get:function(){return jst.UserRefreshClient}});var Wst=b3();Object.defineProperty(Ie,"AwsClient",{enumerable:!0,get:function(){return Wst.AwsClient}});var Vst=w3();Object.defineProperty(Ie,"AwsRequestSigner",{enumerable:!0,get:function(){return Vst.AwsRequestSigner}});var zst=v3();Object.defineProperty(Ie,"IdentityPoolClient",{enumerable:!0,get:function(){return zst.IdentityPoolClient}});var Kst=L3();Object.defineProperty(Ie,"ExternalAccountClient",{enumerable:!0,get:function(){return Kst.ExternalAccountClient}});var Yst=Df();Object.defineProperty(Ie,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Yst.BaseExternalAccountClient}});var Xst=zSe();Object.defineProperty(Ie,"DownscopedClient",{enumerable:!0,get:function(){return Xst.DownscopedClient}});var JSe=N3();Object.defineProperty(Ie,"PluggableAuthClient",{enumerable:!0,get:function(){return JSe.PluggableAuthClient}});Object.defineProperty(Ie,"ExecutableError",{enumerable:!0,get:function(){return JSe.ExecutableError}});var QSe=B3();Object.defineProperty(Ie,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return QSe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Ie,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return QSe.ExternalAccountAuthorizedUserClient}});var Jst=KSe();Object.defineProperty(Ie,"PassThroughClient",{enumerable:!0,get:function(){return Jst.PassThroughClient}});var ZSe=$3();Object.defineProperty(Ie,"GdchClient",{enumerable:!0,get:function(){return ZSe.GdchClient}});Object.defineProperty(Ie,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return ZSe.GDCH_SERVICE_ACCOUNT_TYPE}});Dst(J4(),Ie);var Qst=new YSe.GoogleAuth;Ie.auth=Qst});var qu=B((KMt,rxe)=>{"use strict";var txe=["nodebuffer","arraybuffer","fragments"],nxe=typeof Blob<"u";nxe&&txe.push("blob");rxe.exports={BINARY_TYPES:txe,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nxe,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var US=B((YMt,nO)=>{"use strict";var{EMPTY_BUFFER:Zst}=qu(),X3=Buffer[Symbol.species];function eot(t,e){if(t.length===0)return Zst;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let s=t[i];n.set(s,r),r+=s.length}return r<e?new X3(n.buffer,n.byteOffset,r):n}function ixe(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function sxe(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function tot(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function J3(t){if(J3.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new X3(t):ArrayBuffer.isView(t)?e=new X3(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),J3.readOnly=!1),e}nO.exports={concat:eot,mask:ixe,toArrayBuffer:tot,toBuffer:J3,unmask:sxe};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");nO.exports.mask=function(e,n,r,i,s){s<48?ixe(e,n,r,i,s):t.mask(e,n,r,i,s)},nO.exports.unmask=function(e,n){e.length<32?sxe(e,n):t.unmask(e,n)}}catch{}});var cxe=B((XMt,axe)=>{"use strict";var oxe=Symbol("kDone"),Q3=Symbol("kRun"),Z3=class{constructor(e){this[oxe]=()=>{this.pending--,this[Q3]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Q3]()}[Q3](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[oxe])}}};axe.exports=Z3});var iv=B((JMt,fxe)=>{"use strict";var FS=require("zlib"),lxe=US(),not=cxe(),{kStatusCode:uxe}=qu(),rot=Buffer[Symbol.species],iot=Buffer.from([0,0,255,255]),iO=Symbol("permessage-deflate"),$u=Symbol("total-length"),nv=Symbol("callback"),Uf=Symbol("buffers"),rv=Symbol("error"),rO,eW=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,!rO){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;rO=new not(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[nv];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"&&!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 s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}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){rO.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){rO.add(i=>{this._compress(e,n,(s,o)=>{i(),r(s,o)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?FS.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=FS.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[iO]=this,this._inflate[$u]=0,this._inflate[Uf]=[],this._inflate.on("error",oot),this._inflate.on("data",dxe)}this._inflate[nv]=r,this._inflate.write(e),n&&this._inflate.write(iot),this._inflate.flush(()=>{let s=this._inflate[rv];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=lxe.concat(this._inflate[Uf],this._inflate[$u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$u]=0,this._inflate[Uf]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?FS.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=FS.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[$u]=0,this._deflate[Uf]=[],this._deflate.on("data",sot)}this._deflate[nv]=r,this._deflate.write(e),this._deflate.flush(FS.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=lxe.concat(this._deflate[Uf],this._deflate[$u]);n&&(s=new rot(s.buffer,s.byteOffset,s.length-4)),this._deflate[nv]=null,this._deflate[$u]=0,this._deflate[Uf]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};fxe.exports=eW;function sot(t){this[Uf].push(t),this[$u]+=t.length}function dxe(t){if(this[$u]+=t.length,this[iO]._maxPayload<1||this[$u]<=this[iO]._maxPayload){this[Uf].push(t);return}this[rv]=new RangeError("Max payload size exceeded"),this[rv].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rv][uxe]=1009,this.removeListener("data",dxe),this.reset()}function oot(t){if(this[iO]._inflate=null,this[rv]){this[nv](this[rv]);return}t[uxe]=1007,this[nv](t)}});var sv=B((QMt,sO)=>{"use strict";var{isUtf8:pxe}=require("buffer"),{hasBlob:aot}=qu(),cot=[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 lot(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function tW(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 uot(t){return aot&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}sO.exports={isBlob:uot,isValidStatusCode:lot,isValidUTF8:tW,tokenChars:cot};if(pxe)sO.exports.isValidUTF8=function(t){return t.length<24?tW(t):pxe(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");sO.exports.isValidUTF8=function(e){return e.length<32?tW(e):t(e)}}catch{}});var oW=B((ZMt,Exe)=>{"use strict";var{Writable:dot}=require("stream"),hxe=iv(),{BINARY_TYPES:fot,EMPTY_BUFFER:mxe,kStatusCode:pot,kWebSocket:hot}=qu(),{concat:nW,toArrayBuffer:mot,unmask:got}=US(),{isValidStatusCode:yot,isValidUTF8:gxe}=sv(),oO=Buffer[Symbol.species],Qo=0,yxe=1,_xe=2,vxe=3,rW=4,iW=5,aO=6,sW=class extends dot{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||fot[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[hot]=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._fragments=[],this._errored=!1,this._loop=!1,this._state=Qo}_write(e,n,r){if(this._opcode===8&&this._state==Qo)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 oO(r.buffer,r.byteOffset+e,r.length-e),new oO(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 oO(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 Qo:this.getInfo(e);break;case yxe:this.getPayloadLength16(e);break;case _xe:this.getPayloadLength64(e);break;case vxe:this.getMask();break;case rW:this.getData(e);break;case iW:case aO: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[hxe.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=yxe:this._payloadLength===127?this._state=_xe: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=vxe:this._state=rW}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=rW}getData(e){let n=mxe;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&&got(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=iW,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[hxe.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return n(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(o);return}this._fragments.push(s)}this.dataMessage(n),this._state===Qo&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qo;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=nW(r,n):this._binaryType==="arraybuffer"?i=mot(nW(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit("message",i,!0),this._state=Qo,this.startLoop(e)}))}else{let i=nW(r,n);if(!this._skipUTF8Validation&&!gxe(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===iW||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit("message",i,!1),this._state=Qo,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,mxe),this.end();else{let r=e.readUInt16BE(0);if(!yot(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new oO(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gxe(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=Qo;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qo):(this._state=aO,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qo,this.startLoop(n)}))}createError(e,n,r,i,s){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=s,o[pot]=i,o}};Exe.exports=sW});var lW=B((tNt,xxe)=>{"use strict";var{Duplex:eNt}=require("stream"),{randomFillSync:_ot}=require("crypto"),{types:{isUint8Array:vot}}=require("util"),wxe=iv(),{EMPTY_BUFFER:Eot,kWebSocket:wot,NOOP:Sot}=qu(),{isBlob:ov,isValidStatusCode:xot}=sv(),{mask:Sxe,toBuffer:dm}=US(),Zo=Symbol("kByteLength"),bot=Buffer.alloc(4),cO=8*1024,fm,av=cO,rc=0,Tot=1,Aot=2,aW=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=rc,this.onerror=Sot,this[wot]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||bot,n.generateMask?n.generateMask(r):(av===cO&&(fm===void 0&&(fm=Buffer.alloc(cO)),_ot(fm,0,cO),av=0),r[0]=fm[av++],r[1]=fm[av++],r[2]=fm[av++],r[3]=fm[av++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[Zo]!==void 0?a=n[Zo]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?a+s:s);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],o?[l,e]:i?(Sxe(e,r,l,s,a),[l]):(Sxe(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,i){let s;if(e===void 0)s=Eot;else{if(typeof e!="number"||!xot(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof n=="string")s.write(n,2);else if(vot(n))s.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Zo]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==rc?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ov(e)?(i=e.size,s=!1):(e=dm(e),i=e.length,s=dm.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Zo]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==rc?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ov(e)?(i=e.size,s=!1):(e=dm(e),i=e.length,s=dm.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Zo]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==rc?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[wxe.extensionName],s=n.binary?2:1,o=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ov(e)?(a=e.size,c=!1):(e=dm(e),a=e.length,c=dm.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),n.fin&&(this._firstFragment=!0);let l={[Zo]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};ov(e)?this._state!==rc?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==rc?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[Zo],this._state=Aot,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(cW,this,a,i);return}this._bufferedBytes-=r[Zo];let o=dm(s);n?this.dispatch(o,n,r,i):(this._state=rc,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Cot,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[wxe.extensionName];this._bufferedBytes+=r[Zo],this._state=Tot,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");cW(this,c,i);return}this._bufferedBytes-=r[Zo],this._state=rc,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===rc&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Zo],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Zo],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)}};xxe.exports=aW;function cW(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],s=i[i.length-1];typeof s=="function"&&s(e)}}function Cot(t,e,n){cW(t,e,n),t.onerror(e)}});var Oxe=B((nNt,Pxe)=>{"use strict";var{kForOnEventAttribute:BS,kListener:uW}=qu(),bxe=Symbol("kCode"),Txe=Symbol("kData"),Axe=Symbol("kError"),Cxe=Symbol("kMessage"),Rxe=Symbol("kReason"),cv=Symbol("kTarget"),Ixe=Symbol("kType"),kxe=Symbol("kWasClean"),Gu=class{constructor(e){this[cv]=null,this[Ixe]=e}get target(){return this[cv]}get type(){return this[Ixe]}};Object.defineProperty(Gu.prototype,"target",{enumerable:!0});Object.defineProperty(Gu.prototype,"type",{enumerable:!0});var pm=class extends Gu{constructor(e,n={}){super(e),this[bxe]=n.code===void 0?0:n.code,this[Rxe]=n.reason===void 0?"":n.reason,this[kxe]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[bxe]}get reason(){return this[Rxe]}get wasClean(){return this[kxe]}};Object.defineProperty(pm.prototype,"code",{enumerable:!0});Object.defineProperty(pm.prototype,"reason",{enumerable:!0});Object.defineProperty(pm.prototype,"wasClean",{enumerable:!0});var lv=class extends Gu{constructor(e,n={}){super(e),this[Axe]=n.error===void 0?null:n.error,this[Cxe]=n.message===void 0?"":n.message}get error(){return this[Axe]}get message(){return this[Cxe]}};Object.defineProperty(lv.prototype,"error",{enumerable:!0});Object.defineProperty(lv.prototype,"message",{enumerable:!0});var qS=class extends Gu{constructor(e,n={}){super(e),this[Txe]=n.data===void 0?null:n.data}get data(){return this[Txe]}};Object.defineProperty(qS.prototype,"data",{enumerable:!0});var Rot={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[BS]&&i[uW]===e&&!i[BS])return;let r;if(t==="message")r=function(s,o){let a=new qS("message",{data:o?s:s.toString()});a[cv]=this,lO(e,this,a)};else if(t==="close")r=function(s,o){let a=new pm("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[cv]=this,lO(e,this,a)};else if(t==="error")r=function(s){let o=new lv("error",{error:s,message:s.message});o[cv]=this,lO(e,this,o)};else if(t==="open")r=function(){let s=new Gu("open");s[cv]=this,lO(e,this,s)};else return;r[BS]=!!n[BS],r[uW]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[uW]===e&&!n[BS]){this.removeListener(t,n);break}}};Pxe.exports={CloseEvent:pm,ErrorEvent:lv,Event:Gu,EventTarget:Rot,MessageEvent:qS};function lO(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var uO=B((rNt,Mxe)=>{"use strict";var{tokenChars:$S}=sv();function fl(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Iot(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,s=!1,o,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),o===void 0)if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);l===44?(fl(e,m,n),n=Object.create(null)):o=m,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),fl(n,t.slice(c,u),!0),l===44&&(fl(e,o,n),n=Object.create(null),o=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if($S[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(s)if($S[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)s=!1,u=d;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)s=!0;else if(u===-1&&$S[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);r&&(m=m.replace(/\\/g,""),r=!1),fl(n,a,m),l===44&&(fl(e,o,n),n=Object.create(null),o=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(c,u);return o===void 0?fl(e,f,n):(a===void 0?fl(n,f,!0):r?fl(n,a,f.replace(/\\/g,"")):fl(n,a,f),fl(e,o,n)),e}function kot(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 s=r[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Mxe.exports={format:kot,parse:Iot}});var hO=B((oNt,Wxe)=>{"use strict";var Pot=require("events"),Oot=require("https"),Mot=require("http"),Lxe=require("net"),Not=require("tls"),{randomBytes:Dot,createHash:Lot}=require("crypto"),{Duplex:iNt,Readable:sNt}=require("stream"),{URL:dW}=require("url"),Ff=iv(),Uot=oW(),Fot=lW(),{isBlob:Bot}=sv(),{BINARY_TYPES:Nxe,CLOSE_TIMEOUT:qot,EMPTY_BUFFER:dO,GUID:$ot,kForOnEventAttribute:fW,kListener:Got,kStatusCode:Hot,kWebSocket:Jr,NOOP:Uxe}=qu(),{EventTarget:{addEventListener:jot,removeEventListener:Wot}}=Oxe(),{format:Vot,parse:zot}=uO(),{toBuffer:Kot}=US(),Fxe=Symbol("kAborted"),pW=[8,13],Hu=["CONNECTING","OPEN","CLOSING","CLOSED"],Yot=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Jn=class t extends Pot{constructor(e,n,r){super(),this._binaryType=Nxe[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=dO,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?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Bxe(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Nxe.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 Uot({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Fot(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[Jr]=this,s[Jr]=this,e[Jr]=this,i.on("conclude",Qot),i.on("drain",Zot),i.on("error",eat),i.on("message",tat),i.on("ping",nat),i.on("pong",rat),s.onerror=iat,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Gxe),e.on("data",pO),e.on("end",Hxe),e.on("error",jxe),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[Ff.extensionName]&&this._extensions[Ff.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){io(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._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$xe(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){hW(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||dO,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){hW(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||dO,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){hW(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ff.extensionName]||(i.compress=!1),this._sender.send(e||dO,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){io(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Jn,"CONNECTING",{enumerable:!0,value:Hu.indexOf("CONNECTING")});Object.defineProperty(Jn.prototype,"CONNECTING",{enumerable:!0,value:Hu.indexOf("CONNECTING")});Object.defineProperty(Jn,"OPEN",{enumerable:!0,value:Hu.indexOf("OPEN")});Object.defineProperty(Jn.prototype,"OPEN",{enumerable:!0,value:Hu.indexOf("OPEN")});Object.defineProperty(Jn,"CLOSING",{enumerable:!0,value:Hu.indexOf("CLOSING")});Object.defineProperty(Jn.prototype,"CLOSING",{enumerable:!0,value:Hu.indexOf("CLOSING")});Object.defineProperty(Jn,"CLOSED",{enumerable:!0,value:Hu.indexOf("CLOSED")});Object.defineProperty(Jn.prototype,"CLOSED",{enumerable:!0,value:Hu.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Jn.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Jn.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[fW])return e[Got];return null},set(e){for(let n of this.listeners(t))if(n[fW]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[fW]:!0})}})});Jn.prototype.addEventListener=jot;Jn.prototype.removeEventListener=Wot;Wxe.exports=Jn;function Bxe(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qot,protocolVersion:pW[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol: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,!pW.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${pW.join(", ")})`);let s;if(e instanceof dW)s=e;else try{s=new dW(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let y=new SyntaxError(c);if(t._redirects===0)throw y;fO(t,y);return}let l=o?443:80,u=Dot(16).toString("base64"),d=o?Oot.request:Mot.request,f=new Set,m;if(i.createConnection=i.createConnection||(o?Jot:Xot),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(m=new Ff({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Vot({[Ff.extensionName]:m.offer()})),n.length){for(let y of n){if(typeof y!="string"||!Yot.test(y)||f.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(y)}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),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let y=i.path.split(":");i.socketPath=y[0],i.path=y[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[w,S]of Object.entries(y))r.headers[w.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,y||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=t._req=d(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(i);i.timeout&&g.on("timeout",()=>{io(t,g,"Opening handshake has timed out")}),g.on("error",y=>{g===null||g[Fxe]||(g=t._req=null,fO(t,y))}),g.on("response",y=>{let w=y.headers.location,S=y.statusCode;if(w&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){io(t,g,"Maximum redirects exceeded");return}g.abort();let T;try{T=new dW(w,e)}catch{let C=new SyntaxError(`Invalid URL: ${w}`);fO(t,C);return}Bxe(t,T,n,r)}else t.emit("unexpected-response",g,y)||io(t,g,`Unexpected server response: ${y.statusCode}`)}),g.on("upgrade",(y,w,S)=>{if(t.emit("upgrade",y),t.readyState!==Jn.CONNECTING)return;g=t._req=null;let T=y.headers.upgrade;if(T===void 0||T.toLowerCase()!=="websocket"){io(t,w,"Invalid Upgrade header");return}let R=Lot("sha1").update(u+$ot).digest("base64");if(y.headers["sec-websocket-accept"]!==R){io(t,w,"Invalid Sec-WebSocket-Accept header");return}let C=y.headers["sec-websocket-protocol"],D;if(C!==void 0?f.size?f.has(C)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":f.size&&(D="Server sent no subprotocol"),D){io(t,w,D);return}C&&(t._protocol=C);let $=y.headers["sec-websocket-extensions"];if($!==void 0){if(!m){io(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let G;try{G=zot($)}catch{io(t,w,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(G);if(V.length!==1||V[0]!==Ff.extensionName){io(t,w,"Server indicated an extension that was not requested");return}try{m.accept(G[Ff.extensionName])}catch{io(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ff.extensionName]=m}t.setSocket(w,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function fO(t,e){t._readyState=Jn.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Xot(t){return t.path=t.socketPath,Lxe.connect(t)}function Jot(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Lxe.isIP(t.host)?"":t.host),Not.connect(t)}function io(t,e,n){t._readyState=Jn.CLOSING;let r=new Error(n);Error.captureStackTrace(r,io),e.setHeader?(e[Fxe]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(fO,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function hW(t,e,n){if(e){let r=Bot(e)?e.size:Kot(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Hu[t.readyState]})`);process.nextTick(n,r)}}function Qot(t,e){let n=this[Jr];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Jr]!==void 0&&(n._socket.removeListener("data",pO),process.nextTick(qxe,n._socket),t===1005?n.close():n.close(t,e))}function Zot(){let t=this[Jr];t.isPaused||t._socket.resume()}function eat(t){let e=this[Jr];e._socket[Jr]!==void 0&&(e._socket.removeListener("data",pO),process.nextTick(qxe,e._socket),e.close(t[Hot])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Dxe(){this[Jr].emitClose()}function tat(t,e){this[Jr].emit("message",t,e)}function nat(t){let e=this[Jr];e._autoPong&&e.pong(t,!this._isServer,Uxe),e.emit("ping",t)}function rat(t){this[Jr].emit("pong",t)}function qxe(t){t.resume()}function iat(t){let e=this[Jr];e.readyState!==Jn.CLOSED&&(e.readyState===Jn.OPEN&&(e._readyState=Jn.CLOSING,$xe(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $xe(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Gxe(){let t=this[Jr];if(this.removeListener("close",Gxe),this.removeListener("data",pO),this.removeListener("end",Hxe),t._readyState=Jn.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[Jr]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Dxe),t._receiver.on("finish",Dxe))}function pO(t){this[Jr]._receiver.write(t)||this.pause()}function Hxe(){let t=this[Jr];t._readyState=Jn.CLOSING,t._receiver.end(),this.end()}function jxe(){let t=this[Jr];this.removeListener("error",jxe),this.on("error",Uxe),t&&(t._readyState=Jn.CLOSING,this.destroy())}});var Yxe=B((cNt,Kxe)=>{"use strict";var aNt=hO(),{Duplex:sat}=require("stream");function Vxe(t){t.emit("close")}function oat(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zxe(t){this.removeListener("error",zxe),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function aat(t,e){let n=!0,r=new sat({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&r._readableState.objectMode?s.toString():s;r.push(a)||t.pause()}),t.once("error",function(s){r.destroyed||(n=!1,r.destroy(s))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Vxe,r);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Vxe,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,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,s,o)});return}t.send(i,o)},r.on("end",oat),r.on("error",zxe),r}Kxe.exports=aat});var mW=B((lNt,Xxe)=>{"use strict";var{tokenChars:cat}=sv();function lat(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&cat[o]===1)n===-1&&(n=i);else if(i!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=i);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),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 s=t.slice(n,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Xxe.exports={parse:lat}});var rbe=B((dNt,nbe)=>{"use strict";var uat=require("events"),mO=require("http"),{Duplex:uNt}=require("stream"),{createHash:dat}=require("crypto"),Jxe=uO(),hm=iv(),fat=mW(),pat=hO(),{CLOSE_TIMEOUT:hat,GUID:mat,kWebSocket:gat}=qu(),yat=/^[+/0-9A-Za-z]{22}==$/,Qxe=0,Zxe=1,tbe=2,gW=class extends uat{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:hat,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pat,...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=mO.createServer((r,i)=>{let s=mO.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),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=_at(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Qxe}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===tbe){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(GS,this);return}if(e&&this.once("close",e),this._state!==Zxe)if(this._state=Zxe,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(GS,this):process.nextTick(GS,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{GS(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",ebe);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){mm(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){mm(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!yat.test(s)){mm(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){mm(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){HS(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=fat.parse(c)}catch{mm(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new hm({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=Jxe.parse(u);m[hm.extensionName]&&(f.accept(m[hm.extensionName]),d[hm.extensionName]=f)}catch{mm(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(m,g,y,w)=>{if(!m)return HS(n,g||401,y,w);this.completeUpgrade(d,s,l,e,n,r,i)});return}if(!this.options.verifyClient(f))return HS(n,401)}this.completeUpgrade(d,s,l,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[gat])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Qxe)return HS(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dat("sha1").update(n+mat).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[hm.extensionName]){let d=e[hm.extensionName].params,f=Jxe.format({[hm.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
518
518
  `).join(`\r
519
- `)),s.removeListener("error",ebe),u.setSocket(s,o,{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(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(GS,this)})),a(u,i)}};nbe.exports=g3;function _at(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 GS(t){t._state=tbe,t.emit("close")}function ebe(){this.destroy()}function HS(t,e,n,r){n=n||mO.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} ${mO.STATUS_CODES[e]}\r
519
+ `)),s.removeListener("error",ebe),u.setSocket(s,o,{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(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(GS,this)})),a(u,i)}};nbe.exports=gW;function _at(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 GS(t){t._state=tbe,t.emit("close")}function ebe(){this.destroy()}function HS(t,e,n,r){n=n||mO.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} ${mO.STATUS_CODES[e]}\r
520
520
  `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
521
521
  `)+`\r
522
522
  \r
523
- `+n)}function mm(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,mm),t.emit("wsClientError",o,n,e)}else HS(n,r,i,s)}});var vat,Eat,wat,Sat,xat,bat,y3,Tat,ibe=ae(()=>{vat=ce(Yxe(),1),Eat=ce(uO(),1),wat=ce(iv(),1),Sat=ce(o3(),1),xat=ce(l3(),1),bat=ce(m3(),1),y3=ce(hO(),1),Tat=ce(rbe(),1)});var RAe={};yr(RAe,{ActivityHandling:()=>D6,AdapterSize:()=>Z3,AggregationMetric:()=>i6,ApiError:()=>sx,ApiSpec:()=>C3,AspectRatio:()=>X3,AudioResponseFormat:()=>K6,AudioTranscriptionConfigMode:()=>U6,AuthType:()=>T3,Batches:()=>HO,Behavior:()=>P3,BlockedReason:()=>j3,Caches:()=>jO,CancelTuningJobResponse:()=>ex,Chat:()=>VO,Chats:()=>WO,ComputeTokensResponse:()=>IO,ContentReferenceImage:()=>pV,ControlReferenceImage:()=>uV,ControlReferenceType:()=>_6,CountTokensResponse:()=>QS,CreateFileResponse:()=>UO,DeleteCachedContentResponse:()=>tx,DeleteFileResponse:()=>FO,DeleteModelResponse:()=>JS,Delivery:()=>Y3,DocumentState:()=>l6,DynamicRetrievalConfigMode:()=>O3,EditImageResponse:()=>TO,EditMode:()=>E6,EmbedContentResponse:()=>YS,EmbeddingApiType:()=>KS,EndSensitivity:()=>N6,Environment:()=>R3,EvaluateDatasetResponse:()=>nV,FeatureSelectionPreference:()=>h6,FileSource:()=>R6,FileState:()=>C6,Files:()=>uTe,FinishReason:()=>q3,FunctionCallingConfigMode:()=>B3,FunctionResponse:()=>j6,FunctionResponseBlob:()=>G6,FunctionResponseFileData:()=>$6,FunctionResponsePart:()=>H6,FunctionResponseScheduling:()=>b3,GenerateContentResponse:()=>Bf,GenerateContentResponsePromptFeedback:()=>V6,GenerateContentResponseUsageMetadata:()=>z6,GenerateImagesResponse:()=>bO,GenerateVideosOperation:()=>ZS,GenerateVideosResponse:()=>Z6,GoogleGenAI:()=>Ez,HarmBlockMethod:()=>U3,HarmBlockThreshold:()=>F3,HarmCategory:()=>L3,HarmProbability:()=>$3,HarmSeverity:()=>G3,HttpElementLocation:()=>A3,HttpResponse:()=>Vu,ImagePromptLanguage:()=>g6,ImageResizeMode:()=>T6,ImageResponseFormat:()=>Y6,ImageSize:()=>J3,ImportFileOperation:()=>DO,ImportFileResponse:()=>rV,InlinedEmbedContentResponse:()=>oV,InlinedResponse:()=>iV,InteractionStatus:()=>k6,JobState:()=>SO,Language:()=>x3,ListBatchJobsResponse:()=>rx,ListCachedContentsResponse:()=>nx,ListDocumentsResponse:()=>OO,ListFileSearchStoresResponse:()=>MO,ListFilesResponse:()=>LO,ListModelsResponse:()=>XS,ListTuningJobsResponse:()=>kO,Live:()=>zO,LiveClientToolResponse:()=>hV,LiveMusicPlaybackControl:()=>gm,LiveMusicServerMessage:()=>$O,LiveSendToolResponseParameters:()=>mV,LiveServerMessage:()=>qO,MaskReferenceImage:()=>lV,MaskReferenceMode:()=>y6,MatchOperation:()=>t6,MediaModality:()=>V3,MediaProcessing:()=>d6,MediaResolution:()=>K3,Modality:()=>zS,ModelStage:()=>z3,Models:()=>_m,MusicGenerationMode:()=>B6,Operations:()=>YO,Outcome:()=>S3,PagedItem:()=>pl,Pager:()=>hl,PairwiseChoice:()=>s6,PartMediaResolutionLevel:()=>f6,PersonGeneration:()=>N3,PhishBlockThreshold:()=>k3,ProminentPeople:()=>D3,RawReferenceImage:()=>cV,RecontextImageResponse:()=>CO,RegisterFilesResponse:()=>BO,ReinforcementTuningAutoraterScorerParsedResponseConversionScorer:()=>tV,ReinforcementTuningParseResponseConfig:()=>eV,ReinforcementTuningThinkingLevel:()=>n6,ReplayResponse:()=>aV,ResourceScope:()=>xO,ResponseFormat:()=>Q6,ResponseParseType:()=>e6,SafetyFilterLevel:()=>m6,SafetyPolicy:()=>I3,Scale:()=>F6,SegmentImageResponse:()=>RO,SegmentMode:()=>w6,ServiceTier:()=>u6,Session:()=>KO,SingleEmbedContentResponse:()=>sV,StartSensitivity:()=>M6,StyleReferenceImage:()=>dV,SubjectReferenceImage:()=>fV,SubjectReferenceType:()=>v6,TextResponseFormat:()=>X6,ThinkingLevel:()=>M3,Tokens:()=>XO,ToolResponse:()=>q6,ToolType:()=>p6,TrafficType:()=>W3,TuningJobState:()=>r6,TuningMethod:()=>A6,TuningMode:()=>Q3,TuningSpeed:()=>a6,TuningTask:()=>c6,TurnCompleteReason:()=>I6,TurnCoverage:()=>L6,Type:()=>Wu,UploadToFileSearchStoreOperation:()=>ix,UploadToFileSearchStoreResponse:()=>gV,UploadToFileSearchStoreResumableResponse:()=>NO,UpscaleImageResponse:()=>AO,UrlRetrievalStatus:()=>H3,VadSignalType:()=>P6,ValidateRewardResponse:()=>PO,VideoCompressionQuality:()=>b6,VideoGenerationMaskMode:()=>x6,VideoGenerationReferenceType:()=>S6,VideoOrientation:()=>o6,VideoResponseFormat:()=>J6,VoiceActivityType:()=>O6,createFunctionResponsePartFromBase64:()=>Wat,createFunctionResponsePartFromUri:()=>Vat,createModelContent:()=>ect,createPartFromBase64:()=>Xat,createPartFromCodeExecutionResult:()=>Jat,createPartFromExecutableCode:()=>Qat,createPartFromFunctionCall:()=>Kat,createPartFromFunctionResponse:()=>Yat,createPartFromText:()=>W6,createPartFromUri:()=>zat,createUserContent:()=>Zat,mcpToTool:()=>Zft,setDefaultBaseUrls:()=>Cat});function Cat(t){Vbe=t.geminiUrl,zbe=t.vertexUrl}function Rat(){return{geminiUrl:Vbe,vertexUrl:zbe}}function Iat(t,e,n,r){var i,s;if(!t?.baseUrl){let o=Rat();return e?(i=o.vertexUrl)!==null&&i!==void 0?i:n:(s=o.geminiUrl)!==null&&s!==void 0?s:r}return t.baseUrl}function Ce(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(r,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let s=e[i];return s!=null?String(s):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}function h(t,e,n){for(let s=0;s<e.length-1;s++){let o=e[s];if(o.endsWith("[]")){let a=o.slice(0,-2);if(!(a in t))if(Array.isArray(n))t[a]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${o}`);if(Array.isArray(t[a])){let c=t[a];if(Array.isArray(n))for(let l=0;l<c.length;l++){let u=c[l];h(u,e.slice(s+1),n[l])}else for(let l of c)h(l,e.slice(s+1),n)}return}else if(o.endsWith("[0]")){let a=o.slice(0,-3);a in t||(t[a]=[{}]);let c=t[a];h(c[0],e.slice(s+1),n);return}(!t[o]||typeof t[o]!="object")&&(t[o]={}),t=t[o]}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 p(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 s=i.slice(0,-2);if(s in t){let o=t[s];return Array.isArray(o)?o.map(a=>p(a,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 kat(t,e){for(let[n,r]of Object.entries(e)){let i=n.split("."),s=r.split("."),o=new Set,a=-1;for(let c=0;c<i.length;c++)if(i[c]==="*"){a=c;break}if(a!==-1&&s.length>a)for(let c=a;c<s.length;c++){let l=s[c];l!=="*"&&!l.endsWith("[]")&&!l.endsWith("[0]")&&o.add(l)}w3(t,i,s,0,o)}}function w3(t,e,n,r,i){if(r>=e.length||typeof t!="object"||t===null)return;let s=e[r];if(s.endsWith("[]")){let o=s.slice(0,-2),a=t;if(o in a&&Array.isArray(a[o]))for(let c of a[o])w3(c,e,n,r+1,i)}else if(s==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,a=Object.keys(o).filter(l=>!l.startsWith("_")&&!i.has(l)),c={};for(let l of a)c[l]=o[l];for(let[l,u]of Object.entries(c)){let d=[];for(let f of n.slice(r))f==="*"?d.push(l):d.push(f);h(o,d,u)}for(let l of a)delete o[l]}}else{let o=t;s in o&&w3(o[s],e,n,r+1,i)}}function wz(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function Pat(t){let e={},n=p(t,["operationName"]);n!=null&&h(e,["operationName"],n);let r=p(t,["resourceName"]);return r!=null&&h(e,["_url","resourceName"],r),e}function Oat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response","generateVideoResponse"]);return o!=null&&h(e,["response"],Nat(o)),e}function Mat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Dat(o)),e}function Nat(t){let e={},n=p(t,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>Lat(o))),h(e,["generatedVideos"],s)}let r=p(t,["raiMediaFilteredCount"]);r!=null&&h(e,["raiMediaFilteredCount"],r);let i=p(t,["raiMediaFilteredReasons"]);return i!=null&&h(e,["raiMediaFilteredReasons"],i),e}function Dat(t){let e={},n=p(t,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>Uat(o))),h(e,["generatedVideos"],s)}let r=p(t,["raiMediaFilteredCount"]);r!=null&&h(e,["raiMediaFilteredCount"],r);let i=p(t,["raiMediaFilteredReasons"]);return i!=null&&h(e,["raiMediaFilteredReasons"],i),e}function Lat(t){let e={},n=p(t,["video"]);return n!=null&&h(e,["video"],Hat(n)),e}function Uat(t){let e={},n=p(t,["_self"]);return n!=null&&h(e,["video"],jat(n)),e}function Fat(t){let e={},n=p(t,["operationName"]);return n!=null&&h(e,["_url","operationName"],n),e}function Bat(t){let e={},n=p(t,["operationName"]);return n!=null&&h(e,["_url","operationName"],n),e}function qat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],$at(o)),e}function $at(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Sz(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Gat(o)),e}function Gat(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Hat(t){let e={},n=p(t,["uri"]);n!=null&&h(e,["uri"],n);let r=p(t,["encodedVideo"]);r!=null&&h(e,["videoBytes"],wz(r));let i=p(t,["encoding"]);return i!=null&&h(e,["mimeType"],i),e}function jat(t){let e={},n=p(t,["gcsUri"]);n!=null&&h(e,["uri"],n);let r=p(t,["bytesBase64Encoded"]);r!=null&&h(e,["videoBytes"],wz(r));let i=p(t,["mimeType"]);return i!=null&&h(e,["mimeType"],i),e}function Wat(t,e){return{inlineData:{data:t,mimeType:e}}}function Vat(t,e){return{fileData:{fileUri:t,mimeType:e}}}function zat(t,e,n){return Object.assign({fileData:{fileUri:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function W6(t){return{text:t}}function Kat(t,e){return{functionCall:{name:t,args:e}}}function Yat(t,e,n,r=[]){return{functionResponse:Object.assign({id:t,name:e,response:n},r.length>0&&{parts:r})}}function Xat(t,e,n){return Object.assign({inlineData:{data:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function Jat(t,e){return{codeExecutionResult:{outcome:t,output:e}}}function Qat(t,e){return{executableCode:{code:t,language:e}}}function sbe(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 Kbe(t){let e=[];if(typeof t=="string")e.push(W6(t));else if(sbe(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(W6(n));else if(sbe(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 Zat(t){return{role:"user",parts:Kbe(t)}}function ect(t){return{role:"model",parts:Kbe(t)}}function Kt(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 Ybe(t,e){let n=Kt(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 Xbe(t){return Array.isArray(t)?t.map(e=>GO(e)):[GO(t)]}function GO(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function Jbe(t){let e=GO(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Qbe(t){let e=GO(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function obe(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 Zbe(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>obe(e)):[obe(t)]}function yV(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function abe(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function cbe(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function Qr(t){if(t==null)throw new Error("ContentUnion is required");return yV(t)?t:{role:"user",parts:Zbe(t)}}function xz(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let r=Qr(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(t.isVertexAI()){let n=Qr(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=>Qr(n)):[Qr(e)]}function gs(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(abe(t)||cbe(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Qr(t)]}let e=[],n=[],r=yV(t[0]);for(let i of t){let s=yV(i);if(s!=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(s)e.push(i);else{if(abe(i)||cbe(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:Zbe(n)}),e}function tct(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1)e.type=Object.values(Wu).includes(n[0].toUpperCase())?n[0].toUpperCase():Wu.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let r of n)e.anyOf.push({type:Object.values(Wu).includes(r.toUpperCase())?r.toUpperCase():Wu.TYPE_UNSPECIFIED})}}function fv(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 s=t.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type instanceof Array&&tct(t.type,e);for(let[o,a]of Object.entries(t))if(a!=null)if(o=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;e.type=Object.values(Wu).includes(a.toUpperCase())?a.toUpperCase():Wu.TYPE_UNSPECIFIED}else if(n.includes(o))e[o]=fv(a);else if(r.includes(o)){let c=[];for(let l of a){if(l.type=="null"){e.nullable=!0;continue}c.push(fv(l))}e[o]=c}else if(i.includes(o)){let c={};for(let[l,u]of Object.entries(a))c[l]=fv(u);e[o]=c}else{if(o==="additionalProperties")continue;e[o]=a}return e}function bz(t){return fv(t)}function Tz(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 Az(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function gv(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=fv(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=fv(e.response));return t}function yv(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 nct(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 zu(t,e){if(typeof e!="string")throw new Error("name must be a string");return nct(t,e,"cachedContents")}function eTe(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 vm(t){return wz(t)}function rct(t){return t!=null&&typeof t=="object"&&"name"in t}function tTe(t){return t!=null&&typeof t=="object"&&"video"in t}function nTe(t){return t!=null&&typeof t=="object"&&"uri"in t}function Cz(t){var e;let n;if(rct(t)&&(n=t.name),!(nTe(t)&&(n=t.uri,n===void 0))&&!(tTe(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 rTe(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function iTe(t){for(let e of["models","tunedModels","publisherModels"])if(ict(t,e))return t[e];return[]}function ict(t,e){return t!==null&&typeof t=="object"&&e in t}function sct(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 oct(t,e={}){let n=[],r=new Set;for(let i of t){let s=i.name;if(r.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);r.add(s);let o=sct(i,e);o.functionDeclarations&&n.push(...o.functionDeclarations)}return{functionDeclarations:n}}function sTe(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 act(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 oTe(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 s=!1;for(let o of i){if(typeof o!="object"||o===null)continue;let c=o.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function _v(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 aTe(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 cct(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function lct(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 uct(t){let e={},n=p(t,["responsesFile"]);n!=null&&h(e,["fileName"],n);let r=p(t,["inlinedResponses","inlinedResponses"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>jct(o))),h(e,["inlinedResponses"],s)}let i=p(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["inlinedEmbedContentResponses"],s)}return e}function dct(t){let e={},n=p(t,["predictionsFormat"]);n!=null&&h(e,["format"],n);let r=p(t,["gcsDestination","outputUriPrefix"]);r!=null&&h(e,["gcsUri"],r);let i=p(t,["bigqueryDestination","outputUri"]);i!=null&&h(e,["bigqueryUri"],i);let s=p(t,["vertexMultimodalDatasetDestination"]);return s!=null&&h(e,["vertexDataset"],tlt(s)),e}function fct(t){let e={},n=p(t,["format"]);n!=null&&h(e,["predictionsFormat"],n);let r=p(t,["gcsUri"]);r!=null&&h(e,["gcsDestination","outputUriPrefix"],r);let i=p(t,["bigqueryUri"]);i!=null&&h(e,["bigqueryDestination","outputUri"],i);let s=p(t,["vertexDataset"]);if(s!=null&&h(e,["vertexMultimodalDatasetDestination"],nlt(s)),p(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(p(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(p(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 EO(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata","displayName"]);r!=null&&h(e,["displayName"],r);let i=p(t,["metadata","state"]);i!=null&&h(e,["state"],aTe(i));let s=p(t,["metadata","createTime"]);s!=null&&h(e,["createTime"],s);let o=p(t,["metadata","endTime"]);o!=null&&h(e,["endTime"],o);let a=p(t,["metadata","updateTime"]);a!=null&&h(e,["updateTime"],a);let c=p(t,["metadata","model"]);c!=null&&h(e,["model"],c);let l=p(t,["metadata","output"]);return l!=null&&h(e,["dest"],uct(oTe(l))),e}function _V(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["displayName"]);r!=null&&h(e,["displayName"],r);let i=p(t,["state"]);i!=null&&h(e,["state"],aTe(i));let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["createTime"]);o!=null&&h(e,["createTime"],o);let a=p(t,["startTime"]);a!=null&&h(e,["startTime"],a);let c=p(t,["endTime"]);c!=null&&h(e,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(e,["updateTime"],l);let u=p(t,["model"]);u!=null&&h(e,["model"],u);let d=p(t,["inputConfig"]);d!=null&&h(e,["src"],pct(d));let f=p(t,["outputConfig"]);f!=null&&h(e,["dest"],dct(oTe(f)));let m=p(t,["outputInfo"]);m!=null&&h(e,["outputInfo"],m);let g=p(t,["completionStats"]);return g!=null&&h(e,["completionStats"],g),e}function pct(t){let e={},n=p(t,["instancesFormat"]);n!=null&&h(e,["format"],n);let r=p(t,["gcsSource","uris"]);r!=null&&h(e,["gcsUri"],r);let i=p(t,["bigquerySource","inputUri"]);i!=null&&h(e,["bigqueryUri"],i);let s=p(t,["vertexMultimodalDatasetSource","datasetName"]);return s!=null&&h(e,["vertexDatasetName"],s),e}function hct(t,e){let n={};if(p(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(p(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(p(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(p(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=p(e,["fileName"]);r!=null&&h(n,["fileName"],r);let i=p(e,["inlinedRequests"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>Hct(t,o))),h(n,["requests","requests"],s)}return n}function mct(t){let e={},n=p(t,["format"]);n!=null&&h(e,["instancesFormat"],n);let r=p(t,["gcsUri"]);r!=null&&h(e,["gcsSource","uris"],r);let i=p(t,["bigqueryUri"]);i!=null&&h(e,["bigquerySource","inputUri"],i);let s=p(t,["vertexDatasetName"]);if(s!=null&&h(e,["vertexMultimodalDatasetSource","datasetName"],s),p(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(p(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 gct(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function yct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function _ct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function vct(t){let e={},n=p(t,["content"]);n!=null&&h(e,["content"],n);let r=p(t,["citationMetadata"]);r!=null&&h(e,["citationMetadata"],Ect(r));let i=p(t,["tokenCount"]);i!=null&&h(e,["tokenCount"],i);let s=p(t,["finishReason"]);s!=null&&h(e,["finishReason"],s);let o=p(t,["groundingMetadata"]);o!=null&&h(e,["groundingMetadata"],o);let a=p(t,["avgLogprobs"]);a!=null&&h(e,["avgLogprobs"],a);let c=p(t,["index"]);c!=null&&h(e,["index"],c);let l=p(t,["logprobsResult"]);l!=null&&h(e,["logprobsResult"],l);let u=p(t,["safetyRatings"]);if(u!=null){let f=u;Array.isArray(f)&&(f=f.map(m=>m)),h(e,["safetyRatings"],f)}let d=p(t,["urlContextMetadata"]);return d!=null&&h(e,["urlContextMetadata"],d),e}function Ect(t){let e={},n=p(t,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),h(e,["citations"],r)}return e}function cTe(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Jct(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function wct(t,e){let n={},r=p(t,["displayName"]);if(e!==void 0&&r!=null&&h(e,["batch","displayName"],r),p(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=p(t,["webhookConfig"]);return e!==void 0&&i!=null&&h(e,["batch","webhookConfig"],i),n}function Sct(t,e){let n={},r=p(t,["displayName"]);e!==void 0&&r!=null&&h(e,["displayName"],r);let i=p(t,["dest"]);if(e!==void 0&&i!=null&&h(e,["outputConfig"],fct(act(i))),p(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 lbe(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["_url","model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["batch","inputConfig"],hct(t,sTe(t,i)));let s=p(e,["config"]);return s!=null&&wct(s,n),n}function xct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["inputConfig"],mct(sTe(t,i)));let s=p(e,["config"]);return s!=null&&Sct(s,n),n}function bct(t,e){let n={},r=p(t,["displayName"]);return e!==void 0&&r!=null&&h(e,["batch","displayName"],r),n}function Tct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["_url","model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["batch","inputConfig"],Oct(t,i));let s=p(e,["config"]);return s!=null&&bct(s,n),n}function Act(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Cct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Rct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["name"]);r!=null&&h(e,["name"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);return s!=null&&h(e,["error"],s),e}function Ict(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["name"]);r!=null&&h(e,["name"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);return s!=null&&h(e,["error"],s),e}function kct(t,e){let n={},r=p(e,["contents"]);if(r!=null){let s=xz(t,r);Array.isArray(s)&&(s=s.map(o=>o)),h(n,["requests[]","request","content"],s)}let i=p(e,["config"]);return i!=null&&(h(n,["_self"],Pct(i,n)),kat(n,{"requests[].*":"requests[].request.*"})),n}function Pct(t,e){let n={},r=p(t,["taskType"]);e!==void 0&&r!=null&&h(e,["requests[]","taskType"],r);let i=p(t,["title"]);e!==void 0&&i!=null&&h(e,["requests[]","title"],i);let s=p(t,["outputDimensionality"]);if(e!==void 0&&s!=null&&h(e,["requests[]","outputDimensionality"],s),p(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(p(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(p(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(p(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 Oct(t,e){let n={},r=p(e,["fileName"]);r!=null&&h(n,["file_name"],r);let i=p(e,["inlinedRequests"]);return i!=null&&h(n,["requests"],kct(t,i)),n}function Mct(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function Nct(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 Dct(t){let e={},n=p(t,["allowedFunctionNames"]);n!=null&&h(e,["allowedFunctionNames"],n);let r=p(t,["mode"]);if(r!=null&&h(e,["mode"],r),p(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 Lct(t,e,n){let r={},i=p(e,["serviceTier"]);n!==void 0&&i!=null&&h(n,["serviceTier"],i);let s=p(e,["systemInstruction"]);n!==void 0&&s!=null&&h(n,["systemInstruction"],cTe(Qr(s)));let o=p(e,["temperature"]);o!=null&&h(r,["temperature"],o);let a=p(e,["topP"]);a!=null&&h(r,["topP"],a);let c=p(e,["topK"]);c!=null&&h(r,["topK"],c);let l=p(e,["candidateCount"]);l!=null&&h(r,["candidateCount"],l);let u=p(e,["maxOutputTokens"]);u!=null&&h(r,["maxOutputTokens"],u);let d=p(e,["stopSequences"]);d!=null&&h(r,["stopSequences"],d);let f=p(e,["responseLogprobs"]);f!=null&&h(r,["responseLogprobs"],f);let m=p(e,["logprobs"]);m!=null&&h(r,["logprobs"],m);let g=p(e,["presencePenalty"]);g!=null&&h(r,["presencePenalty"],g);let y=p(e,["frequencyPenalty"]);y!=null&&h(r,["frequencyPenalty"],y);let w=p(e,["seed"]);w!=null&&h(r,["seed"],w);let S=p(e,["responseMimeType"]);S!=null&&h(r,["responseMimeType"],S);let T=p(e,["responseSchema"]);T!=null&&h(r,["responseSchema"],bz(T));let R=p(e,["responseJsonSchema"]);if(R!=null&&h(r,["responseJsonSchema"],R),p(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(p(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 C=p(e,["safetySettings"]);if(n!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(F=>Qct(F))),h(n,["safetySettings"],P)}let D=p(e,["tools"]);if(n!==void 0&&D!=null){let P=yv(D);Array.isArray(P)&&(P=P.map(F=>elt(gv(F)))),h(n,["tools"],P)}let $=p(e,["toolConfig"]);if(n!==void 0&&$!=null&&h(n,["toolConfig"],Zct($)),p(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=p(e,["cachedContent"]);n!==void 0&&G!=null&&h(n,["cachedContent"],zu(t,G));let V=p(e,["responseModalities"]);V!=null&&h(r,["responseModalities"],V);let L=p(e,["mediaResolution"]);L!=null&&h(r,["mediaResolution"],L);let k=p(e,["speechConfig"]);if(k!=null&&h(r,["speechConfig"],Tz(k)),p(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 E=p(e,["thinkingConfig"]);E!=null&&h(r,["thinkingConfig"],E);let A=p(e,["audioTranscriptionConfig"]);A!=null&&h(r,["audioTranscriptionConfig"],A);let M=p(e,["imageConfig"]);M!=null&&h(r,["imageConfig"],Gct(M));let I=p(e,["enableEnhancedCivicAnswers"]);if(I!=null&&h(r,["enableEnhancedCivicAnswers"],I),p(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Uct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["candidates"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(u=>vct(u))),h(e,["candidates"],l)}let i=p(t,["modelVersion"]);i!=null&&h(e,["modelVersion"],i);let s=p(t,["promptFeedback"]);s!=null&&h(e,["promptFeedback"],s);let o=p(t,["responseId"]);o!=null&&h(e,["responseId"],o);let a=p(t,["usageMetadata"]);a!=null&&h(e,["usageMetadata"],a);let c=p(t,["modelStatus"]);return c!=null&&h(e,["modelStatus"],c),e}function Fct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Bct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function qct(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],lct(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 $ct(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function Gct(t){let e={},n=p(t,["aspectRatio"]);n!=null&&h(e,["aspectRatio"],n);let r=p(t,["imageSize"]);if(r!=null&&h(e,["imageSize"],r),p(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(p(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(p(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(p(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(p(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 Hct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["request","model"],Kt(t,r));let i=p(e,["contents"]);if(i!=null){let a=gs(i);Array.isArray(a)&&(a=a.map(c=>cTe(c))),h(n,["request","contents"],a)}let s=p(e,["metadata"]);s!=null&&h(n,["metadata"],s);let o=p(e,["config"]);return o!=null&&h(n,["request","generationConfig"],Lct(t,o,p(n,["request"],{}))),n}function jct(t){let e={},n=p(t,["response"]);n!=null&&h(e,["response"],Uct(n));let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["error"]);return i!=null&&h(e,["error"],i),e}function Wct(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);if(e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),p(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 Vct(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);e!==void 0&&i!=null&&h(e,["_query","pageToken"],i);let s=p(t,["filter"]);return e!==void 0&&s!=null&&h(e,["_query","filter"],s),n}function zct(t){let e={},n=p(t,["config"]);return n!=null&&Wct(n,e),e}function Kct(t){let e={},n=p(t,["config"]);return n!=null&&Vct(n,e),e}function Yct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["operations"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>EO(o))),h(e,["batchJobs"],s)}return e}function Xct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["batchPredictionJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>_V(o))),h(e,["batchJobs"],s)}return e}function Jct(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],Mct(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],Nct(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],gct(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function Qct(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Zct(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],Dct(n));let r=p(t,["retrievalConfig"]);r!=null&&h(e,["retrievalConfig"],r);let i=p(t,["includeServerSideToolInvocations"]);return i!=null&&h(e,["includeServerSideToolInvocations"],i),e}function elt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],qct(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],$ct(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function tlt(t){let e={},n=p(t,["bigqueryDestination","outputUri"]);n!=null&&h(e,["bigqueryDestination"],n);let r=p(t,["displayName"]);return r!=null&&h(e,["displayName"],r),e}function nlt(t){let e={},n=p(t,["bigqueryDestination"]);n!=null&&h(e,["bigqueryDestination","outputUri"],n);let r=p(t,["displayName"]);return r!=null&&h(e,["displayName"],r),e}function rlt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 ilt(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function slt(t){let e={},n=p(t,["enablePromptInjectionDetection"]);n!=null&&h(e,["enablePromptInjectionDetection"],n);let r=p(t,["environment"]);r!=null&&h(e,["environment"],r);let i=p(t,["excludedPredefinedFunctions"]);if(i!=null&&h(e,["excludedPredefinedFunctions"],i),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function ube(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Rlt(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function dbe(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Ilt(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function olt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);e!==void 0&&i!=null&&h(e,["expireTime"],i);let s=p(t,["displayName"]);e!==void 0&&s!=null&&h(e,["displayName"],s);let o=p(t,["contents"]);if(e!==void 0&&o!=null){let u=gs(o);Array.isArray(u)&&(u=u.map(d=>ube(d))),h(e,["contents"],u)}let a=p(t,["systemInstruction"]);e!==void 0&&a!=null&&h(e,["systemInstruction"],ube(Qr(a)));let c=p(t,["tools"]);if(e!==void 0&&c!=null){let u=c;Array.isArray(u)&&(u=u.map(d=>Olt(d))),h(e,["tools"],u)}let l=p(t,["toolConfig"]);if(e!==void 0&&l!=null&&h(e,["toolConfig"],klt(l)),p(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 alt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);e!==void 0&&i!=null&&h(e,["expireTime"],i);let s=p(t,["displayName"]);e!==void 0&&s!=null&&h(e,["displayName"],s);let o=p(t,["contents"]);if(e!==void 0&&o!=null){let d=gs(o);Array.isArray(d)&&(d=d.map(f=>dbe(f))),h(e,["contents"],d)}let a=p(t,["systemInstruction"]);e!==void 0&&a!=null&&h(e,["systemInstruction"],dbe(Qr(a)));let c=p(t,["tools"]);if(e!==void 0&&c!=null){let d=c;Array.isArray(d)&&(d=d.map(f=>Mlt(f))),h(e,["tools"],d)}let l=p(t,["toolConfig"]);e!==void 0&&l!=null&&h(e,["toolConfig"],Plt(l));let u=p(t,["kmsKeyName"]);return e!==void 0&&u!=null&&h(e,["encryption_spec","kmsKeyName"],u),n}function clt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Ybe(t,r));let i=p(e,["config"]);return i!=null&&olt(i,n),n}function llt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Ybe(t,r));let i=p(e,["config"]);return i!=null&&alt(i,n),n}function ult(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function dlt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function flt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function plt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function hlt(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function mlt(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 glt(t){let e={},n=p(t,["allowedFunctionNames"]);n!=null&&h(e,["allowedFunctionNames"],n);let r=p(t,["mode"]);if(r!=null&&h(e,["mode"],r),p(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 ylt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function _lt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function vlt(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],rlt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 Elt(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function wlt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function Slt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function xlt(t){let e={},n=p(t,["config"]);return n!=null&&wlt(n,e),e}function blt(t){let e={},n=p(t,["config"]);return n!=null&&Slt(n,e),e}function Tlt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["cachedContents"],s)}return e}function Alt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["cachedContents"],s)}return e}function Clt(t){let e={};if(p(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(p(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 Rlt(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],hlt(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],mlt(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],ilt(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function Ilt(t){let e={},n=p(t,["mediaResolution"]);if(n!=null&&h(e,["mediaResolution"],n),p(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(p(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=p(t,["audioTranscription"]);r!=null&&h(e,["audioTranscription"],r);let i=p(t,["codeExecutionResult"]);i!=null&&h(e,["codeExecutionResult"],i);let s=p(t,["executableCode"]);s!=null&&h(e,["executableCode"],s);let o=p(t,["fileData"]);o!=null&&h(e,["fileData"],o);let a=p(t,["functionCall"]);a!=null&&h(e,["functionCall"],a);let c=p(t,["functionResponse"]);c!=null&&h(e,["functionResponse"],c);let l=p(t,["inlineData"]);l!=null&&h(e,["inlineData"],l);let u=p(t,["text"]);u!=null&&h(e,["text"],u);let d=p(t,["thought"]);d!=null&&h(e,["thought"],d);let f=p(t,["thoughtSignature"]);f!=null&&h(e,["thoughtSignature"],f);let m=p(t,["videoMetadata"]);if(m!=null&&h(e,["videoMetadata"],m),p(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=p(t,["mediaProcessing"]);return g!=null&&h(e,["mediaProcessing"],g),e}function klt(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],glt(n));let r=p(t,["retrievalConfig"]);r!=null&&h(e,["retrievalConfig"],r);let i=p(t,["includeServerSideToolInvocations"]);return i!=null&&h(e,["includeServerSideToolInvocations"],i),e}function Plt(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],n);let r=p(t,["retrievalConfig"]);if(r!=null&&h(e,["retrievalConfig"],r),p(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 Olt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],vlt(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],Elt(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function Mlt(t){let e={},n=p(t,["retrieval"]);n!=null&&h(e,["retrieval"],n);let r=p(t,["googleMaps"]);r!=null&&h(e,["googleMaps"],r);let i=p(t,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Clt(y))),h(e,["mcpServers"],g)}let s=p(t,["codeExecution"]);s!=null&&h(e,["codeExecution"],s);let o=p(t,["computerUse"]);o!=null&&h(e,["computerUse"],slt(o));let a=p(t,["enterpriseWebSearch"]);a!=null&&h(e,["enterpriseWebSearch"],a);let c=p(t,["exaAiSearch"]);c!=null&&h(e,["exaAiSearch"],c);let l=p(t,["functionDeclarations"]);if(l!=null){let g=l;Array.isArray(g)&&(g=g.map(y=>y)),h(e,["functionDeclarations"],g)}let u=p(t,["googleSearch"]);u!=null&&h(e,["googleSearch"],u);let d=p(t,["googleSearchRetrieval"]);d!=null&&h(e,["googleSearchRetrieval"],d);let f=p(t,["parallelAiSearch"]);f!=null&&h(e,["parallelAiSearch"],f);let m=p(t,["urlContext"]);if(m!=null&&h(e,["urlContext"],m),p(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 Nlt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);return e!==void 0&&i!=null&&h(e,["expireTime"],i),n}function Dlt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);return e!==void 0&&i!=null&&h(e,["expireTime"],i),n}function Llt(t,e){let n={},r=p(e,["name"]);r!=null&&h(n,["_url","name"],zu(t,r));let i=p(e,["config"]);return i!=null&&Nlt(i,n),n}function Ult(t,e){let n={},r=p(e,["name"]);r!=null&&h(n,["_url","name"],zu(t,r));let i=p(e,["config"]);return i!=null&&Dlt(i,n),n}function Cr(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 fbe(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 Hn(t){return this instanceof Hn?(this.v=t,this):new Hn(t)}function pv(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(m){return function(g){return Promise.resolve(g).then(m,d)}}function a(m,g){r[m]&&(i[m]=function(y){return new Promise(function(w,S){s.push([m,y,w,S])>1||c(m,y)})},g&&(i[m]=g(i[m])))}function c(m,g){try{l(r[m](g))}catch(y){f(s[0][3],y)}}function l(m){m.value instanceof Hn?Promise.resolve(m.value.v).then(u,d):f(s[0][2],m)}function u(m){c("next",m)}function d(m){c("throw",m)}function f(m,g){m(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function VS(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 fbe=="function"?fbe(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Flt(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:lTe(n)}function lTe(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 Blt(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 pbe(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=[],s=!0;for(;r<n&&t[r].role==="model";)i.push(t[r]),s&&!lTe(t[r])&&(s=!1),r++;s?e.push(...i):e.pop()}return e}function qlt(t){let e={},n=p(t,["file"]);return n!=null&&h(e,["file"],n),e}function $lt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function Glt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","file"],Cz(n)),e}function Hlt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function jlt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","file"],Cz(n)),e}function Wlt(t){let e={},n=p(t,["uris"]);return n!=null&&h(e,["uris"],n),e}function Vlt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function zlt(t){let e={},n=p(t,["config"]);return n!=null&&Vlt(n,e),e}function Klt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["files"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["files"],s)}return e}function Ylt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["files"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(e,["files"],i)}return e}function Xlt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 wO(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function Jlt(t){let e={},n=p(t,["enablePromptInjectionDetection"]);n!=null&&h(e,["enablePromptInjectionDetection"],n);let r=p(t,["environment"]);r!=null&&h(e,["environment"],r);let i=p(t,["excludedPredefinedFunctions"]);if(i!=null&&h(e,["excludedPredefinedFunctions"],i),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Qlt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>gut(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function Zlt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>yut(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function eut(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function tut(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 nut(t){let e={},n=p(t,["modelSelectionConfig"]);n!=null&&h(e,["modelConfig"],n);let r=p(t,["responseJsonSchema"]);r!=null&&h(e,["responseJsonSchema"],r);let i=p(t,["audioTranscriptionConfig"]);i!=null&&h(e,["audioTranscriptionConfig"],i);let s=p(t,["audioTimestamp"]);s!=null&&h(e,["audioTimestamp"],s);let o=p(t,["candidateCount"]);o!=null&&h(e,["candidateCount"],o);let a=p(t,["enableAffectiveDialog"]);a!=null&&h(e,["enableAffectiveDialog"],a);let c=p(t,["frequencyPenalty"]);c!=null&&h(e,["frequencyPenalty"],c);let l=p(t,["logprobs"]);l!=null&&h(e,["logprobs"],l);let u=p(t,["maxOutputTokens"]);u!=null&&h(e,["maxOutputTokens"],u);let d=p(t,["mediaResolution"]);d!=null&&h(e,["mediaResolution"],d);let f=p(t,["presencePenalty"]);f!=null&&h(e,["presencePenalty"],f);let m=p(t,["responseFormat"]);if(m!=null){let k=m;Array.isArray(k)&&(k=k.map(E=>E)),h(e,["responseFormat"],k)}let g=p(t,["responseLogprobs"]);g!=null&&h(e,["responseLogprobs"],g);let y=p(t,["responseMimeType"]);y!=null&&h(e,["responseMimeType"],y);let w=p(t,["responseModalities"]);w!=null&&h(e,["responseModalities"],w);let S=p(t,["responseSchema"]);S!=null&&h(e,["responseSchema"],S);let T=p(t,["routingConfig"]);T!=null&&h(e,["routingConfig"],T);let R=p(t,["seed"]);R!=null&&h(e,["seed"],R);let C=p(t,["speechConfig"]);C!=null&&h(e,["speechConfig"],dTe(C));let D=p(t,["stopSequences"]);D!=null&&h(e,["stopSequences"],D);let $=p(t,["temperature"]);$!=null&&h(e,["temperature"],$);let G=p(t,["thinkingConfig"]);G!=null&&h(e,["thinkingConfig"],G);let V=p(t,["topK"]);V!=null&&h(e,["topK"],V);let L=p(t,["topP"]);if(L!=null&&h(e,["topP"],L),p(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(p(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function rut(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],Xlt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 iut(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function sut(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],r);let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],Az(d));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],Qlt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let L=yv(y);Array.isArray(L)&&(L=L.map(k=>Sut(gv(k)))),h(e,["setup","tools"],L)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],Eut(w));let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);if(e!==void 0&&D!=null&&h(e,["setup","proactivity"],D),p(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let $=p(t,["avatarConfig"]);e!==void 0&&$!=null&&h(e,["setup","avatarConfig"],$);let G=p(t,["safetySettings"]);if(e!==void 0&&G!=null){let L=G;Array.isArray(L)&&(L=L.map(k=>vut(k))),h(e,["setup","safetySettings"],L)}let V=p(t,["translationConfig"]);return e!==void 0&&V!=null&&h(e,["setup","generationConfig","translationConfig"],V),n}function out(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],nut(r));let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],dTe(Az(d)));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],Zlt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let k=yv(y);Array.isArray(k)&&(k=k.map(E=>xut(gv(E)))),h(e,["setup","tools"],k)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],w);let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);e!==void 0&&D!=null&&h(e,["setup","proactivity"],D);let $=p(t,["explicitVadSignal"]);e!==void 0&&$!=null&&h(e,["setup","explicitVadSignal"],$);let G=p(t,["avatarConfig"]);e!==void 0&&G!=null&&h(e,["setup","avatarConfig"],G);let V=p(t,["safetySettings"]);if(e!==void 0&&V!=null){let k=V;Array.isArray(k)&&(k=k.map(E=>E)),h(e,["setup","safetySettings"],k)}let L=p(t,["translationConfig"]);return e!==void 0&&L!=null&&h(e,["setup","generationConfig","translationConfig"],L),n}function aut(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],sut(i,n)),n}function cut(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],out(i,n)),n}function lut(t){let e={},n=p(t,["musicGenerationConfig"]);return n!=null&&h(e,["musicGenerationConfig"],n),e}function uut(t){let e={},n=p(t,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),h(e,["weightedPrompts"],r)}return e}function dut(t){let e={},n=p(t,["media"]);if(n!=null){let l=Xbe(n);Array.isArray(l)&&(l=l.map(u=>wO(u))),h(e,["mediaChunks"],l)}let r=p(t,["audio"]);r!=null&&h(e,["audio"],wO(Qbe(r)));let i=p(t,["audioStreamEnd"]);i!=null&&h(e,["audioStreamEnd"],i);let s=p(t,["video"]);s!=null&&h(e,["video"],wO(Jbe(s)));let o=p(t,["text"]);o!=null&&h(e,["text"],o);let a=p(t,["activityStart"]);a!=null&&h(e,["activityStart"],a);let c=p(t,["activityEnd"]);return c!=null&&h(e,["activityEnd"],c),e}function fut(t){let e={},n=p(t,["media"]);if(n!=null){let l=Xbe(n);Array.isArray(l)&&(l=l.map(u=>u)),h(e,["mediaChunks"],l)}let r=p(t,["audio"]);r!=null&&h(e,["audio"],Qbe(r));let i=p(t,["audioStreamEnd"]);i!=null&&h(e,["audioStreamEnd"],i);let s=p(t,["video"]);s!=null&&h(e,["video"],Jbe(s));let o=p(t,["text"]);o!=null&&h(e,["text"],o);let a=p(t,["activityStart"]);a!=null&&h(e,["activityStart"],a);let c=p(t,["activityEnd"]);return c!=null&&h(e,["activityEnd"],c),e}function put(t){let e={},n=p(t,["setupComplete"]);n!=null&&h(e,["setupComplete"],n);let r=p(t,["serverContent"]);r!=null&&h(e,["serverContent"],r);let i=p(t,["toolCall"]);i!=null&&h(e,["toolCall"],i);let s=p(t,["toolCallCancellation"]);s!=null&&h(e,["toolCallCancellation"],s);let o=p(t,["usageMetadata"]);o!=null&&h(e,["usageMetadata"],but(o));let a=p(t,["goAway"]);a!=null&&h(e,["goAway"],a);let c=p(t,["sessionResumptionUpdate"]);c!=null&&h(e,["sessionResumptionUpdate"],c);let l=p(t,["voiceActivityDetectionSignal"]);l!=null&&h(e,["voiceActivityDetectionSignal"],l);let u=p(t,["voiceActivity"]);return u!=null&&h(e,["voiceActivity"],Tut(u)),e}function hut(t){let e={};if(p(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(p(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 mut(t){let e={},n=p(t,["speakerVoiceConfigs"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>wut(i))),h(e,["speakerVoiceConfigs"],r)}return e}function gut(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],eut(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],tut(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],wO(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function yut(t){let e={},n=p(t,["mediaResolution"]);if(n!=null&&h(e,["mediaResolution"],n),p(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(p(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=p(t,["audioTranscription"]);r!=null&&h(e,["audioTranscription"],r);let i=p(t,["codeExecutionResult"]);i!=null&&h(e,["codeExecutionResult"],i);let s=p(t,["executableCode"]);s!=null&&h(e,["executableCode"],s);let o=p(t,["fileData"]);o!=null&&h(e,["fileData"],o);let a=p(t,["functionCall"]);a!=null&&h(e,["functionCall"],a);let c=p(t,["functionResponse"]);c!=null&&h(e,["functionResponse"],c);let l=p(t,["inlineData"]);l!=null&&h(e,["inlineData"],l);let u=p(t,["text"]);u!=null&&h(e,["text"],u);let d=p(t,["thought"]);d!=null&&h(e,["thought"],d);let f=p(t,["thoughtSignature"]);f!=null&&h(e,["thoughtSignature"],f);let m=p(t,["videoMetadata"]);if(m!=null&&h(e,["videoMetadata"],m),p(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=p(t,["mediaProcessing"]);return g!=null&&h(e,["mediaProcessing"],g),e}function _ut(t){let e={},n=p(t,["mimeType"]);n!=null&&h(e,["mimeType"],n);let r=p(t,["voiceSampleAudio"]);if(r!=null&&h(e,["voiceSampleAudio"],r),p(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(p(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 vut(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Eut(t){let e={},n=p(t,["handle"]);if(n!=null&&h(e,["handle"],n),p(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 wut(t){let e={},n=p(t,["speaker"]);n!=null&&h(e,["speaker"],n);let r=p(t,["voiceConfig"]);return r!=null&&h(e,["voiceConfig"],fTe(r)),e}function dTe(t){let e={},n=p(t,["voiceConfig"]);n!=null&&h(e,["voiceConfig"],fTe(n));let r=p(t,["languageCode"]);r!=null&&h(e,["languageCode"],r);let i=p(t,["multiSpeakerVoiceConfig"]);return i!=null&&h(e,["multiSpeakerVoiceConfig"],mut(i)),e}function Sut(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],rut(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],iut(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function xut(t){let e={},n=p(t,["retrieval"]);n!=null&&h(e,["retrieval"],n);let r=p(t,["googleMaps"]);r!=null&&h(e,["googleMaps"],r);let i=p(t,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>hut(y))),h(e,["mcpServers"],g)}let s=p(t,["codeExecution"]);s!=null&&h(e,["codeExecution"],s);let o=p(t,["computerUse"]);o!=null&&h(e,["computerUse"],Jlt(o));let a=p(t,["enterpriseWebSearch"]);a!=null&&h(e,["enterpriseWebSearch"],a);let c=p(t,["exaAiSearch"]);c!=null&&h(e,["exaAiSearch"],c);let l=p(t,["functionDeclarations"]);if(l!=null){let g=l;Array.isArray(g)&&(g=g.map(y=>y)),h(e,["functionDeclarations"],g)}let u=p(t,["googleSearch"]);u!=null&&h(e,["googleSearch"],u);let d=p(t,["googleSearchRetrieval"]);d!=null&&h(e,["googleSearchRetrieval"],d);let f=p(t,["parallelAiSearch"]);f!=null&&h(e,["parallelAiSearch"],f);let m=p(t,["urlContext"]);if(m!=null&&h(e,["urlContext"],m),p(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 but(t){let e={},n=p(t,["candidatesTokenCount"]);n!=null&&h(e,["responseTokenCount"],n);let r=p(t,["candidatesTokensDetails"]);if(r!=null){let m=r;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["responseTokensDetails"],m)}let i=p(t,["cacheTokensDetails"]);if(i!=null){let m=i;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["cacheTokensDetails"],m)}let s=p(t,["cachedContentTokenCount"]);s!=null&&h(e,["cachedContentTokenCount"],s);let o=p(t,["promptTokenCount"]);o!=null&&h(e,["promptTokenCount"],o);let a=p(t,["promptTokensDetails"]);if(a!=null){let m=a;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["promptTokensDetails"],m)}let c=p(t,["thoughtsTokenCount"]);c!=null&&h(e,["thoughtsTokenCount"],c);let l=p(t,["toolUsePromptTokenCount"]);l!=null&&h(e,["toolUsePromptTokenCount"],l);let u=p(t,["toolUsePromptTokensDetails"]);if(u!=null){let m=u;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["toolUsePromptTokensDetails"],m)}let d=p(t,["totalTokenCount"]);d!=null&&h(e,["totalTokenCount"],d);let f=p(t,["trafficType"]);return f!=null&&h(e,["trafficType"],f),e}function Tut(t){let e={},n=p(t,["type"]);n!=null&&h(e,["voiceActivityType"],n);let r=p(t,["audioOffset"]);return r!=null&&h(e,["audioOffset"],r),e}function fTe(t){let e={},n=p(t,["replicatedVoiceConfig"]);n!=null&&h(e,["replicatedVoiceConfig"],_ut(n));let r=p(t,["prebuiltVoiceConfig"]);return r!=null&&h(e,["prebuiltVoiceConfig"],r),e}function Aut(t,e){let n={},r=p(t,["apiKey"]);if(r!=null&&h(n,["apiKey"],r),p(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(p(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(p(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(p(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(p(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(p(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 Cut(t,e){let n={},r=p(t,["data"]);if(r!=null&&h(n,["data"],r),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function Rut(t,e){let n={},r=p(t,["content"]);r!=null&&h(n,["content"],r);let i=p(t,["citationMetadata"]);i!=null&&h(n,["citationMetadata"],Iut(i));let s=p(t,["tokenCount"]);s!=null&&h(n,["tokenCount"],s);let o=p(t,["finishReason"]);o!=null&&h(n,["finishReason"],o);let a=p(t,["groundingMetadata"]);a!=null&&h(n,["groundingMetadata"],a);let c=p(t,["avgLogprobs"]);c!=null&&h(n,["avgLogprobs"],c);let l=p(t,["index"]);l!=null&&h(n,["index"],l);let u=p(t,["logprobsResult"]);u!=null&&h(n,["logprobsResult"],u);let d=p(t,["safetyRatings"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(g=>g)),h(n,["safetyRatings"],m)}let f=p(t,["urlContextMetadata"]);return f!=null&&h(n,["urlContextMetadata"],f),n}function Iut(t,e){let n={},r=p(t,["citationSources"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(n,["citations"],i)}return n}function kut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let o=gs(s);Array.isArray(o)&&(o=o.map(a=>vv(a))),h(r,["contents"],o)}return r}function Put(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["tokensInfo"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["tokensInfo"],s)}return n}function Out(t,e){let n={},r=p(t,["enablePromptInjectionDetection"]);r!=null&&h(n,["enablePromptInjectionDetection"],r);let i=p(t,["environment"]);i!=null&&h(n,["environment"],i);let s=p(t,["excludedPredefinedFunctions"]);if(s!=null&&h(n,["excludedPredefinedFunctions"],s),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Mut(t,e){let n={},r=p(t,["values"]);r!=null&&h(n,["values"],r);let i=p(t,["statistics"]);return i!=null&&h(n,["statistics"],Nut(i)),n}function Nut(t,e){let n={},r=p(t,["truncated"]);r!=null&&h(n,["truncated"],r);let i=p(t,["token_count"]);i!=null&&h(n,["tokenCount"],i);let s=p(t,["tokensDetails"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(a=>a)),h(n,["tokensDetails"],o)}return n}function lx(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Bdt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function vv(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>qdt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function Dut(t,e){let n={},r=p(t,["controlType"]);r!=null&&h(n,["controlType"],r);let i=p(t,["enableControlImageComputation"]);return i!=null&&h(n,["computeControl"],i),n}function Lut(t,e){let n={};if(p(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(p(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(p(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 Uut(t,e,n){let r={},i=p(t,["systemInstruction"]);e!==void 0&&i!=null&&h(e,["systemInstruction"],vv(Qr(i)));let s=p(t,["tools"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>gTe(c))),h(e,["tools"],a)}let o=p(t,["generationConfig"]);return e!==void 0&&o!=null&&h(e,["generationConfig"],xdt(o)),r}function Fut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>lx(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&Lut(o),r}function But(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>vv(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&Uut(o,r),r}function qut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["totalTokens"]);i!=null&&h(n,["totalTokens"],i);let s=p(t,["cachedContentTokenCount"]);return s!=null&&h(n,["cachedContentTokenCount"],s),n}function $ut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["totalTokens"]);return i!=null&&h(n,["totalTokens"],i),n}function Gut(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Hut(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function jut(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function Wut(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function Vut(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["negativePrompt"]);e!==void 0&&s!=null&&h(e,["parameters","negativePrompt"],s);let o=p(t,["numberOfImages"]);e!==void 0&&o!=null&&h(e,["parameters","sampleCount"],o);let a=p(t,["aspectRatio"]);e!==void 0&&a!=null&&h(e,["parameters","aspectRatio"],a);let c=p(t,["guidanceScale"]);e!==void 0&&c!=null&&h(e,["parameters","guidanceScale"],c);let l=p(t,["seed"]);e!==void 0&&l!=null&&h(e,["parameters","seed"],l);let u=p(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&h(e,["parameters","safetySetting"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["includeSafetyAttributes"]);e!==void 0&&f!=null&&h(e,["parameters","includeSafetyAttributes"],f);let m=p(t,["includeRaiReason"]);e!==void 0&&m!=null&&h(e,["parameters","includeRaiReason"],m);let g=p(t,["language"]);e!==void 0&&g!=null&&h(e,["parameters","language"],g);let y=p(t,["outputMimeType"]);e!==void 0&&y!=null&&h(e,["parameters","outputOptions","mimeType"],y);let w=p(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&h(e,["parameters","outputOptions","compressionQuality"],w);let S=p(t,["addWatermark"]);e!==void 0&&S!=null&&h(e,["parameters","addWatermark"],S);let T=p(t,["labels"]);e!==void 0&&T!=null&&h(e,["labels"],T);let R=p(t,["editMode"]);e!==void 0&&R!=null&&h(e,["parameters","editMode"],R);let C=p(t,["baseSteps"]);return e!==void 0&&C!=null&&h(e,["parameters","editConfig","baseSteps"],C),r}function zut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["referenceImages"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(l=>Vdt(l))),h(r,["instances[0]","referenceImages"],c)}let a=p(e,["config"]);return a!=null&&Vut(a,r),r}function Kut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o1(o))),h(n,["generatedImages"],s)}return n}function Yut(t,e,n){let r={},i=p(t,["taskType"]);e!==void 0&&i!=null&&h(e,["requests[]","taskType"],i);let s=p(t,["title"]);e!==void 0&&s!=null&&h(e,["requests[]","title"],s);let o=p(t,["outputDimensionality"]);if(e!==void 0&&o!=null&&h(e,["requests[]","outputDimensionality"],o),p(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(p(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(p(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(p(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 Xut(t,e,n){let r={},i=p(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let d=p(t,["taskType"]);e!==void 0&&d!=null&&h(e,["instances[]","task_type"],d)}else if(i==="EMBED_CONTENT"){let d=p(t,["taskType"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","taskType"],d)}let s=p(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let d=p(t,["title"]);e!==void 0&&d!=null&&h(e,["instances[]","title"],d)}else if(s==="EMBED_CONTENT"){let d=p(t,["title"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","title"],d)}let o=p(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let d=p(t,["outputDimensionality"]);e!==void 0&&d!=null&&h(e,["parameters","outputDimensionality"],d)}else if(o==="EMBED_CONTENT"){let d=p(t,["outputDimensionality"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","outputDimensionality"],d)}let a=p(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let d=p(t,["mimeType"]);e!==void 0&&d!=null&&h(e,["instances[]","mimeType"],d)}let c=p(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let d=p(t,["autoTruncate"]);e!==void 0&&d!=null&&h(e,["parameters","autoTruncate"],d)}else if(c==="EMBED_CONTENT"){let d=p(t,["autoTruncate"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","autoTruncate"],d)}let l=p(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="EMBED_CONTENT"){let d=p(t,["documentOcr"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","documentOcr"],d)}let u=p(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="EMBED_CONTENT"){let d=p(t,["audioTrackExtraction"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","audioTrackExtraction"],d)}return r}function Jut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let l=xz(t,s);Array.isArray(l)&&(l=l.map(u=>u)),h(r,["requests[]","content"],l)}let o=p(e,["content"]);o!=null&&lx(Qr(o));let a=p(e,["config"]);a!=null&&Yut(a,r);let c=p(e,["model"]);return c!==void 0&&h(r,["requests[]","model"],Kt(t,c)),r}function Qut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let c=p(e,["contents"]);if(c!=null){let l=xz(t,c);Array.isArray(l)&&(l=l.map(u=>u)),h(r,["instances[]","content"],l)}}let o=p(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="EMBED_CONTENT"){let c=p(e,["content"]);c!=null&&h(r,["content"],vv(Qr(c)))}let a=p(e,["config"]);return a!=null&&Xut(a,r,n),r}function Zut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),h(n,["embeddings"],o)}let s=p(t,["metadata"]);return s!=null&&h(n,["metadata"],s),n}function edt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions[]","embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>Mut(a))),h(n,["embeddings"],o)}let s=p(t,["metadata"]);if(s!=null&&h(n,["metadata"],s),e&&p(e,["embeddingApiType"])==="EMBED_CONTENT"){let o=p(t,["embedding"]),a=p(t,["usageMetadata"]),c=p(t,["truncated"]);if(o){let l={};a&&a.promptTokenCount&&(l.tokenCount=a.promptTokenCount),a&&a.promptTokensDetails&&(l.tokensDetails=a.promptTokensDetails),c&&(l.truncated=c),o.statistics=l,h(n,["embeddings"],[o])}}return n}function tdt(t,e){let n={},r=p(t,["endpoint"]);r!=null&&h(n,["name"],r);let i=p(t,["deployedModelId"]);return i!=null&&h(n,["deployedModelId"],i),n}function ndt(t,e){let n={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["fileUri"]);r!=null&&h(n,["fileUri"],r);let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function rdt(t,e){let n={},r=p(t,["args"]);r!=null&&h(n,["args"],r);let i=p(t,["id"]);i!=null&&h(n,["id"],i);let s=p(t,["name"]);if(s!=null&&h(n,["name"],s),p(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(p(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 idt(t,e){let n={},r=p(t,["allowedFunctionNames"]);r!=null&&h(n,["allowedFunctionNames"],r);let i=p(t,["mode"]);if(i!=null&&h(n,["mode"],i),p(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 sdt(t,e,n,r){let i={},s=p(e,["serviceTier"]);n!==void 0&&s!=null&&h(n,["serviceTier"],s);let o=p(e,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],lx(Qr(o)));let a=p(e,["temperature"]);a!=null&&h(i,["temperature"],a);let c=p(e,["topP"]);c!=null&&h(i,["topP"],c);let l=p(e,["topK"]);l!=null&&h(i,["topK"],l);let u=p(e,["candidateCount"]);u!=null&&h(i,["candidateCount"],u);let d=p(e,["maxOutputTokens"]);d!=null&&h(i,["maxOutputTokens"],d);let f=p(e,["stopSequences"]);f!=null&&h(i,["stopSequences"],f);let m=p(e,["responseLogprobs"]);m!=null&&h(i,["responseLogprobs"],m);let g=p(e,["logprobs"]);g!=null&&h(i,["logprobs"],g);let y=p(e,["presencePenalty"]);y!=null&&h(i,["presencePenalty"],y);let w=p(e,["frequencyPenalty"]);w!=null&&h(i,["frequencyPenalty"],w);let S=p(e,["seed"]);S!=null&&h(i,["seed"],S);let T=p(e,["responseMimeType"]);T!=null&&h(i,["responseMimeType"],T);let R=p(e,["responseSchema"]);R!=null&&h(i,["responseSchema"],bz(R));let C=p(e,["responseJsonSchema"]);if(C!=null&&h(i,["responseJsonSchema"],C),p(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(p(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 D=p(e,["safetySettings"]);if(n!==void 0&&D!=null){let F=D;Array.isArray(F)&&(F=F.map(X=>Kdt(X))),h(n,["safetySettings"],F)}let $=p(e,["tools"]);if(n!==void 0&&$!=null){let F=yv($);Array.isArray(F)&&(F=F.map(X=>rft(gv(X)))),h(n,["tools"],F)}let G=p(e,["toolConfig"]);if(n!==void 0&&G!=null&&h(n,["toolConfig"],tft(G)),p(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let V=p(e,["cachedContent"]);n!==void 0&&V!=null&&h(n,["cachedContent"],zu(t,V));let L=p(e,["responseModalities"]);L!=null&&h(i,["responseModalities"],L);let k=p(e,["mediaResolution"]);k!=null&&h(i,["mediaResolution"],k);let E=p(e,["speechConfig"]);if(E!=null&&h(i,["speechConfig"],Tz(E)),p(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 A=p(e,["thinkingConfig"]);A!=null&&h(i,["thinkingConfig"],A);let M=p(e,["audioTranscriptionConfig"]);M!=null&&h(i,["audioTranscriptionConfig"],M);let I=p(e,["imageConfig"]);I!=null&&h(i,["imageConfig"],Rdt(I));let P=p(e,["enableEnhancedCivicAnswers"]);if(P!=null&&h(i,["enableEnhancedCivicAnswers"],P),p(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function odt(t,e,n,r){let i={},s=p(e,["serviceTier"]);n!==void 0&&s!=null&&h(n,["serviceTier"],s);let o=p(e,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],vv(Qr(o)));let a=p(e,["temperature"]);a!=null&&h(i,["temperature"],a);let c=p(e,["topP"]);c!=null&&h(i,["topP"],c);let l=p(e,["topK"]);l!=null&&h(i,["topK"],l);let u=p(e,["candidateCount"]);u!=null&&h(i,["candidateCount"],u);let d=p(e,["maxOutputTokens"]);d!=null&&h(i,["maxOutputTokens"],d);let f=p(e,["stopSequences"]);f!=null&&h(i,["stopSequences"],f);let m=p(e,["responseLogprobs"]);m!=null&&h(i,["responseLogprobs"],m);let g=p(e,["logprobs"]);g!=null&&h(i,["logprobs"],g);let y=p(e,["presencePenalty"]);y!=null&&h(i,["presencePenalty"],y);let w=p(e,["frequencyPenalty"]);w!=null&&h(i,["frequencyPenalty"],w);let S=p(e,["seed"]);S!=null&&h(i,["seed"],S);let T=p(e,["responseMimeType"]);T!=null&&h(i,["responseMimeType"],T);let R=p(e,["responseSchema"]);R!=null&&h(i,["responseSchema"],bz(R));let C=p(e,["responseJsonSchema"]);C!=null&&h(i,["responseJsonSchema"],C);let D=p(e,["routingConfig"]);D!=null&&h(i,["routingConfig"],D);let $=p(e,["modelSelectionConfig"]);$!=null&&h(i,["modelConfig"],$);let G=p(e,["safetySettings"]);if(n!==void 0&&G!=null){let q=G;Array.isArray(q)&&(q=q.map(pe=>pe)),h(n,["safetySettings"],q)}let V=p(e,["tools"]);if(n!==void 0&&V!=null){let q=yv(V);Array.isArray(q)&&(q=q.map(pe=>gTe(gv(pe)))),h(n,["tools"],q)}let L=p(e,["toolConfig"]);n!==void 0&&L!=null&&h(n,["toolConfig"],nft(L));let k=p(e,["labels"]);n!==void 0&&k!=null&&h(n,["labels"],k);let E=p(e,["cachedContent"]);n!==void 0&&E!=null&&h(n,["cachedContent"],zu(t,E));let A=p(e,["responseModalities"]);A!=null&&h(i,["responseModalities"],A);let M=p(e,["mediaResolution"]);M!=null&&h(i,["mediaResolution"],M);let I=p(e,["speechConfig"]);I!=null&&h(i,["speechConfig"],mTe(Tz(I)));let P=p(e,["audioTimestamp"]);P!=null&&h(i,["audioTimestamp"],P);let F=p(e,["thinkingConfig"]);F!=null&&h(i,["thinkingConfig"],F);let X=p(e,["audioTranscriptionConfig"]);X!=null&&h(i,["audioTranscriptionConfig"],X);let N=p(e,["imageConfig"]);if(N!=null&&h(i,["imageConfig"],Idt(N)),p(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 b=p(e,["modelArmorConfig"]);return n!==void 0&&b!=null&&h(n,["modelArmorConfig"],b),i}function hbe(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>lx(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&h(r,["generationConfig"],sdt(t,o,r)),r}function mbe(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>vv(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&h(r,["generationConfig"],odt(t,o,r)),r}function gbe(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(d=>Rut(d))),h(n,["candidates"],u)}let s=p(t,["modelVersion"]);s!=null&&h(n,["modelVersion"],s);let o=p(t,["promptFeedback"]);o!=null&&h(n,["promptFeedback"],o);let a=p(t,["responseId"]);a!=null&&h(n,["responseId"],a);let c=p(t,["usageMetadata"]);c!=null&&h(n,["usageMetadata"],c);let l=p(t,["modelStatus"]);return l!=null&&h(n,["modelStatus"],l),n}function ybe(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(d=>d)),h(n,["candidates"],u)}let s=p(t,["createTime"]);s!=null&&h(n,["createTime"],s);let o=p(t,["modelVersion"]);o!=null&&h(n,["modelVersion"],o);let a=p(t,["promptFeedback"]);a!=null&&h(n,["promptFeedback"],a);let c=p(t,["responseId"]);c!=null&&h(n,["responseId"],c);let l=p(t,["usageMetadata"]);return l!=null&&h(n,["usageMetadata"],l),n}function adt(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["negativePrompt"]);e!==void 0&&s!=null&&h(e,["parameters","negativePrompt"],s);let o=p(t,["numberOfImages"]);e!==void 0&&o!=null&&h(e,["parameters","sampleCount"],o);let a=p(t,["aspectRatio"]);e!==void 0&&a!=null&&h(e,["parameters","aspectRatio"],a);let c=p(t,["guidanceScale"]);e!==void 0&&c!=null&&h(e,["parameters","guidanceScale"],c);let l=p(t,["seed"]);e!==void 0&&l!=null&&h(e,["parameters","seed"],l);let u=p(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&h(e,["parameters","safetySetting"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["includeSafetyAttributes"]);e!==void 0&&f!=null&&h(e,["parameters","includeSafetyAttributes"],f);let m=p(t,["includeRaiReason"]);e!==void 0&&m!=null&&h(e,["parameters","includeRaiReason"],m);let g=p(t,["language"]);e!==void 0&&g!=null&&h(e,["parameters","language"],g);let y=p(t,["outputMimeType"]);e!==void 0&&y!=null&&h(e,["parameters","outputOptions","mimeType"],y);let w=p(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&h(e,["parameters","outputOptions","compressionQuality"],w);let S=p(t,["addWatermark"]);e!==void 0&&S!=null&&h(e,["parameters","addWatermark"],S);let T=p(t,["labels"]);e!==void 0&&T!=null&&h(e,["labels"],T);let R=p(t,["imageSize"]);e!==void 0&&R!=null&&h(e,["parameters","sampleImageSize"],R);let C=p(t,["enhancePrompt"]);return e!==void 0&&C!=null&&h(e,["parameters","enhancePrompt"],C),r}function cdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["config"]);return o!=null&&adt(o,r),r}function ldt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>o1(a))),h(n,["generatedImages"],o)}let s=p(t,["positivePromptSafetyAttributes"]);return s!=null&&h(n,["positivePromptSafetyAttributes"],hTe(s)),n}function udt(t,e,n){let r={},i=p(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i),p(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=p(t,["durationSeconds"]);if(e!==void 0&&s!=null&&h(e,["parameters","durationSeconds"],s),p(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=p(t,["aspectRatio"]);e!==void 0&&o!=null&&h(e,["parameters","aspectRatio"],o);let a=p(t,["resolution"]);e!==void 0&&a!=null&&h(e,["parameters","resolution"],a);let c=p(t,["personGeneration"]);if(e!==void 0&&c!=null&&h(e,["parameters","personGeneration"],c),p(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let l=p(t,["negativePrompt"]);e!==void 0&&l!=null&&h(e,["parameters","negativePrompt"],l);let u=p(t,["enhancePrompt"]);if(e!==void 0&&u!=null&&h(e,["parameters","enhancePrompt"],u),p(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=p(t,["lastFrame"]);e!==void 0&&d!=null&&h(e,["instances[0]","lastFrame"],a1(d));let f=p(t,["referenceImages"]);if(e!==void 0&&f!=null){let g=f;Array.isArray(g)&&(g=g.map(y=>gft(y))),h(e,["instances[0]","referenceImages"],g)}if(p(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=p(t,["webhookConfig"]);if(e!==void 0&&m!=null&&h(e,["webhookConfig"],m),p(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function ddt(t,e,n){let r={},i=p(t,["numberOfVideos"]);e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i);let s=p(t,["outputGcsUri"]);e!==void 0&&s!=null&&h(e,["parameters","storageUri"],s);let o=p(t,["fps"]);e!==void 0&&o!=null&&h(e,["parameters","fps"],o);let a=p(t,["durationSeconds"]);e!==void 0&&a!=null&&h(e,["parameters","durationSeconds"],a);let c=p(t,["seed"]);e!==void 0&&c!=null&&h(e,["parameters","seed"],c);let l=p(t,["aspectRatio"]);e!==void 0&&l!=null&&h(e,["parameters","aspectRatio"],l);let u=p(t,["resolution"]);e!==void 0&&u!=null&&h(e,["parameters","resolution"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["pubsubTopic"]);e!==void 0&&f!=null&&h(e,["parameters","pubsubTopic"],f);let m=p(t,["negativePrompt"]);e!==void 0&&m!=null&&h(e,["parameters","negativePrompt"],m);let g=p(t,["enhancePrompt"]);e!==void 0&&g!=null&&h(e,["parameters","enhancePrompt"],g);let y=p(t,["generateAudio"]);e!==void 0&&y!=null&&h(e,["parameters","generateAudio"],y);let w=p(t,["lastFrame"]);e!==void 0&&w!=null&&h(e,["instances[0]","lastFrame"],oc(w));let S=p(t,["referenceImages"]);if(e!==void 0&&S!=null){let $=S;Array.isArray($)&&($=$.map(G=>yft(G))),h(e,["instances[0]","referenceImages"],$)}let T=p(t,["mask"]);e!==void 0&&T!=null&&h(e,["instances[0]","mask"],mft(T));let R=p(t,["compressionQuality"]);e!==void 0&&R!=null&&h(e,["parameters","compressionQuality"],R);let C=p(t,["labels"]);if(e!==void 0&&C!=null&&h(e,["labels"],C),p(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 D=p(t,["resizeMode"]);return e!==void 0&&D!=null&&h(e,["parameters","resizeMode"],D),r}function fdt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["metadata"]);i!=null&&h(n,["metadata"],i);let s=p(t,["done"]);s!=null&&h(n,["done"],s);let o=p(t,["error"]);o!=null&&h(n,["error"],o);let a=p(t,["response","generateVideoResponse"]);return a!=null&&h(n,["response"],gdt(a)),n}function pdt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["metadata"]);i!=null&&h(n,["metadata"],i);let s=p(t,["done"]);s!=null&&h(n,["done"],s);let o=p(t,["error"]);o!=null&&h(n,["error"],o);let a=p(t,["response"]);return a!=null&&h(n,["response"],ydt(a)),n}function hdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["image"]);o!=null&&h(r,["instances[0]","image"],a1(o));let a=p(e,["video"]);a!=null&&h(r,["instances[0]","video"],yTe(a));let c=p(e,["source"]);c!=null&&_dt(c,r);let l=p(e,["config"]);return l!=null&&udt(l,r),r}function mdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["image"]);o!=null&&h(r,["instances[0]","image"],oc(o));let a=p(e,["video"]);a!=null&&h(r,["instances[0]","video"],_Te(a));let c=p(e,["source"]);c!=null&&vdt(c,r);let l=p(e,["config"]);return l!=null&&ddt(l,r),r}function gdt(t,e){let n={},r=p(t,["generatedSamples"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>wdt(a))),h(n,["generatedVideos"],o)}let i=p(t,["raiMediaFilteredCount"]);i!=null&&h(n,["raiMediaFilteredCount"],i);let s=p(t,["raiMediaFilteredReasons"]);return s!=null&&h(n,["raiMediaFilteredReasons"],s),n}function ydt(t,e){let n={},r=p(t,["videos"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>Sdt(a))),h(n,["generatedVideos"],o)}let i=p(t,["raiMediaFilteredCount"]);i!=null&&h(n,["raiMediaFilteredCount"],i);let s=p(t,["raiMediaFilteredReasons"]);return s!=null&&h(n,["raiMediaFilteredReasons"],s),n}function _dt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],a1(s));let o=p(t,["video"]);return e!==void 0&&o!=null&&h(e,["instances[0]","video"],yTe(o)),r}function vdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],oc(s));let o=p(t,["video"]);return e!==void 0&&o!=null&&h(e,["instances[0]","video"],_Te(o)),r}function o1(t,e){let n={},r=p(t,["_self"]);r!=null&&h(n,["image"],pTe(r));let i=p(t,["raiFilteredReason"]);i!=null&&h(n,["raiFilteredReason"],i);let s=p(t,["_self"]);s!=null&&h(n,["safetyAttributes"],hTe(s));let o=p(t,["prompt"]);return o!=null&&h(n,["enhancedPrompt"],o),n}function Edt(t,e){let n={},r=p(t,["_self"]);r!=null&&h(n,["mask"],pTe(r));let i=p(t,["labels"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["labels"],s)}return n}function wdt(t,e){let n={},r=p(t,["video"]);return r!=null&&h(n,["video"],pft(r)),n}function Sdt(t,e){let n={},r=p(t,["_self"]);return r!=null&&h(n,["video"],hft(r)),n}function xdt(t,e){let n={},r=p(t,["modelSelectionConfig"]);r!=null&&h(n,["modelConfig"],r);let i=p(t,["responseJsonSchema"]);i!=null&&h(n,["responseJsonSchema"],i);let s=p(t,["audioTranscriptionConfig"]);s!=null&&h(n,["audioTranscriptionConfig"],s);let o=p(t,["audioTimestamp"]);o!=null&&h(n,["audioTimestamp"],o);let a=p(t,["candidateCount"]);a!=null&&h(n,["candidateCount"],a);let c=p(t,["enableAffectiveDialog"]);c!=null&&h(n,["enableAffectiveDialog"],c);let l=p(t,["frequencyPenalty"]);l!=null&&h(n,["frequencyPenalty"],l);let u=p(t,["logprobs"]);u!=null&&h(n,["logprobs"],u);let d=p(t,["maxOutputTokens"]);d!=null&&h(n,["maxOutputTokens"],d);let f=p(t,["mediaResolution"]);f!=null&&h(n,["mediaResolution"],f);let m=p(t,["presencePenalty"]);m!=null&&h(n,["presencePenalty"],m);let g=p(t,["responseFormat"]);if(g!=null){let E=g;Array.isArray(E)&&(E=E.map(A=>A)),h(n,["responseFormat"],E)}let y=p(t,["responseLogprobs"]);y!=null&&h(n,["responseLogprobs"],y);let w=p(t,["responseMimeType"]);w!=null&&h(n,["responseMimeType"],w);let S=p(t,["responseModalities"]);S!=null&&h(n,["responseModalities"],S);let T=p(t,["responseSchema"]);T!=null&&h(n,["responseSchema"],T);let R=p(t,["routingConfig"]);R!=null&&h(n,["routingConfig"],R);let C=p(t,["seed"]);C!=null&&h(n,["seed"],C);let D=p(t,["speechConfig"]);D!=null&&h(n,["speechConfig"],mTe(D));let $=p(t,["stopSequences"]);$!=null&&h(n,["stopSequences"],$);let G=p(t,["temperature"]);G!=null&&h(n,["temperature"],G);let V=p(t,["thinkingConfig"]);V!=null&&h(n,["thinkingConfig"],V);let L=p(t,["topK"]);L!=null&&h(n,["topK"],L);let k=p(t,["topP"]);if(k!=null&&h(n,["topP"],k),p(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(p(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bdt(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Tdt(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Adt(t,e){let n={},r=p(t,["authConfig"]);r!=null&&h(n,["authConfig"],Aut(r));let i=p(t,["enableWidget"]);if(i!=null&&h(n,["enableWidget"],i),p(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 Cdt(t,e){let n={};if(p(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(p(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=p(t,["searchTypes"]);r!=null&&h(n,["searchTypes"],r);let i=p(t,["timeRangeFilter"]);return i!=null&&h(n,["timeRangeFilter"],i),n}function Rdt(t,e){let n={},r=p(t,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);let i=p(t,["imageSize"]);if(i!=null&&h(n,["imageSize"],i),p(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(p(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(p(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(p(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(p(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 Idt(t,e){let n={},r=p(t,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);let i=p(t,["imageSize"]);i!=null&&h(n,["imageSize"],i);let s=p(t,["personGeneration"]);s!=null&&h(n,["personGeneration"],s);let o=p(t,["outputMimeType"]);o!=null&&h(n,["imageOutputOptions","mimeType"],o);let a=p(t,["outputCompressionQuality"]);a!=null&&h(n,["imageOutputOptions","compressionQuality"],a);let c=p(t,["imageOutputOptions"]);c!=null&&h(n,["imageOutputOptions"],c);let l=p(t,["prominentPeople"]);return l!=null&&h(n,["prominentPeople"],l),n}function pTe(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["bytesBase64Encoded"]);i!=null&&h(n,["imageBytes"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function a1(t,e){let n={};if(p(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["imageBytes"]);r!=null&&h(n,["bytesBase64Encoded"],vm(r));let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function oc(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["imageBytes"]);i!=null&&h(n,["bytesBase64Encoded"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function kdt(t,e,n,r){let i={},s=p(e,["pageSize"]);n!==void 0&&s!=null&&h(n,["_query","pageSize"],s);let o=p(e,["pageToken"]);n!==void 0&&o!=null&&h(n,["_query","pageToken"],o);let a=p(e,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);let c=p(e,["queryBase"]);return n!==void 0&&c!=null&&h(n,["_url","models_url"],rTe(t,c)),i}function Pdt(t,e,n,r){let i={},s=p(e,["pageSize"]);n!==void 0&&s!=null&&h(n,["_query","pageSize"],s);let o=p(e,["pageToken"]);n!==void 0&&o!=null&&h(n,["_query","pageToken"],o);let a=p(e,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);let c=p(e,["queryBase"]);return n!==void 0&&c!=null&&h(n,["_url","models_url"],rTe(t,c)),i}function Odt(t,e,n){let r={},i=p(e,["config"]);return i!=null&&kdt(t,i,r),r}function Mdt(t,e,n){let r={},i=p(e,["config"]);return i!=null&&Pdt(t,i,r),r}function Ndt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["_self"]);if(s!=null){let o=iTe(s);Array.isArray(o)&&(o=o.map(a=>vV(a))),h(n,["models"],o)}return n}function Ddt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["_self"]);if(s!=null){let o=iTe(s);Array.isArray(o)&&(o=o.map(a=>EV(a))),h(n,["models"],o)}return n}function Ldt(t,e){let n={},r=p(t,["maskMode"]);r!=null&&h(n,["maskMode"],r);let i=p(t,["segmentationClasses"]);i!=null&&h(n,["maskClasses"],i);let s=p(t,["maskDilation"]);return s!=null&&h(n,["dilation"],s),n}function Udt(t,e){let n={};if(p(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(p(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 vV(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["displayName"]);i!=null&&h(n,["displayName"],i);let s=p(t,["description"]);s!=null&&h(n,["description"],s);let o=p(t,["version"]);o!=null&&h(n,["version"],o);let a=p(t,["_self"]);a!=null&&h(n,["tunedModelInfo"],ift(a));let c=p(t,["inputTokenLimit"]);c!=null&&h(n,["inputTokenLimit"],c);let l=p(t,["outputTokenLimit"]);l!=null&&h(n,["outputTokenLimit"],l);let u=p(t,["supportedGenerationMethods"]);u!=null&&h(n,["supportedActions"],u);let d=p(t,["temperature"]);d!=null&&h(n,["temperature"],d);let f=p(t,["maxTemperature"]);f!=null&&h(n,["maxTemperature"],f);let m=p(t,["topP"]);m!=null&&h(n,["topP"],m);let g=p(t,["topK"]);g!=null&&h(n,["topK"],g);let y=p(t,["thinking"]);return y!=null&&h(n,["thinking"],y),n}function EV(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["displayName"]);i!=null&&h(n,["displayName"],i);let s=p(t,["description"]);s!=null&&h(n,["description"],s);let o=p(t,["versionId"]);o!=null&&h(n,["version"],o);let a=p(t,["deployedModels"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(m=>tdt(m))),h(n,["endpoints"],f)}let c=p(t,["labels"]);c!=null&&h(n,["labels"],c);let l=p(t,["_self"]);l!=null&&h(n,["tunedModelInfo"],sft(l));let u=p(t,["defaultCheckpointId"]);u!=null&&h(n,["defaultCheckpointId"],u);let d=p(t,["checkpoints"]);if(d!=null){let f=d;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["checkpoints"],f)}return n}function Fdt(t,e){let n={},r=p(t,["speakerVoiceConfigs"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>eft(s))),h(n,["speakerVoiceConfigs"],i)}return n}function Bdt(t,e){let n={},r=p(t,["mediaResolution"]);r!=null&&h(n,["mediaResolution"],r);let i=p(t,["toolCall"]);i!=null&&h(n,["toolCall"],i);let s=p(t,["toolResponse"]);s!=null&&h(n,["toolResponse"],s);let o=p(t,["audioTranscription"]);o!=null&&h(n,["audioTranscription"],o);let a=p(t,["codeExecutionResult"]);a!=null&&h(n,["codeExecutionResult"],a);let c=p(t,["executableCode"]);c!=null&&h(n,["executableCode"],c);let l=p(t,["fileData"]);l!=null&&h(n,["fileData"],ndt(l));let u=p(t,["functionCall"]);u!=null&&h(n,["functionCall"],rdt(u));let d=p(t,["functionResponse"]);d!=null&&h(n,["functionResponse"],d);let f=p(t,["inlineData"]);f!=null&&h(n,["inlineData"],Cut(f));let m=p(t,["text"]);m!=null&&h(n,["text"],m);let g=p(t,["thought"]);g!=null&&h(n,["thought"],g);let y=p(t,["thoughtSignature"]);y!=null&&h(n,["thoughtSignature"],y);let w=p(t,["videoMetadata"]);w!=null&&h(n,["videoMetadata"],w);let S=p(t,["partMetadata"]);S!=null&&h(n,["partMetadata"],S);let T=p(t,["mediaProcessing"]);return T!=null&&h(n,["mediaProcessing"],T),n}function qdt(t,e){let n={},r=p(t,["mediaResolution"]);if(r!=null&&h(n,["mediaResolution"],r),p(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(p(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=p(t,["audioTranscription"]);i!=null&&h(n,["audioTranscription"],i);let s=p(t,["codeExecutionResult"]);s!=null&&h(n,["codeExecutionResult"],s);let o=p(t,["executableCode"]);o!=null&&h(n,["executableCode"],o);let a=p(t,["fileData"]);a!=null&&h(n,["fileData"],a);let c=p(t,["functionCall"]);c!=null&&h(n,["functionCall"],c);let l=p(t,["functionResponse"]);l!=null&&h(n,["functionResponse"],l);let u=p(t,["inlineData"]);u!=null&&h(n,["inlineData"],u);let d=p(t,["text"]);d!=null&&h(n,["text"],d);let f=p(t,["thought"]);f!=null&&h(n,["thought"],f);let m=p(t,["thoughtSignature"]);m!=null&&h(n,["thoughtSignature"],m);let g=p(t,["videoMetadata"]);if(g!=null&&h(n,["videoMetadata"],g),p(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 y=p(t,["mediaProcessing"]);return y!=null&&h(n,["mediaProcessing"],y),n}function $dt(t,e){let n={},r=p(t,["productImage"]);return r!=null&&h(n,["image"],oc(r)),n}function Gdt(t,e,n){let r={},i=p(t,["numberOfImages"]);e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i);let s=p(t,["baseSteps"]);e!==void 0&&s!=null&&h(e,["parameters","baseSteps"],s);let o=p(t,["outputGcsUri"]);e!==void 0&&o!=null&&h(e,["parameters","storageUri"],o);let a=p(t,["seed"]);e!==void 0&&a!=null&&h(e,["parameters","seed"],a);let c=p(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&h(e,["parameters","safetySetting"],c);let l=p(t,["personGeneration"]);e!==void 0&&l!=null&&h(e,["parameters","personGeneration"],l);let u=p(t,["addWatermark"]);e!==void 0&&u!=null&&h(e,["parameters","addWatermark"],u);let d=p(t,["outputMimeType"]);e!==void 0&&d!=null&&h(e,["parameters","outputOptions","mimeType"],d);let f=p(t,["outputCompressionQuality"]);e!==void 0&&f!=null&&h(e,["parameters","outputOptions","compressionQuality"],f);let m=p(t,["enhancePrompt"]);e!==void 0&&m!=null&&h(e,["parameters","enhancePrompt"],m);let g=p(t,["labels"]);return e!==void 0&&g!=null&&h(e,["labels"],g),r}function Hdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["source"]);s!=null&&Wdt(s,r);let o=p(e,["config"]);return o!=null&&Gdt(o,r),r}function jdt(t,e){let n={},r=p(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>o1(s))),h(n,["generatedImages"],i)}return n}function Wdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["personImage"]);e!==void 0&&s!=null&&h(e,["instances[0]","personImage","image"],oc(s));let o=p(t,["productImages"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(c=>$dt(c))),h(e,["instances[0]","productImages"],a)}return r}function Vdt(t,e){let n={},r=p(t,["referenceImage"]);r!=null&&h(n,["referenceImage"],oc(r));let i=p(t,["referenceId"]);i!=null&&h(n,["referenceId"],i);let s=p(t,["referenceType"]);s!=null&&h(n,["referenceType"],s);let o=p(t,["maskImageConfig"]);o!=null&&h(n,["maskImageConfig"],Ldt(o));let a=p(t,["controlImageConfig"]);a!=null&&h(n,["controlImageConfig"],Dut(a));let c=p(t,["styleImageConfig"]);c!=null&&h(n,["styleImageConfig"],c);let l=p(t,["subjectImageConfig"]);return l!=null&&h(n,["subjectImageConfig"],l),n}function zdt(t,e){let n={},r=p(t,["mimeType"]);r!=null&&h(n,["mimeType"],r);let i=p(t,["voiceSampleAudio"]);if(i!=null&&h(n,["voiceSampleAudio"],i),p(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(p(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 hTe(t,e){let n={},r=p(t,["safetyAttributes","categories"]);r!=null&&h(n,["categories"],r);let i=p(t,["safetyAttributes","scores"]);i!=null&&h(n,["scores"],i);let s=p(t,["contentType"]);return s!=null&&h(n,["contentType"],s),n}function Kdt(t,e){let n={},r=p(t,["category"]);if(r!=null&&h(n,["category"],r),p(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=p(t,["threshold"]);return i!=null&&h(n,["threshold"],i),n}function Ydt(t,e){let n={},r=p(t,["image"]);return r!=null&&h(n,["image"],oc(r)),n}function Xdt(t,e,n){let r={},i=p(t,["mode"]);e!==void 0&&i!=null&&h(e,["parameters","mode"],i);let s=p(t,["maxPredictions"]);e!==void 0&&s!=null&&h(e,["parameters","maxPredictions"],s);let o=p(t,["confidenceThreshold"]);e!==void 0&&o!=null&&h(e,["parameters","confidenceThreshold"],o);let a=p(t,["maskDilation"]);e!==void 0&&a!=null&&h(e,["parameters","maskDilation"],a);let c=p(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&h(e,["parameters","binaryColorThreshold"],c);let l=p(t,["labels"]);return e!==void 0&&l!=null&&h(e,["labels"],l),r}function Jdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["source"]);s!=null&&Zdt(s,r);let o=p(e,["config"]);return o!=null&&Xdt(o,r),r}function Qdt(t,e){let n={},r=p(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>Edt(s))),h(n,["generatedMasks"],i)}return n}function Zdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],oc(s));let o=p(t,["scribbleImage"]);return e!==void 0&&o!=null&&h(e,["instances[0]","scribble"],Ydt(o)),r}function eft(t,e){let n={},r=p(t,["speaker"]);r!=null&&h(n,["speaker"],r);let i=p(t,["voiceConfig"]);return i!=null&&h(n,["voiceConfig"],vTe(i)),n}function mTe(t,e){let n={},r=p(t,["voiceConfig"]);r!=null&&h(n,["voiceConfig"],vTe(r));let i=p(t,["languageCode"]);i!=null&&h(n,["languageCode"],i);let s=p(t,["multiSpeakerVoiceConfig"]);return s!=null&&h(n,["multiSpeakerVoiceConfig"],Fdt(s)),n}function tft(t,e){let n={},r=p(t,["functionCallingConfig"]);r!=null&&h(n,["functionCallingConfig"],idt(r));let i=p(t,["retrievalConfig"]);i!=null&&h(n,["retrievalConfig"],i);let s=p(t,["includeServerSideToolInvocations"]);return s!=null&&h(n,["includeServerSideToolInvocations"],s),n}function nft(t,e){let n={},r=p(t,["functionCallingConfig"]);r!=null&&h(n,["functionCallingConfig"],r);let i=p(t,["retrievalConfig"]);if(i!=null&&h(n,["retrievalConfig"],i),p(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 rft(t,e){let n={};if(p(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=p(t,["googleMaps"]);r!=null&&h(n,["googleMaps"],Adt(r));let i=p(t,["mcpServers"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["mcpServers"],f)}let s=p(t,["codeExecution"]);s!=null&&h(n,["codeExecution"],s);let o=p(t,["computerUse"]);if(o!=null&&h(n,["computerUse"],o),p(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(p(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=p(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["functionDeclarations"],f)}let c=p(t,["googleSearch"]);c!=null&&h(n,["googleSearch"],Cdt(c));let l=p(t,["googleSearchRetrieval"]);if(l!=null&&h(n,["googleSearchRetrieval"],l),p(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 u=p(t,["urlContext"]);u!=null&&h(n,["urlContext"],u);let d=p(t,["fileSearch"]);return d!=null&&h(n,["fileSearch"],d),n}function gTe(t,e){let n={},r=p(t,["retrieval"]);r!=null&&h(n,["retrieval"],r);let i=p(t,["googleMaps"]);i!=null&&h(n,["googleMaps"],i);let s=p(t,["mcpServers"]);if(s!=null){let y=s;Array.isArray(y)&&(y=y.map(w=>Udt(w))),h(n,["mcpServers"],y)}let o=p(t,["codeExecution"]);o!=null&&h(n,["codeExecution"],o);let a=p(t,["computerUse"]);a!=null&&h(n,["computerUse"],Out(a));let c=p(t,["enterpriseWebSearch"]);c!=null&&h(n,["enterpriseWebSearch"],c);let l=p(t,["exaAiSearch"]);l!=null&&h(n,["exaAiSearch"],l);let u=p(t,["functionDeclarations"]);if(u!=null){let y=u;Array.isArray(y)&&(y=y.map(w=>w)),h(n,["functionDeclarations"],y)}let d=p(t,["googleSearch"]);d!=null&&h(n,["googleSearch"],d);let f=p(t,["googleSearchRetrieval"]);f!=null&&h(n,["googleSearchRetrieval"],f);let m=p(t,["parallelAiSearch"]);m!=null&&h(n,["parallelAiSearch"],m);let g=p(t,["urlContext"]);if(g!=null&&h(n,["urlContext"],g),p(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 ift(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["createTime"]);i!=null&&h(n,["createTime"],i);let s=p(t,["updateTime"]);return s!=null&&h(n,["updateTime"],s),n}function sft(t,e){let n={},r=p(t,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["createTime"]);i!=null&&h(n,["createTime"],i);let s=p(t,["updateTime"]);return s!=null&&h(n,["updateTime"],s),n}function oft(t,e,n){let r={},i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["description"]);e!==void 0&&s!=null&&h(e,["description"],s);let o=p(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&h(e,["defaultCheckpointId"],o),r}function aft(t,e,n){let r={},i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["description"]);e!==void 0&&s!=null&&h(e,["description"],s);let o=p(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&h(e,["defaultCheckpointId"],o),r}function cft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","name"],Kt(t,i));let s=p(e,["config"]);return s!=null&&oft(s,r),r}function lft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["config"]);return s!=null&&aft(s,r),r}function uft(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&h(e,["parameters","safetySetting"],s);let o=p(t,["personGeneration"]);e!==void 0&&o!=null&&h(e,["parameters","personGeneration"],o);let a=p(t,["includeRaiReason"]);e!==void 0&&a!=null&&h(e,["parameters","includeRaiReason"],a);let c=p(t,["outputMimeType"]);e!==void 0&&c!=null&&h(e,["parameters","outputOptions","mimeType"],c);let l=p(t,["outputCompressionQuality"]);e!==void 0&&l!=null&&h(e,["parameters","outputOptions","compressionQuality"],l);let u=p(t,["enhanceInputImage"]);e!==void 0&&u!=null&&h(e,["parameters","upscaleConfig","enhanceInputImage"],u);let d=p(t,["imagePreservationFactor"]);e!==void 0&&d!=null&&h(e,["parameters","upscaleConfig","imagePreservationFactor"],d);let f=p(t,["labels"]);e!==void 0&&f!=null&&h(e,["labels"],f);let m=p(t,["numberOfImages"]);e!==void 0&&m!=null&&h(e,["parameters","sampleCount"],m);let g=p(t,["mode"]);return e!==void 0&&g!=null&&h(e,["parameters","mode"],g),r}function dft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["image"]);s!=null&&h(r,["instances[0]","image"],oc(s));let o=p(e,["upscaleFactor"]);o!=null&&h(r,["parameters","upscaleConfig","upscaleFactor"],o);let a=p(e,["config"]);return a!=null&&uft(a,r),r}function fft(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o1(o))),h(n,["generatedImages"],s)}return n}function pft(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["uri"],r);let i=p(t,["encodedVideo"]);i!=null&&h(n,["videoBytes"],vm(i));let s=p(t,["encoding"]);return s!=null&&h(n,["mimeType"],s),n}function hft(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["uri"],r);let i=p(t,["bytesBase64Encoded"]);i!=null&&h(n,["videoBytes"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function mft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["_self"],oc(r));let i=p(t,["maskMode"]);return i!=null&&h(n,["maskMode"],i),n}function gft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["image"],a1(r));let i=p(t,["referenceType"]);return i!=null&&h(n,["referenceType"],i),n}function yft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["image"],oc(r));let i=p(t,["referenceType"]);return i!=null&&h(n,["referenceType"],i),n}function yTe(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["uri"],r);let i=p(t,["videoBytes"]);i!=null&&h(n,["encodedVideo"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["encoding"],s),n}function _Te(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["videoBytes"]);i!=null&&h(n,["bytesBase64Encoded"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function vTe(t,e){let n={},r=p(t,["replicatedVoiceConfig"]);r!=null&&h(n,["replicatedVoiceConfig"],zdt(r));let i=p(t,["prebuiltVoiceConfig"]);return i!=null&&h(n,["prebuiltVoiceConfig"],i),n}function _ft(t,e,n){let r={},i=p(e,["displayName"]);n!==void 0&&i!=null&&h(n,["displayName"],i);let s=p(e,["embeddingModel"]);return n!==void 0&&s!=null&&h(n,["embeddingModel"],Kt(t,s)),r}function vft(t,e){let n={},r=p(e,["config"]);return r!=null&&_ft(t,r,n),n}function Eft(t,e){let n={},r=p(t,["force"]);return e!==void 0&&r!=null&&h(e,["_query","force"],r),n}function wft(t){let e={},n=p(t,["name"]);n!=null&&h(e,["_url","name"],n);let r=p(t,["config"]);return r!=null&&Eft(r,e),e}function Sft(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","name"],n),e}function xft(t,e){let n={},r=p(t,["customMetadata"]);if(e!==void 0&&r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["customMetadata"],s)}let i=p(t,["chunkingConfig"]);return e!==void 0&&i!=null&&h(e,["chunkingConfig"],i),n}function bft(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Aft(o)),e}function Tft(t){let e={},n=p(t,["fileSearchStoreName"]);n!=null&&h(e,["_url","file_search_store_name"],n);let r=p(t,["fileName"]);r!=null&&h(e,["fileName"],r);let i=p(t,["config"]);return i!=null&&xft(i,e),e}function Aft(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Cft(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function Rft(t){let e={},n=p(t,["config"]);return n!=null&&Cft(n,e),e}function Ift(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["fileSearchStores"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["fileSearchStores"],s)}return e}function ETe(t,e){let n={},r=p(t,["mimeType"]);e!==void 0&&r!=null&&h(e,["mimeType"],r);let i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["customMetadata"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>c)),h(e,["customMetadata"],a)}let o=p(t,["chunkingConfig"]);return e!==void 0&&o!=null&&h(e,["chunkingConfig"],o),n}function kft(t){let e={},n=p(t,["fileSearchStoreName"]);n!=null&&h(e,["_url","file_search_store_name"],n);let r=p(t,["config"]);return r!=null&&ETe(r,e),e}function Pft(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function qft(t){let n=globalThis[Symbol.for("undici.globalDispatcher.1")];if(n)for(let r of Object.getOwnPropertySymbols(n)){let i=r.description;if(i?.includes("headers timeout")||i?.includes("body timeout")){let s=n[r];typeof s=="number"&&(n[r]=Math.max(s,t))}}}function $ft(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 s=()=>r.abort();return e&&(e.aborted?r.abort():e.addEventListener("abort",s)),{signal:r.signal,dispose:()=>{i!==void 0&&clearTimeout(i),e?.removeEventListener("abort",s)}}}async function _3(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 sx({message:i,status:n}):new Error(i)}}function Kft(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{let s=JSON.parse(t.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))n=s;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function r(s,o){let a=Object.assign({},s);for(let c in o)if(Object.prototype.hasOwnProperty.call(o,c)){let l=o[c],u=a[c];l&&typeof l=="object"&&!Array.isArray(l)&&u&&typeof u=="object"&&!Array.isArray(u)?a[c]=r(u,l):(u&&l&&typeof u!=typeof l&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof u}, New type: ${typeof l}. Overwriting.`),a[c]=l)}return a}let i=r(n,e);t.body=JSON.stringify(i)}function STe(t){for(let e of t)if(Xft(e)||typeof e=="object"&&"inputSchema"in e)return!0;return wTe}function xTe(t){var e;let n=(e=t[wV])!==null&&e!==void 0?e:"";t[wV]=(n+` ${Yft}`).trimStart()}function Xft(t){return t!==null&&typeof t=="object"&&t instanceof ox}function Jft(t){return pv(this,arguments,function*(n,r=100){let i,s=0;for(;s<r;){let o=yield Hn(n.listTools({cursor:i}));for(let a of o.tools)yield yield Hn(a),s++;if(!o.nextCursor)break;i=o.nextCursor}})}function Qft(t){return t!==null&&typeof t=="object"&&"listTools"in t&&typeof t.listTools=="function"}function Zft(...t){if(wTe=!0,t.length===0)throw new Error("No MCP clients provided");let e=t[t.length-1];return Qft(e)?ox.create(t,{}):ox.create(t.slice(0,t.length-1),e)}async function ept(t,e,n){let r=new $O,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(r,i),e(r)}function tpt(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function npt(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}async function ipt(t,e,n){let r=new qO,i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;let s=JSON.parse(i);if(t.isVertexAI()){let o=put(s);Object.assign(r,o)}else Object.assign(r,s);e(r)}function opt(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function apt(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}function vbe(t){var e,n,r;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let o of(n=t?.tools)!==null&&n!==void 0?n:[])if(hv(o)){i=!0;break}if(!i)return!0;let s=(r=t?.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0):!1}function hv(t){return"callTool"in t&&typeof t.callTool=="function"}function cpt(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=>hv(i)))!==null&&r!==void 0?r:!1}function Ebe(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((r,i)=>{if(hv(r))return;let s=r;s.functionDeclarations&&s.functionDeclarations.length>0&&n.push(i)}),n}function wbe(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}function lpt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 upt(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function dpt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Ept(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function fpt(t,e,n){let r={},i=p(e,["expireTime"]);n!==void 0&&i!=null&&h(n,["expireTime"],i);let s=p(e,["newSessionExpireTime"]);n!==void 0&&s!=null&&h(n,["newSessionExpireTime"],s);let o=p(e,["uses"]);n!==void 0&&o!=null&&h(n,["uses"],o);let a=p(e,["liveConnectConstraints"]);n!==void 0&&a!=null&&h(n,["bidiGenerateContentSetup"],vpt(t,a));let c=p(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&h(n,["fieldMask"],c),r}function ppt(t,e){let n={},r=p(e,["config"]);return r!=null&&h(n,["config"],fpt(t,r,n)),n}function hpt(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function mpt(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 gpt(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],lpt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 ypt(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function _pt(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],r);let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],Az(d));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],dpt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let L=yv(y);Array.isArray(L)&&(L=L.map(k=>xpt(gv(k)))),h(e,["setup","tools"],L)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],Spt(w));let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);if(e!==void 0&&D!=null&&h(e,["setup","proactivity"],D),p(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let $=p(t,["avatarConfig"]);e!==void 0&&$!=null&&h(e,["setup","avatarConfig"],$);let G=p(t,["safetySettings"]);if(e!==void 0&&G!=null){let L=G;Array.isArray(L)&&(L=L.map(k=>wpt(k))),h(e,["setup","safetySettings"],L)}let V=p(t,["translationConfig"]);return e!==void 0&&V!=null&&h(e,["setup","generationConfig","translationConfig"],V),n}function vpt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],_pt(i,n)),n}function Ept(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],hpt(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],mpt(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],upt(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function wpt(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Spt(t){let e={},n=p(t,["handle"]);if(n!=null&&h(e,["handle"],n),p(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 xpt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],gpt(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],ypt(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function bpt(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&&Object.keys(r).length>0){let i=Object.keys(r).map(s=>`${n}.${s}`);e.push(...i)}else e.push(n)}return e.join(",")}function Tpt(t,e){let n=null,r=t.bidiGenerateContentSetup;if(typeof r=="object"&&r!==null&&"setup"in r){let s=r.setup;typeof s=="object"&&s!==null?(t.bidiGenerateContentSetup=s,n=s):delete t.bidiGenerateContentSetup}else r!==void 0&&delete t.bidiGenerateContentSetup;let i=t.fieldMask;if(n){let s=bpt(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)s?t.fieldMask=s:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let o=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],a=[];i.length>0&&(a=i.map(l=>o.includes(l)?`generationConfig.${l}`:l));let c=[];s&&c.push(s),a.length>0&&c.push(...a),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}function Apt(t,e){let n={},r=p(t,["force"]);return e!==void 0&&r!=null&&h(e,["_query","force"],r),n}function Cpt(t){let e={},n=p(t,["name"]);n!=null&&h(e,["_url","name"],n);let r=p(t,["config"]);return r!=null&&Apt(r,e),e}function Rpt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","name"],n),e}function Ipt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function kpt(t){let e={},n=p(t,["parent"]);n!=null&&h(e,["_url","parent"],n);let r=p(t,["config"]);return r!=null&&Ipt(r,e),e}function Ppt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["documents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["documents"],s)}return e}function Opt(){return"Deno"in globalThis}function ax(){var t,e,n,r,i,s;if(gO)return gO;let o=globalThis,a={};return Opt()?a=(r=(n=(e=(t=o.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:{}:a=(s=(i=o.process)===null||i===void 0?void 0:i.env)!==null&&s!==void 0?s:{},gO=a,gO}function Mpt(t){var e,n;let r=Object.assign({},t),i=ax();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}function Npt(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 Dpt(t,e){if(TTe(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return bTe(n)?Sbe(n):Sbe(void 0)}function Lpt(t){var e,n;if(TTe(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(bTe(t))return t.default_headers}function Sbe(t){var e,n;let r=ax(),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 ATe(i)?i:void 0}function Upt(t){var e,n;let r={};for(let[s,o]of t){let a=s.toLowerCase();a!=="authorization"&&a!=="x-goog-api-key"&&(r[s]=o)}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 ATe(i)?i:void 0}function xbe(t,e){if(e)for(let[n,r]of new Headers(e))t.get(n)===null&&t.set(n,r)}function Fpt(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 Bpt(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",$pt(e.access_token))}}function qpt(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function $pt(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function bTe(t){return typeof t=="object"&&t!==null}function TTe(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function ATe(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}function ym(t){return Vpt(t)?t:t instanceof na?Gpt(t):t instanceof Gf?Hpt(t):t}function Gpt(t){let e=jpt(t),n=ys.generate(t.statusCode,e,t.message,t.headers);return jS(n,"body",t.body),jS(n,"contentType",t.contentType),jS(n,"rawResponse",t.rawResponse),jS(n,"statusCode",t.statusCode),jS(n,"cause",t),n}function Hpt(t){return t instanceof ZO?new PV({message:t.message}):t instanceof QO?new kV({message:t.message}):t instanceof e1?new mv({message:t.message,cause:t}):new mv({message:t.message,cause:t})}function jpt(t){let e=bbe(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=bbe(t,"error");return n&&typeof n=="object"?n:void 0}function bbe(t,e){return t&&typeof t=="object"?t[e]:void 0}function Tbe(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Wpt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vpt(t){return typeof t=="object"&&t!==null?ys.prototype.isPrototypeOf(t):!1}function jS(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function uv(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(Abe),[s="",...o]=i;if(s.split("/").length!==2)return!1;let a=r.split(Abe),[c="",...l]=a,[u="",d=""]=c.split("/");if(!u||!d||s!=="*/*"&&c!==s&&`${u}/*`!==s&&`*/${d}`!==s||l.length<o.length)return!1;let f=new Set(l);for(let m of o)if(!f.has(m))return!1;return!0}function kt(t,e){let n=`${t.status}`,r=Array.isArray(e)?e:[e];return r.length?r.some(i=>{let s=`${i}`;if(s==="default")return!0;if(!Kpt.test(`${s}`))return s===n;let o=s.charAt(0);if(!o)throw new Error("Invalid status code range");let a=n.charAt(0);if(!a)throw new Error(`Invalid response status code: ${n}`);return a===o}):!1}function Ypt(t,e,n){return kt(t,e)&&uv(t,n)}function CTe(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 RTe(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 Xpt(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 Jpt(t){let e=new RV;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}function Cbe(t){return{ok:!0,value:t}}function ju(t){return{ok:!1,error:t}}function Rz(t){return btoa(String.fromCodePoint(...t))}function Qpt(t){return new TextEncoder().encode(t)}function Zpt(t){return Rz(Qpt(t))}function Mt(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(i={}){return t.replace(n,function(s,o){if(!eht.call(i,o))throw new Error(`Parameter '${o}' is required`);let a=i[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Parameter '${o}' must be a string or number`);return`${a}`}).replace(/^\/+/,"")}}function tht(t){var e;let n=t.server_url,r={};if(!n){let s=(e=t.server_idx)!==null&&e!==void 0?e:0;if(s<0||s>=Rbe.length)throw new Error(`Invalid server index ${s}`);n=Rbe[s]||""}let i=Mt(n)(r);return new URL(i)}function rht(...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):iht(e)}}function iht(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 o of t)if(o.aborted)return o;function r(){e.abort(this.reason),s()}let i=[];function s(){for(let o of i){let a=o.deref();a&&a.removeEventListener("abort",r)}}for(let o of t)i.push(new WeakRef(o)),o.addEventListener("abort",r);return n}function $t(t){let e={};for(let[n,r]of Object.entries(t))typeof r<"u"&&(e[n]=r);return e}function Hf(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}function ITe(t,e){return c1(t,e==="percentExceptReserved"?"percent":e)}function c1(t,e){switch(e){case"percent":return encodeURIComponent(t);case"percentExceptReserved":return encodeURIComponent(t).replace(sht,n=>decodeURIComponent(n));default:return t}}function oht(t){return(e,n,r)=>{let i="",s=r?.explode?PTe(e,n):[[e,n]];if(s.every(([l,u])=>u==null))return;let o=l=>c1(l,r?.charEncoding),a=l=>o(OTe(l)),c=o(t);return s.forEach(([l,u])=>{var d,f;let m="",g=null;u!=null&&(Array.isArray(u)?g=(d=NTe(u,y=>`${a(y)}`))===null||d===void 0?void 0:d.join(c):Hf(u)?g=(f=DTe(Object.entries(u),([y,w])=>`${o(y)}${c}${a(w)}`))===null||f===void 0?void 0:f.join(c):g=`${a(u)}`,g!=null&&(m=`${ITe(l,r?.charEncoding)}=${g}`,!(!m||m==="=")&&(i+=`&${m}`)))}),i.slice(1)}}function ac(t,e,n){if(typeof e>"u")return;let i=(s=>c1(s,n?.charEncoding))(JSON.stringify(e,MTe));return n?.explode?i:`${ITe(t,n?.charEncoding)}=${i}`}function PTe(t,e){return Array.isArray(e)?e.map(n=>[t,n]):Hf(e)?Object.entries(e??{}).map(([r,i])=>[r,i]):[[t,e]]}function OTe(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?Rz(t):typeof t=="object"?JSON.stringify(t,MTe):`${t}`}function MTe(t,e){return e instanceof Uint8Array?Rz(e):e}function NTe(t,e){let n=t.reduce((r,i)=>{if(i==null)return r;let s=e(i);return s==null||r.push(s),r},[]);return n.length?n:null}function DTe(t,e){let n=[];for(let[r,i]of t){if(i==null)continue;let s=e([r,i]);s!=null&&n.push(s)}return n.length?n:null}function aht(...t){return t.filter(Boolean).join("&")}function cht(t){return function(n,r){var i,s,o;let a=Object.assign(Object.assign({},r),{explode:(i=r?.explode)!==null&&i!==void 0?i:!0,charEncoding:(s=r?.charEncoding)!==null&&s!==void 0?s:"percent"}),c=new Set((o=r?.allowEmptyValue)!==null&&o!==void 0?o:[]),l=Object.entries(n).map(([u,d])=>c.has(u)&&(d==null||d===""||Array.isArray(d)&&d.length===0)?`${encodeURIComponent(u)}=`:t(u,d,a));return aht(...l)}}async function lht(t,e){var n;switch(e.config.strategy){case"backoff":return fht(kbe(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:Ibe);case"attempt-count-backoff":return pht(kbe(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},Ibe),e.config.backoff),e.config);default:return await t(0)}}function kbe(t,e){return async n=>{try{let r=await t(n);if(dht(r,e.statusCodes))throw new jf("Response failed with retryable status code",r);return r}catch(r){throw r instanceof jf||e.retryConnectionErrors&&(RTe(r)||CTe(r))?r:new cx("Permanent error",{cause:r})}}}function dht(t,e){let n=`${t.status}`;return e.some(r=>{if(!uht.test(r))return r===n;let i=r.charAt(0);if(!i)throw new Error("Invalid status code range");let s=n.charAt(0);if(!s)throw new Error(`Invalid response status code: ${n}`);return s===i})}async function fht(t,e){let{maxElapsedTime:n,initialInterval:r,exponent:i,maxInterval:s}=e,o=Date.now(),a=0;for(;;)try{return await t(a)}catch(c){if(c instanceof cx)throw c.cause;if(Date.now()-o>n){if(c instanceof jf)return c.response;throw c}let u=0;c instanceof jf&&(u=LTe(c.response)),u<=0&&(u=r*Math.pow(a,i)+Math.random()*1e3);let d=Math.min(u,s);await UTe(d),a++}}async function pht(t,e,n){let r=0;for(;;)try{return await t(r)}catch(i){if(i instanceof cx)throw i.cause;if(r>=n.maxRetries){if(i instanceof jf)return i.response;throw i}let s=0;i instanceof jf&&(s=LTe(i.response)),s<=0&&(s=e.initialInterval*Math.pow(e.exponent,r)*(1-Math.random()*.25));let o=Math.min(s,e.maxInterval);await UTe(o),r++}}function LTe(t){let e=t.headers.get("retry-after-ms");if(e){let s=Number(e);if(Number.isFinite(s)&&s>=0)return s}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 s=i-Date.now();return s>0?Math.ceil(s):0}return 0}async function UTe(t){return new Promise(e=>setTimeout(e,t))}async function ght(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,s]of e.headers.entries())t.log(`${i}: ${s}`);switch(t.groupEnd(),t.group("Body:"),!0){case FTe.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[s,o]of i){let a=o instanceof Blob?"<Blob>":o;t.log(`${s}: ${a}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function yht(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[s,o]of e.headers.entries())t.log(`${s}: ${o}`);switch(t.groupEnd(),t.group("Body:"),!0){case(uv(e,"application/json")||FTe.test(i)&&!Pbe.test(i)):t.log(await e.clone().json());break;case(uv(e,"application/jsonl")||Pbe.test(i)):case uv(e,"text/event-stream"):t.log(`<${r}>`);break;case uv(e,"text/*"):t.log(await e.clone().text());break;case uv(e,"multipart/form-data"):{let s=await e.clone().formData();for(let[o,a]of s){let c=a instanceof Blob?"<Blob>":a;t.log(`${o}: ${c}`)}break}default:t.log(`<${r}>`);break}t.groupEnd(),t.groupEnd()}function Obe(t){try{return JSON.parse(t)}catch{return t}}function _ht(t,e={}){var n,r;let i=e.flattened===!0,s=(n=e.sentinel)!==null&&n!==void 0?n:"";return new qV(t,o=>s!==""&&o.data===s?{done:!0,value:void 0}:i?{done:!1,value:o.data==null?void 0:Obe(o.data)}:{done:!1,value:Object.assign(Object.assign({},o),{data:o.data==null?o.data:Obe(o.data)})},{dataRequired:(r=e.dataRequired)!==null&&r!==void 0?r:!0})}function Eht(t,e,n){for(let r=n;r<e;r++)if(!(t[r]!==ea&&t[r]!==ta))for(let i of BTe){if(r+i.length>e)continue;let s=!0;for(let o=0;o<i.length;o++)if(t[r+o]!==i[o]){s=!1;break}if(s)return{index:r,length:i.length}}return null}function wht(t,e,n,r){let s=new TextDecoder().decode(t).split(/\r\n|\r|\n/),o=[],a={},c=!0;for(let l of s){if(!l||l.startsWith(":"))continue;c=!1;let u=l.indexOf(":"),d=l,f="";u>0&&(d=l.slice(0,u),f=l[u+1]===" "?l.slice(u+2):l.slice(u+1)),d==="data"?o.push(f):d==="event"?a.event=f:d==="id"&&!f.includes("\0")?n.eventId=f:d==="retry"&&/^\d+$/.test(f)&&(a.retry=Number(f))}if(!c){if(a.id=n.eventId,o.length)a.data=o.join(`
524
- `);else if(r)return;return e(a)}}function Wf(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function tn(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function qTe(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function $Te(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function Be(t){return{enc:"fail",codes:t}}function Gt(...t){return async function(n,r,i){let s,o;for(let f of t){let{codes:m}=f,g="ctype"in f?f.ctype:Sht[f.enc];if(g&&Ypt(n,m,g)){o=f;break}else if(!g&&kt(n,m)){o=f;break}}if(!o)return[{ok:!1,error:new r1("Unexpected Status or Content-Type",{response:n,request:r,body:await n.text().catch(()=>"")})},s];let a=o.enc,c="";switch(a){case"json":c=await n.text();try{s=JSON.parse(c)}catch(f){if(!("err"in o))throw f;s=c}break;case"jsonl":s=n.body;break;case"bytes":s=new Uint8Array(await n.arrayBuffer());break;case"stream":s=n.body;break;case"text":c=await n.text(),s=c;break;case"sse":if(n.body){let f="sse"in o&&o.sse||{};s=_ht(n.body,f)}else s=null;break;case"nil":c=await n.text(),s=void 0;break;case"fail":c=await n.text(),s=c;break;default:throw new Error(`Unsupported response type: ${a}`)}if(o.enc==="fail")return[{ok:!1,error:new r1("API error occurred",{request:r,response:n,body:c})},s];let l=o.key||i?.resultKey,u,d=o.hdrs?{headers:bht(n.headers)}:null;return"err"in o?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),Hf(s)?s:null):l?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),{[l]:s}):o.hdrs?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),Hf(s)?s:null):u=s,"err"in o?[{ok:!1,error:o.errorClass?new o.errorClass(u,{request:r,response:n,body:c}):u},s]:[{ok:!0,value:u},s]}}function bht(t){let e={};for(let[n,r]of t.entries())e[n]=r.split(xht);return e}function Tht(...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":Aht(e,r);break;case"http:custom":break;case"http:bearer":_O(e,r);break;case"oauth2":_O(e,r);break;case"oauth2:password":_O(e,r);break;case"oauth2:client_credentials":break;case"openIdConnect":_O(e,r);break;default:throw $V.unrecognizedType(i)}}),e)}function Aht(t,e){e.value!=null&&(t.basic=e.value)}function _O(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 Ht(t,e){var n,r;let i=[[{fieldName:"accessToken",type:"http:custom",value:(n=t?.access_token)!==null&&n!==void 0?n:ax().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(r=t?.api_key)!==null&&r!==void 0?r:ax().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return Tht(...i)}async function jt(t){if(t!=null)return typeof t=="function"?t():t}function qt(t){let e=t.$inspect(),n=e.then(([i,s])=>{if(!i.ok)throw i.error;return[i.value,s]}),r=e.then(([i,s])=>{var o;if(!i.ok&&!(!((o=s.response)===null||o===void 0)&&o.ok))throw i.error;return s});return n.catch(()=>{}),r.catch(()=>{}),new At(n,r)}function HTe(t,e,n,r){return new At(Cht(t,e,n,r))}async function Cht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function jTe(t,e,n,r){return new At(Rht(t,e,n,r))}async function Rht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function WTe(t,e,n,r){return new At(Iht(t,e,n,r))}async function Iht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function VTe(t,e,n,r,i,s){return new At(kht(t,e,n,r,i,s))}async function kht(t,e,n,r,i,s){var o,a,c;let u={api_version:e,page_size:n,page_token:r,parent:i},d=null,f={api_version:De("api_version",(o=u?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/agents")(f),g=cc({page_size:u?.page_size,page_token:u?.page_token,parent:u?.parent}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(Be("4XX"),Be("5XX"),tn("default"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function zTe(t,e,n,r){return new At(Pht(t,e,n,r))}async function Pht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function KTe(t,e,n,r){return new At(Oht(t,e,n,r))}async function Oht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function YTe(t,e,n,r){return new At(Mht(t,e,n,r))}async function Mht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function XTe(t,e,n,r,i){return new At(Nht(t,e,n,r,i))}async function Nht(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/credentials")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(tn(200),Be("4XX"),Be("5XX"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function JTe(t,e,n,r,i,s){return new At(Dht(t,e,n,r,i,s))}async function Dht(t,e,n,r,i,s){var o,a,c;let u={id:e,body:n,api_version:r,update_mask:i},d=ac("body",u.body,{explode:!0}),f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",u.id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/credentials/{id}")(f),g=cc({update_mask:u.update_mask}),y=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"PATCH",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function QTe(t,e,n,r){return new At(Lht(t,e,n,r))}async function Lht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function ZTe(t,e,n,r){return new At(Uht(t,e,n,r))}async function Uht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function eAe(t,e,n,r){return new At(Fht(t,e,n,r))}async function Fht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function tAe(t,e,n,r,i){return new At(Bht(t,e,n,r,i))}async function Bht(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/environments")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function nAe(t,e,n,r,i,s,o,a){return new At(qht(t,e,n,r,i,s,o,a))}async function qht(t,e,n,r,i,s,o,a){var c,l,u;let f={environment:e,path:n,api_version:r,page_size:i,page_token:s,recursive:o},m=null,g={api_version:De("api_version",(c=f.api_version)!==null&&c!==void 0?c:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:De("environment",f.environment,{explode:!1,charEncoding:"percent"}),path:De("path",f.path,{explode:!1,charEncoding:"percentExceptReserved"})},y=Mt("/{api_version}/environments/{environment}/files/{path}")(g),w=cc({page_size:f.page_size,page_token:f.page_token,recursive:f.recursive}),S=new Headers($t({Accept:"application/json"})),T=await jt(t._options.security),R=Ht(T),C={options:t._options,base_url:(u=(l=a?.server_url)!==null&&l!==void 0?l:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:R,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"]},D=t._createRequest(C,{security:R,method:"GET",baseURL:a?.server_url,path:y,headers:S,query:w,body:m,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!D.ok)return[D,{status:"invalid"}];let $=D.value,G=await t._do($,{context:C,isErrorStatusCode:k=>kt({status:k},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!G.ok)return[G,{status:"request-error",request:$}];let V=G.value,[L]=await Gt(tn(200),Be("4XX"),Be("5XX"))(V,$);return L.ok?[L,{status:"complete",request:$,response:V}]:[L,{status:"complete",request:$,response:V}]}function rAe(t,e,n,r,i,s,o,a,c,l,u){return new At($ht(t,e,n,r,i,s,o,a,c,l,u))}async function $ht(t,e,n,r,i,s,o,a,c,l,u){var d,f,m;let y={environment:e,path:n,"X-Goog-Upload-Command":r,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":s,"X-Goog-Upload-Protocol":o,api_version:a,extract:c,overwrite:l},w=null,S={api_version:De("api_version",(d=y.api_version)!==null&&d!==void 0?d:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:De("environment",y.environment,{explode:!1,charEncoding:"percent"}),path:De("path",y.path,{explode:!1,charEncoding:"percentExceptReserved"})},T=Mt("/upload/{api_version}/environments/{environment}/files/{path}")(S),R=cc({extract:y.extract,overwrite:y.overwrite}),C=new Headers($t({Accept:"*/*","X-Goog-Upload-Command":De("X-Goog-Upload-Command",y["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":De("X-Goog-Upload-Header-Content-Length",y["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":De("X-Goog-Upload-Header-Content-Type",y["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":De("X-Goog-Upload-Protocol",y["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),D=await jt(t._options.security),$=Ht(D),G={options:t._options,base_url:(m=(f=u?.server_url)!==null&&f!==void 0?f:t._baseURL)!==null&&m!==void 0?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:$,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"]},V=t._createRequest(G,{security:$,method:"PUT",baseURL:u?.server_url,path:T,headers:C,query:R,body:w,userAgent:t._options.user_agent,timeout_ms:u?.timeout_ms||t._options.timeout_ms||-1},u);if(!V.ok)return[V,{status:"invalid"}];let L=V.value,k=await t._do(L,{context:G,isErrorStatusCode:I=>kt({status:I},["4XX","5XX"]),retryConfig:G.retry_config,retryCodes:G.retry_codes});if(!k.ok)return[k,{status:"request-error",request:L}];let E=k.value,A={httpMeta:{response:E,request:L}},[M]=await Gt($Te(200,{hdrs:!0}),Be("4XX"),Be("5XX"))(E,L,{extraFields:A});return M.ok?[M,{status:"complete",request:L,response:E}]:[M,{status:"complete",request:L,response:E}]}function iAe(t,e,n,r){return new At(Ght(t,e,n,r))}async function Ght(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/interactions/{id}/cancel")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,C={httpMeta:{response:R,request:S}},[D]=await Gt(tn(200),Wf("4XX",KV),Wf("5XX",zV))(R,S,{extraFields:C});return D.ok?[D,{status:"complete",request:S,response:R}]:[D,{status:"complete",request:S,response:R}]}function sAe(t,e,n,r){return new At(Hht(t,e,n,r))}async function Hht(t,e,n,r){var i,s,o,a;let c={body:e,api_version:n},l=c,u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(i=l.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/interactions")(d),m=new Headers($t({"Content-Type":"application/json",Accept:!((s=c?.body)===null||s===void 0)&&s.stream?"text/event-stream":"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:r?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,D={httpMeta:{response:C,request:T}},[$]=await Gt(tn(200),qTe(200,{sentinel:"[DONE]",flattened:!0}),Wf("4XX",XV),Wf("5XX",YV))(C,T,{extraFields:D});return $.ok?[$,{status:"complete",request:T,response:C}]:[$,{status:"complete",request:T,response:C}]}function jht(t,e,n,r){return new At(Wht(t,e,n,r))}async function Wht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/interactions/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,C={httpMeta:{response:R,request:S}},[D]=await Gt($Te(200),Wf("4XX",QV),Wf("5XX",JV))(R,S,{extraFields:C});return D.ok?[D,{status:"complete",request:S,response:R}]:[D,{status:"complete",request:S,response:R}]}function oAe(t,e,n,r,i,s,o){return new At(Vht(t,e,n,r,i,s,o))}async function Vht(t,e,n,r,i,s,o){var a,c,l;let u={id:e,api_version:n,include_input:r,last_event_id:i,stream:s},d=u,f=null,m={api_version:De("api_version",(a=d.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",d.id,{explode:!1,charEncoding:"percent"})},g=Mt("/{api_version}/interactions/{id}")(m),y=cc({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),w=new Headers($t({Accept:u?.stream?"text/event-stream":"application/json"})),S=await jt(t._options.security),T=Ht(S),R={options:t._options,base_url:(l=(c=o?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&l!==void 0?l:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:T,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(R,{security:T,method:"GET",baseURL:o?.server_url,path:g,headers:w,query:y,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let D=C.value,$=await t._do(D,{context:R,isErrorStatusCode:k=>kt({status:k},["4XX","5XX"]),retryConfig:R.retry_config,retryCodes:R.retry_codes});if(!$.ok)return[$,{status:"request-error",request:D}];let G=$.value,V={httpMeta:{response:G,request:D}},[L]=await Gt(tn(200),qTe(200,{sentinel:"[DONE]",flattened:!0}),Wf("4XX",ez),Wf("5XX",ZV))(G,D,{extraFields:V});return L.ok?[L,{status:"complete",request:D,response:G}]:[L,{status:"complete",request:D,response:G}]}function aAe(t,e,n,r){return new At(zht(t,e,n,r))}async function zht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function cAe(t,e,n,r){return new At(Kht(t,e,n,r))}async function Kht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function lAe(t,e,n,r){return new At(Yht(t,e,n,r))}async function Yht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function uAe(t,e,n,r,i,s){return new At(Xht(t,e,n,r,i,s))}async function Xht(t,e,n,r,i,s){var o,a,c;let u={trigger_id:e,api_version:n,page_size:r,page_token:i},d=null,f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:De("trigger_id",u.trigger_id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/triggers/{trigger_id}/executions")(f),g=cc({page_size:u.page_size,page_token:u.page_token}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function dAe(t,e,n,r,i,s){return new At(Jht(t,e,n,r,i,s))}async function Jht(t,e,n,r,i,s){var o,a,c;let u={api_version:e,filter:n,page_size:r,page_token:i},d=null,f={api_version:De("api_version",(o=u?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/triggers")(f),g=cc({filter:u?.filter,page_size:u?.page_size,page_token:u?.page_token}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function fAe(t,e,n,r){return new At(Qht(t,e,n,r))}async function Qht(t,e,n,r){var i,s,o;let c={trigger_id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:De("trigger_id",c.trigger_id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{trigger_id}/executions")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function pAe(t,e,n,r,i){return new At(Zht(t,e,n,r,i))}async function Zht(t,e,n,r,i){var s,o,a;let l={id:e,body:n,api_version:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/triggers/{id}")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"PATCH",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(tn(200),Be("4XX"),Be("5XX"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function hAe(t,e,n,r){return new At(emt(t,e,n,r))}async function emt(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function mAe(t,e,n,r){return new At(tmt(t,e,n,r))}async function tmt(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function gAe(t,e,n,r){return new At(nmt(t,e,n,r))}async function nmt(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function yAe(t,e,n,r,i){return new At(rmt(t,e,n,r,i))}async function rmt(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function _Ae(t,e,n,r,i){return new At(imt(t,e,n,r,i))}async function imt(t,e,n,r,i){var s,o,a;let l={id:e,api_version:n,body:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks/{id}:ping")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function vAe(t,e,n,r,i){return new At(smt(t,e,n,r,i))}async function smt(t,e,n,r,i){var s,o,a;let l={id:e,api_version:n,body:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks/{id}:rotateSigningSecret")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function EAe(t,e,n,r,i,s){return new At(omt(t,e,n,r,i,s))}async function omt(t,e,n,r,i,s){var o,a,c;let u={id:e,api_version:n,update_mask:r,body:i},d=ac("body",u.body,{explode:!0}),f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",u.id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/webhooks/{id}")(f),g=cc({update_mask:u.update_mask}),y=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"PATCH",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(Be("4XX"),Be("5XX"),tn("default"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function lmt(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function umt(t){let e=dmt(t.getApiVersion()),n=t.getProject(),r=t.getLocation();return t.isVertexAI()&&e&&n&&r?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(r)}`:e}function ra(t,e={}){var n,r,i,s,o,a,c;let l=e.http_client||(n=t.getFetch)===null||n===void 0?void 0:n.call(t),u=(r=e.http_client)!==null&&r!==void 0?r:l?new t1({fetcher:l}):void 0;return new amt(Object.assign(Object.assign({},e),{http_client:u,api_version:(i=e.api_version)!==null&&i!==void 0?i:umt(t),security:(s=e.security)!==null&&s!==void 0?s:new CV({defaultHeaders:Object.assign(Object.assign({},(o=t.getDefaultHeaders)===null||o===void 0?void 0:o.call(t)),(a=t.getHeaders)===null||a===void 0?void 0:a.call(t)),getAuthHeaders:f=>t.getAuthHeaders(f)}),server_url:(c=e.server_url)!==null&&c!==void 0?c:lmt(t)}))}function dmt(t){return t.replace(/^\/+|\/+$/g,"")}function It(t,e=!1){var n,r,i,s;if(!t&&!e)return;let o=t??{},{timeout:a,maxRetries:c,defaultBaseURL:l,query:u,body:d,fetchOptions:f}=o,m=Cr(o,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),g=Object.assign({},m);i1(u)?g.extra_query=u:Nbe("query",u),i1(d)?g.extra_body=d:Nbe("body",d);let y=(n=m.fetch_options)!==null&&n!==void 0?n:f;y&&(g.fetch_options=y);let w=(r=m.server_url)!==null&&r!==void 0?r:l;w&&(g.server_url=w);let S=(i=m.timeout_ms)!==null&&i!==void 0?i:a;if(S!==void 0&&(g.timeout_ms=S),c!==void 0&&(g.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let T=new Headers((s=g.headers)!==null&&s!==void 0?s:y?.headers);T.set("Accept","text/event-stream"),g.headers=T}return g}function Nbe(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 en(t){let[e,n]=await t.$inspect();if(!e.ok)throw ym(e.error);return fmt(e.value,n)}async function v3(t){try{return await t()}catch(e){throw ym(e)}}function Dbe(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 s=e[Symbol.asyncIterator]();return{async next(...o){try{return await s.next(...o)}catch(a){throw ym(a)}},async return(o){if(!s.return)return{done:!0,value:o};try{return await s.return(o)}catch(a){throw ym(a)}},async throw(o){if(!s.throw)throw ym(o);try{return await s.throw(o)}catch(a){throw ym(a)}},[Symbol.asyncIterator](){return this}}}}})}function fmt(t,e){return!i1(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:pmt(e.response,t)})}function pmt(t,e){let n={};for(let[r,i]of t.headers.entries())n[r]=i;return{headers:n,responseInternal:t,json:async()=>e}}function E3(t){let e=hmt(t);return e?gmt(e):t}function hmt(t){if(i1(t)){if(Array.isArray(t.steps))return t;if(mmt(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,r=Cr(t,["outputs"]);return Object.assign(Object.assign({},r),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function mmt(t){let e=t.model;return typeof e=="string"&&cmt.has(e)}function i1(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gmt(t){var e,n;let r=ymt(t),i=(e=r.steps)!==null&&e!==void 0?e:[],s=[],o=!1;e:for(let d=i.length-1;d>=0;d--){let f=i[d];if(f.type==="user_input")break;if(f.type!=="model_output"||!f.content){if(o)break;continue}let m=f.content;for(let g=m.length-1;g>=0;g--){let y=m[g];if(y.type==="text")o=!0,s.push((n=y.text)!==null&&n!==void 0?n:"");else if(o)break e}}let a,c,l;for(let d=i.length-1;d>=0;d--){let f=i[d];if(f.type==="user_input")break;if(f.type==="model_output"&&f.content)for(let m=f.content.length-1;m>=0;m--){let g=f.content[m];g.type==="image"&&!a&&(a=g),g.type==="audio"&&!c&&(c=g),g.type==="video"&&!l&&(l=g)}}let u=s.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},r),u&&{output_text:u}),a?{output_image:a}:{}),c?{output_audio:c}:{}),l?{output_video:l}:{})}function ymt(t){return Object.assign(Object.assign({},t),{created:Lbe(t.created),updated:Lbe(t.updated)})}function Lbe(t){return t instanceof Date?t.toISOString():t}function _mt(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]}function vmt(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==WS||Array.isArray(e.scopes)&&e.scopes.indexOf(WS)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${WS}`)}else return e.scopes=[WS],e;return e}else return e={scopes:[WS]},e}async function Emt(t,e){var n,r,i;let s=Cz(t.file);if(s!==void 0)return await e.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal});if(tTe(t.file)){let o=(i=t.file.video)===null||i===void 0?void 0:i.videoBytes;if(typeof o=="string")return o;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(nTe(t.file)){let o=t.file.videoBytes;if(typeof o=="string")return o;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}function wmt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Smt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function xmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function bmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function mz(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Umt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function Tmt(t,e,n){let r={};if(p(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=p(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&h(e,["displayName"],i),p(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=p(t,["epochCount"]);e!==void 0&&s!=null&&h(e,["tuningTask","hyperparameters","epochCount"],s);let o=p(t,["learningRateMultiplier"]);if(o!=null&&h(r,["tuningTask","hyperparameters","learningRateMultiplier"],o),p(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(p(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(p(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(p(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(p(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 a=p(t,["batchSize"]);e!==void 0&&a!=null&&h(e,["tuningTask","hyperparameters","batchSize"],a);let c=p(t,["learningRate"]);if(e!==void 0&&c!=null&&h(e,["tuningTask","hyperparameters","learningRate"],c),p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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 Amt(t,e,n){let r={},i=p(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec"],vO(I))}else if(i==="PREFERENCE_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec"],vO(I))}else if(i==="DISTILLATION"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["distillationSpec"],vO(I))}else if(i==="REINFORCEMENT_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec"],vO(I))}let s=p(t,["tunedModelDisplayName"]);e!==void 0&&s!=null&&h(e,["tunedModelDisplayName"],s);let o=p(t,["description"]);e!==void 0&&o!=null&&h(e,["description"],o);let a=p(n,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","epochCount"],I)}else if(a==="PREFERENCE_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],I)}else if(a==="DISTILLATION"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","epochCount"],I)}else if(a==="REINFORCEMENT_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","epochCount"],I)}let c=p(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="PREFERENCE_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="DISTILLATION"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="REINFORCEMENT_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],I)}let l=p(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","exportLastCheckpointOnly"],I)}else if(l==="PREFERENCE_TUNING"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],I)}else if(l==="DISTILLATION"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["distillationSpec","exportLastCheckpointOnly"],I)}let u=p(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","adapterSize"],I)}else if(u==="PREFERENCE_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],I)}else if(u==="DISTILLATION"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","adapterSize"],I)}else if(u==="REINFORCEMENT_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],I)}let d=p(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let I=p(t,["tuningMode"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","tuningMode"],I)}else if(d==="DISTILLATION"){let I=p(t,["tuningMode"]);e!==void 0&&I!=null&&h(e,["distillationSpec","tuningMode"],I)}let f=p(t,["customBaseModel"]);e!==void 0&&f!=null&&h(e,["customBaseModel"],f);let m=p(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","batchSize"],I)}else if(m==="DISTILLATION"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","batchSize"],I)}else if(m==="REINFORCEMENT_TUNING"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","batchSize"],I)}let g=p(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){let I=p(t,["learningRate"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","learningRate"],I)}else if(g==="DISTILLATION"){let I=p(t,["learningRate"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","learningRate"],I)}let y=p(t,["labels"]);e!==void 0&&y!=null&&h(e,["labels"],y);let w=p(t,["beta"]);e!==void 0&&w!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","beta"],w);let S=p(t,["baseTeacherModel"]);e!==void 0&&S!=null&&h(e,["distillationSpec","baseTeacherModel"],S);let T=p(t,["tunedTeacherModelSource"]);e!==void 0&&T!=null&&h(e,["distillationSpec","tunedTeacherModelSource"],T);let R=p(t,["sftLossWeightMultiplier"]);e!==void 0&&R!=null&&h(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],R);let C=p(t,["outputUri"]);e!==void 0&&C!=null&&h(e,["outputUri"],C);let D=p(t,["rewardConfig"]);e!==void 0&&D!=null&&h(e,["reinforcementTuningSpec","singleRewardConfig"],D);let $=p(t,["compositeRewardConfig"]);e!==void 0&&$!=null&&h(e,["reinforcementTuningSpec","compositeRewardConfig"],$);let G=p(t,["samplesPerPrompt"]);e!==void 0&&G!=null&&h(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],G);let V=p(t,["evaluateInterval"]);e!==void 0&&V!=null&&h(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],V);let L=p(t,["checkpointInterval"]);e!==void 0&&L!=null&&h(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],L);let k=p(t,["maxOutputTokens"]);e!==void 0&&k!=null&&h(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],k);let E=p(t,["thinkingLevel"]);e!==void 0&&E!=null&&h(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],E);let A=p(t,["validationDatasetUri"]);e!==void 0&&A!=null&&h(e,["reinforcementTuningSpec","validationDatasetUri"],A);let M=p(t,["encryptionSpec"]);return e!==void 0&&M!=null&&h(e,["encryptionSpec"],M),r}function Cmt(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["preTunedModel"]);i!=null&&h(n,["preTunedModel"],i);let s=p(t,["trainingDataset"]);s!=null&&qmt(s);let o=p(t,["config"]);return o!=null&&Tmt(o,n),n}function Rmt(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["preTunedModel"]);i!=null&&h(n,["preTunedModel"],i);let s=p(t,["trainingDataset"]);s!=null&&$mt(s,n,e);let o=p(t,["config"]);return o!=null&&Amt(o,n,e),n}function wAe(t,e){let n={},r=p(t,["epochCount"]);r!=null&&h(n,["epochCount"],r);let i=p(t,["learningRateMultiplier"]);i!=null&&h(n,["learningRateMultiplier"],i);let s=p(t,["adapterSize"]);s!=null&&h(n,["adapterSize"],s);let o=p(t,["batchSize"]);o!=null&&h(n,["batchSize"],o);let a=p(t,["learningRate"]);a!=null&&h(n,["learningRate"],a);let c=p(t,["generationConfig"]);return c!=null&&h(n,["generationConfig"],Pmt(c)),n}function Imt(t,e){let n={},r=p(t,["promptDatasetUri"]);r!=null&&h(n,["promptDatasetUri"],r);let i=p(t,["validationDatasetUri"]);i!=null&&h(n,["validationDatasetUri"],i);let s=p(t,["baseTeacherModel"]);s!=null&&h(n,["baseTeacherModel"],s);let o=p(t,["tunedTeacherModelSource"]);o!=null&&h(n,["tunedTeacherModelSource"],o);let a=p(t,["hyperparameters"]);return a!=null&&h(n,["hyperparameters"],wAe(a)),n}function kmt(t,e){let n={},r=p(t,["baseTeacherModel"]);r!=null&&h(n,["baseTeacherModel"],r);let i=p(t,["hyperParameters"]);i!=null&&h(n,["hyperParameters"],wAe(i));let s=p(t,["pipelineRootDirectory"]);s!=null&&h(n,["pipelineRootDirectory"],s);let o=p(t,["promptDatasetUri"]);o!=null&&h(n,["promptDatasetUri"],o);let a=p(t,["studentModel"]);a!=null&&h(n,["studentModel"],a);let c=p(t,["trainingDatasetUri"]);c!=null&&h(n,["trainingDatasetUri"],c);let l=p(t,["tunedTeacherModelSource"]);l!=null&&h(n,["tunedTeacherModelSource"],l);let u=p(t,["tuningMode"]);u!=null&&h(n,["tuningMode"],u);let d=p(t,["validationDatasetUri"]);return d!=null&&h(n,["validationDatasetUri"],d),n}function Pmt(t,e){let n={},r=p(t,["modelConfig"]);r!=null&&h(n,["modelSelectionConfig"],r);let i=p(t,["responseJsonSchema"]);i!=null&&h(n,["responseJsonSchema"],i);let s=p(t,["audioTranscriptionConfig"]);s!=null&&h(n,["audioTranscriptionConfig"],s);let o=p(t,["audioTimestamp"]);o!=null&&h(n,["audioTimestamp"],o);let a=p(t,["candidateCount"]);a!=null&&h(n,["candidateCount"],a);let c=p(t,["enableAffectiveDialog"]);c!=null&&h(n,["enableAffectiveDialog"],c);let l=p(t,["frequencyPenalty"]);l!=null&&h(n,["frequencyPenalty"],l);let u=p(t,["logprobs"]);u!=null&&h(n,["logprobs"],u);let d=p(t,["maxOutputTokens"]);d!=null&&h(n,["maxOutputTokens"],d);let f=p(t,["mediaResolution"]);f!=null&&h(n,["mediaResolution"],f);let m=p(t,["presencePenalty"]);m!=null&&h(n,["presencePenalty"],m);let g=p(t,["responseFormat"]);if(g!=null){let E=g;Array.isArray(E)&&(E=E.map(A=>A)),h(n,["responseFormat"],E)}let y=p(t,["responseLogprobs"]);y!=null&&h(n,["responseLogprobs"],y);let w=p(t,["responseMimeType"]);w!=null&&h(n,["responseMimeType"],w);let S=p(t,["responseModalities"]);S!=null&&h(n,["responseModalities"],S);let T=p(t,["responseSchema"]);T!=null&&h(n,["responseSchema"],T);let R=p(t,["routingConfig"]);R!=null&&h(n,["routingConfig"],R);let C=p(t,["seed"]);C!=null&&h(n,["seed"],C);let D=p(t,["speechConfig"]);D!=null&&h(n,["speechConfig"],D);let $=p(t,["stopSequences"]);$!=null&&h(n,["stopSequences"],$);let G=p(t,["temperature"]);G!=null&&h(n,["temperature"],G);let V=p(t,["thinkingConfig"]);V!=null&&h(n,["thinkingConfig"],V);let L=p(t,["topK"]);L!=null&&h(n,["topK"],L);let k=p(t,["topP"]);return k!=null&&h(n,["topP"],k),n}function Omt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Mmt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Nmt(t,e,n){let r={},i=p(t,["pageSize"]);e!==void 0&&i!=null&&h(e,["_query","pageSize"],i);let s=p(t,["pageToken"]);e!==void 0&&s!=null&&h(e,["_query","pageToken"],s);let o=p(t,["filter"]);return e!==void 0&&o!=null&&h(e,["_query","filter"],o),r}function Dmt(t,e){let n={},r=p(t,["config"]);return r!=null&&Nmt(r,n),n}function Lmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["tuningJobs"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(a=>gz(a))),h(n,["tuningJobs"],o)}return n}function Umt(t,e){let n={},r=p(t,["mediaResolution"]);if(r!=null&&h(n,["mediaResolution"],r),p(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(p(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=p(t,["audioTranscription"]);i!=null&&h(n,["audioTranscription"],i);let s=p(t,["codeExecutionResult"]);s!=null&&h(n,["codeExecutionResult"],s);let o=p(t,["executableCode"]);o!=null&&h(n,["executableCode"],o);let a=p(t,["fileData"]);a!=null&&h(n,["fileData"],a);let c=p(t,["functionCall"]);c!=null&&h(n,["functionCall"],c);let l=p(t,["functionResponse"]);l!=null&&h(n,["functionResponse"],l);let u=p(t,["inlineData"]);u!=null&&h(n,["inlineData"],u);let d=p(t,["text"]);d!=null&&h(n,["text"],d);let f=p(t,["thought"]);f!=null&&h(n,["thought"],f);let m=p(t,["thoughtSignature"]);m!=null&&h(n,["thoughtSignature"],m);let g=p(t,["videoMetadata"]);if(g!=null&&h(n,["videoMetadata"],g),p(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 y=p(t,["mediaProcessing"]);return y!=null&&h(n,["mediaProcessing"],y),n}function Fmt(t,e){let n={},r=p(t,["references"]);r!=null&&h(n,["references"],r);let i=p(t,["contents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>mz(a))),h(n,["contents"],o)}let s=p(t,["systemInstruction"]);return s!=null&&h(n,["systemInstruction"],mz(s)),n}function Bmt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["model"],r);let i=p(t,["name"]);return i!=null&&h(n,["endpoint"],i),n}function qmt(t,e){let n={};if(p(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(p(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=p(t,["examples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(n,["examples","examples"],i)}return n}function $mt(t,e,n){let r={},i=p(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(i==="PREFERENCE_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(i==="DISTILLATION"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["distillationSpec","promptDatasetUri"],o)}else if(i==="REINFORCEMENT_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["reinforcementTuningSpec","trainingDatasetUri"],o)}let s=p(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(s==="PREFERENCE_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(s==="DISTILLATION"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["distillationSpec","promptDatasetUri"],o)}else if(s==="REINFORCEMENT_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["reinforcementTuningSpec","trainingDatasetUri"],o)}if(p(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 Gmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["state"]);s!=null&&h(n,["state"],eTe(s));let o=p(t,["createTime"]);o!=null&&h(n,["createTime"],o);let a=p(t,["tuningTask","startTime"]);a!=null&&h(n,["startTime"],a);let c=p(t,["tuningTask","completeTime"]);c!=null&&h(n,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(n,["updateTime"],l);let u=p(t,["description"]);u!=null&&h(n,["description"],u);let d=p(t,["baseModel"]);d!=null&&h(n,["baseModel"],d);let f=p(t,["_self"]);return f!=null&&h(n,["tunedModel"],Bmt(f)),n}function gz(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["state"]);s!=null&&h(n,["state"],eTe(s));let o=p(t,["createTime"]);o!=null&&h(n,["createTime"],o);let a=p(t,["startTime"]);a!=null&&h(n,["startTime"],a);let c=p(t,["endTime"]);c!=null&&h(n,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(n,["updateTime"],l);let u=p(t,["error"]);u!=null&&h(n,["error"],u);let d=p(t,["description"]);d!=null&&h(n,["description"],d);let f=p(t,["baseModel"]);f!=null&&h(n,["baseModel"],f);let m=p(t,["tunedModel"]);m!=null&&h(n,["tunedModel"],m);let g=p(t,["preTunedModel"]);g!=null&&h(n,["preTunedModel"],g);let y=p(t,["supervisedTuningSpec"]);y!=null&&h(n,["supervisedTuningSpec"],y);let w=p(t,["preferenceOptimizationSpec"]);w!=null&&h(n,["preferenceOptimizationSpec"],w);let S=p(t,["distillationSamplingSpec"]);S!=null&&h(n,["distillationSamplingSpec"],Imt(S));let T=p(t,["distillationSpec"]);T!=null&&h(n,["distillationSpec"],kmt(T));let R=p(t,["reinforcementTuningSpec"]);R!=null&&h(n,["reinforcementTuningSpec"],R);let C=p(t,["tuningDataStats"]);C!=null&&h(n,["tuningDataStats"],C);let D=p(t,["encryptionSpec"]);D!=null&&h(n,["encryptionSpec"],D);let $=p(t,["partnerModelTuningSpec"]);$!=null&&h(n,["partnerModelTuningSpec"],$);let G=p(t,["customBaseModel"]);G!=null&&h(n,["customBaseModel"],G);let V=p(t,["evaluateDatasetRuns"]);if(V!=null){let q=V;Array.isArray(q)&&(q=q.map(pe=>pe)),h(n,["evaluateDatasetRuns"],q)}let L=p(t,["experiment"]);L!=null&&h(n,["experiment"],L);let k=p(t,["fullFineTuningSpec"]);k!=null&&h(n,["fullFineTuningSpec"],k);let E=p(t,["labels"]);E!=null&&h(n,["labels"],E);let A=p(t,["outputUri"]);A!=null&&h(n,["outputUri"],A);let M=p(t,["pipelineJob"]);M!=null&&h(n,["pipelineJob"],M);let I=p(t,["serviceAccount"]);I!=null&&h(n,["serviceAccount"],I);let P=p(t,["tunedModelDisplayName"]);P!=null&&h(n,["tunedModelDisplayName"],P);let F=p(t,["tuningJobMetadata"]);F!=null&&h(n,["tuningJobMetadata"],F);let X=p(t,["tuningJobState"]);X!=null&&h(n,["tuningJobState"],X);let N=p(t,["veoLoraTuningSpec"]);N!=null&&h(n,["veoLoraTuningSpec"],N);let b=p(t,["veoTuningSpec"]);return b!=null&&h(n,["veoTuningSpec"],b),n}function Hmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["metadata"]);s!=null&&h(n,["metadata"],s);let o=p(t,["done"]);o!=null&&h(n,["done"],o);let a=p(t,["error"]);return a!=null&&h(n,["error"],a),n}function vO(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["validationDatasetUri"],r);let i=p(t,["vertexDatasetResource"]);return i!=null&&h(n,["validationDatasetUri"],i),n}function jmt(t,e){let n={},r=p(t,["parent"]);r!=null&&h(n,["_url","parent"],r);let i=p(t,["sampleResponse"]);i!=null&&h(n,["sampleResponse"],mz(i));let s=p(t,["example"]);s!=null&&h(n,["example"],Fmt(s));let o=p(t,["singleRewardConfig"]);o!=null&&h(n,["singleRewardConfig"],o);let a=p(t,["compositeRewardConfig"]);return a!=null&&h(n,["compositeRewardConfig"],a),n}function Wmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["overallReward"]);i!=null&&h(n,["overallReward"],i);let s=p(t,["error"]);s!=null&&h(n,["error"],s);let o=p(t,["rewardInfoDetails"]);return o!=null&&h(n,["rewardInfoDetails"],o),n}async function Vmt(t,e,n,r){var i;let s=await AAe(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return o.file}async function zmt(t,e,n,r){var i;let s=await AAe(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Sz(o),c=new ix;return Object.assign(c,a),c}async function AAe(t,e,n,r){var i,s,o;let a=e,c=r?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(c){let m=new URL(c),g=new URL(e);g.protocol=m.protocol,g.host=m.host,g.port=m.port,a=g.toString()}let l=0,u=0,d=new Vu(new Response),f="upload";for(l=t.size;u<l;){let m=Math.min(SAe,l-u),g=t.slice(u,u+m);u+m>=l&&(f+=", finalize");let y=0,w=bAe;for(;y<xAe;){let S=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":f,"X-Goog-Upload-Offset":String(u)});if(d=await n.request({path:"",body:g,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:a,headers:S})}),!((s=d?.headers)===null||s===void 0)&&s[qf])break;y++,await CAe(w),w=w*TAe}if(u+=m,((o=d?.headers)===null||o===void 0?void 0:o[qf])!=="active")break;if(l<=u)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}async function Kmt(t){return{size:t.size,type:t.type}}function CAe(t){return new Promise(e=>setTimeout(e,t))}function Xmt(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=$f("GOOGLE_GENAI_USE_ENTERPRISE"),r=$f("GOOGLE_GENAI_USE_VERTEXAI"),i=Fbe(n),s=Fbe(r);return n!==void 0&&r!==void 0&&i!==s&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?i:r!==void 0?s:!1}function $f(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 Fbe(t){return t===void 0?!1:t.toLowerCase()==="true"}function Jmt(){let t=$f("GOOGLE_API_KEY"),e=$f("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}var Bbe,qbe,$be,s1,Gbe,Hbe,jbe,Wbe,Vbe,zbe,ic,S3,x3,b3,Wu,T3,A3,C3,R3,I3,k3,P3,O3,M3,N3,D3,L3,U3,F3,B3,q3,$3,G3,H3,j3,W3,V3,z3,K3,zS,Y3,X3,J3,Q3,Z3,e6,t6,n6,SO,r6,i6,s6,o6,a6,c6,l6,u6,d6,f6,p6,xO,h6,KS,m6,g6,y6,_6,v6,E6,w6,S6,x6,b6,T6,A6,C6,R6,I6,k6,P6,O6,M6,N6,D6,L6,U6,F6,B6,gm,q6,$6,G6,H6,j6,Vu,V6,z6,Bf,YS,bO,TO,AO,CO,RO,XS,JS,K6,Y6,X6,J6,Q6,QS,IO,Z6,ZS,eV,tV,nV,kO,ex,PO,tx,nx,OO,MO,NO,rV,DO,LO,UO,FO,BO,iV,sV,oV,rx,aV,cV,lV,uV,dV,fV,pV,qO,hV,mV,$O,gV,ix,pl,hl,HO,jO,WO,VO,sx,uTe,Oft,Mft,Nft,wV,Dft,Lft,Uft,Fft,Bft,Gft,Hft,jft,Wft,Vft,zft,SV,Yft,wTe,ox,xV,bV,rpt,zO,spt,KO,_be,_m,YO,XO,TV,AV,gO,CV,RV,Gf,JO,dv,QO,ZO,e1,na,IV,ys,kV,mv,PV,OV,MV,NV,DV,LV,UV,FV,BV,zpt,t1,Abe,Kpt,n1,eht,Rbe,nht,sht,kTe,De,cc,Ibe,cx,jf,uht,yO,hht,mht,sc,FTe,Pbe,r1,qV,ea,ta,BTe,vht,Sht,xht,Mbe,$V,GTe,At,GV,HV,jV,WV,VV,zV,KV,YV,XV,JV,QV,ZV,ez,tz,nz,rz,amt,cmt,iz,sz,oz,az,cz,lz,uz,Ube,WS,dz,fz,pz,hz,yz,SAe,xAe,bAe,TAe,qf,_z,vz,Ymt,Ez,IAe=ae(()=>{Bbe=ce(uEe(),1),qbe=ce(exe(),1),$be=require("fs"),s1=ce(require("fs/promises"),1),Gbe=require("fs/promises"),Hbe=require("node:stream"),jbe=require("node:stream/promises");ibe();Wbe=ce(require("path"),1);ic=class{};(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(S3||(S3={}));(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(x3||(x3={}));(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(b3||(b3={}));(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"})(Wu||(Wu={}));(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"})(T3||(T3={}));(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"})(A3||(A3={}));(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(C3||(C3={}));(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(R3||(R3={}));(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"})(I3||(I3={}));(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"})(k3||(k3={}));(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(P3||(P3={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(O3||(O3={}));(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(M3||(M3={}));(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(N3||(N3={}));(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(D3||(D3={}));(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"})(L3||(L3={}));(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(U3||(U3={}));(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"})(F3||(F3={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(B3||(B3={}));(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"})(q3||(q3={}));(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})($3||($3={}));(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"})(G3||(G3={}));(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"})(H3||(H3={}));(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"})(j3||(j3={}));(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(W3||(W3={}));(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(V3||(V3={}));(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"})(z3||(z3={}));(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"})(K3||(K3={}));(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(zS||(zS={}));(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(Y3||(Y3={}));(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"})(X3||(X3={}));(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"})(J3||(J3={}));(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"})(Q3||(Q3={}));(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"})(Z3||(Z3={}));(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(e6||(e6={}));(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})(t6||(t6={}));(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(n6||(n6={}));(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"})(SO||(SO={}));(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"})(r6||(r6={}));(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"})(i6||(i6={}));(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(s6||(s6={}));(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(o6||(o6={}));(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(a6||(a6={}));(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"})(c6||(c6={}));(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(l6||(l6={}));(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(u6||(u6={}));(function(t){t.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",t.STATIC="STATIC",t.AGENTIC="AGENTIC"})(d6||(d6={}));(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"})(f6||(f6={}));(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"})(p6||(p6={}));(function(t){t.COLLECTION="COLLECTION"})(xO||(xO={}));(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(h6||(h6={}));(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(KS||(KS={}));(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"})(m6||(m6={}));(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"})(g6||(g6={}));(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"})(y6||(y6={}));(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"})(_6||(_6={}));(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"})(v6||(v6={}));(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"})(E6||(E6={}));(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(w6||(w6={}));(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(S6||(S6={}));(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(x6||(x6={}));(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(b6||(b6={}));(function(t){t.CROP="CROP",t.PAD="PAD"})(T6||(T6={}));(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(A6||(A6={}));(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(C6||(C6={}));(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(R6||(R6={}));(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"})(I6||(I6={}));(function(t){t.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",t.IN_PROGRESS="IN_PROGRESS",t.REQUIRES_ACTION="REQUIRES_ACTION",t.IDLE="IDLE"})(k6||(k6={}));(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"})(P6||(P6={}));(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(O6||(O6={}));(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(M6||(M6={}));(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(N6||(N6={}));(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(D6||(D6={}));(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"})(L6||(L6={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.VERBATIM="VERBATIM",t.SMART="SMART"})(U6||(U6={}));(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"})(F6||(F6={}));(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(B6||(B6={}));(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(gm||(gm={}));q6=class{},$6=class{},G6=class{},H6=class{};j6=class{};Vu=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()}},V6=class{},z6=class{},Bf=class{get text(){var e,n,r,i,s,o,a,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 l="",u=!1,d=[];for(let f of(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)!==null&&c!==void 0?c:[]){for(let[m,g]of Object.entries(f))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(g!==null||g!==void 0)&&d.push(m);if(typeof f.text=="string"){if(typeof f.thought=="boolean"&&f.thought)continue;u=!0,l+=f.text}}return d.length>0&&console.warn(`there are non-text parts ${d} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,n,r,i,s,o,a,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 l="",u=[];for(let d of(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)!==null&&c!==void 0?c:[]){for(let[f,m]of Object.entries(d))f!=="inlineData"&&(m!==null||m!==void 0)&&u.push(f);d.inlineData&&typeof d.inlineData.data=="string"&&(l+=atob(d.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,n,r,i,s,o,a,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 l=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(u=>u.functionCall).map(u=>u.functionCall).filter(u=>u!==void 0);if(l?.length!==0)return l}get executableCode(){var e,n,r,i,s,o,a,c,l;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 u=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(d=>d.executableCode).map(d=>d.executableCode).filter(d=>d!==void 0);if(u?.length!==0)return(l=u?.[0])===null||l===void 0?void 0:l.code}get codeExecutionResult(){var e,n,r,i,s,o,a,c,l;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 u=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(d=>d.codeExecutionResult).map(d=>d.codeExecutionResult).filter(d=>d!==void 0);if(u?.length!==0)return(l=u?.[0])===null||l===void 0?void 0:l.output}},YS=class{},bO=class{},TO=class{},AO=class{},CO=class{},RO=class{},XS=class{},JS=class{},K6=class{},Y6=class{},X6=class{},J6=class{},Q6=class{},QS=class{},IO=class{},Z6=class{},ZS=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,i,s=e;return n?i=Mat(s):i=Oat(s),Object.assign(r,i),r}},eV=class{},tV=class{},nV=class{},kO=class{},ex=class{},PO=class{},tx=class{},nx=class{},OO=class{},MO=class{},NO=class{},rV=class{},DO=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=qat(e);return Object.assign(r,s),r}},LO=class{},UO=class{},FO=class{},BO=class{},iV=class{},sV=class{},oV=class{},rx=class{},aV=class{},cV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},lV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},uV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},dV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},fV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},pV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},qO=class{get text(){var e,n,r;let i="",s=!1,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[c,l]of Object.entries(a))c!=="text"&&c!=="thought"&&l!==null&&o.push(c);if(typeof a.text=="string"){if(typeof a.thought=="boolean"&&a.thought)continue;s=!0,i+=a.text}}return o.length>0&&console.warn(`there are non-text parts ${o} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),s?i:void 0}get data(){var e,n,r;let i="",s=[];for(let o 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[a,c]of Object.entries(o))a!=="inlineData"&&c!==null&&s.push(a);o.inlineData&&typeof o.inlineData.data=="string"&&(i+=atob(o.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}},hV=class{},mV=class{constructor(){this.functionResponses=[]}},$O=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},gV=class{},ix=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=Sz(e);return Object.assign(r,s),r}};(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"})(pl||(pl={}));hl=class{constructor(e,n,r,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,r,i)}init(e,n,r){var i,s;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let o={config:{}};!r||Object.keys(r).length===0?o={config:{}}:typeof r=="object"?o=Object.assign({},r):o=r,o.config&&(o.config.pageToken=n.nextPageToken),this.paramsInternal=o,this.pageInternalSize=(s=(i=o.config)===null||i===void 0?void 0:i.pageSize)!==null&&s!==void 0?s:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};HO=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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=lbe(this.apiClient,e),r=n._url,i=Ce("{model}:batchGenerateContent",r),a=n.batch.inputConfig.requests,c=a.requests,l=[];for(let u of c){let d=Object.assign({},u);if(d.systemInstruction){let f=d.systemInstruction;delete d.systemInstruction;let m=d.request;m.systemInstruction=f,d.request=m}l.push(d)}return a.requests=l,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 s=this.getGcsUri(e),o=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?r.dest=`${s.slice(0,-6)}/dest`:r.dest=`${s}_dest_${i}`;else if(o)r.dest=`${o}_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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=xct(this.apiClient,e);return a=Ce("batchPredictionJobs",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>_V(u))}else{let l=lbe(this.apiClient,e);return a=Ce("{model}:batchGenerateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>EO(u))}}async createEmbeddingsInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Tct(this.apiClient,e);return s=Ce("{model}:asyncBatchEmbedContent",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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=>EO(c))}}async get(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Bct(this.apiClient,e);return a=Ce("batchPredictionJobs/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>_V(u))}else{let l=Fct(this.apiClient,e);return a=Ce("batches/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>EO(u))}}async cancel(e){var n,r,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let c=_ct(this.apiClient,e);o=Ce("batchPredictionJobs/{name}:cancel",c._url),a=c._query,delete c._url,delete c._query,await 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})}else{let c=yct(this.apiClient,e);o=Ce("batches/{name}:cancel",c._url),a=c._query,delete c._url,delete c._query,await this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Kct(e);return a=Ce("batchPredictionJobs",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Xct(u),f=new rx;return Object.assign(f,d),f})}else{let l=zct(e);return a=Ce("batches",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Yct(u),f=new rx;return Object.assign(f,d),f})}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Cct(this.apiClient,e);return a=Ce("batchPredictionJobs/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Ict(u))}else{let l=Act(this.apiClient,e);return a=Ce("batches/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Rct(u))}}};jO=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=llt(this.apiClient,e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=clt(this.apiClient,e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async get(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=_lt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=ylt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=dlt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=plt(u),f=new tx;return Object.assign(f,d),f})}else{let l=ult(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=flt(u),f=new tx;return Object.assign(f,d),f})}}async update(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Ult(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=Llt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=blt(e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Alt(u),f=new nx;return Object.assign(f,d),f})}else{let l=xlt(e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Tlt(u),f=new nx;return Object.assign(f,d),f})}}};WO=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new VO(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},VO=class{constructor(e,n,r,i={},s=[]){this.apiClient=e,this.modelsModule=n,this.model=r,this.config=i,this.history=s,this.sendPromise=Promise.resolve(),Blt(s)}async sendMessage(e){var n;await this.sendPromise;let r=Qr(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 s,o,a;let c=await i,l=(o=(s=c.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content,u=c.automaticFunctionCallingHistory,d=this.getHistory(!0).length,f=[];u!=null&&(f=(a=u.slice(d))!==null&&a!==void 0?a:[]);let m=l?[l]:[];this.recordHistory(r,m,f)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let r=Qr(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 s=await i;return this.processStreamResponse(s,r)}getHistory(e=!1){let n=e?pbe(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return pv(this,arguments,function*(){var i,s,o,a,c,l;let u=[];try{for(var d=!0,f=VS(e),m;m=yield Hn(f.next()),i=m.done,!i;d=!0){a=m.value,d=!1;let g=a;if(Flt(g)){let y=(l=(c=g.candidates)===null||c===void 0?void 0:c[0])===null||l===void 0?void 0:l.content;y!==void 0&&u.push(y)}yield yield Hn(g)}}catch(g){s={error:g}}finally{try{!d&&!i&&(o=f.return)&&(yield Hn(o.call(f)))}finally{if(s)throw s.error}}this.recordHistory(n,u)})}recordHistory(e,n,r){let i=[];n.length>0&&n.every(s=>s.role!==void 0)?i=n:i.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...pbe(r)):this.history.push(e),this.history.push(...i)}};sx=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}};uTe=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=zlt(e);return s=Ce("files",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Klt(c),u=new LO;return Object.assign(u,l),u})}}async createInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=qlt(e);return s=Ce("upload/v1beta/files",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=$lt(c),u=new UO;return Object.assign(u,l),u})}}async get(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=jlt(e);return s=Ce("files/{file}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Glt(e);return s=Ce("files/{file}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,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}).then(c=>c.json().then(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Hlt(c),u=new FO;return Object.assign(u,l),u})}}async registerFilesInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Wlt(e);return s=Ce("files:register",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ylt(c),u=new BO;return Object.assign(u,l),u})}}};Oft="Content-Type",Mft="X-Server-Timeout",Nft="User-Agent",wV="x-goog-api-client",Dft="2.23.0",Lft=`google-genai-sdk/${Dft}`,Uft="v1beta1",Fft="v1beta",Bft=new Set(["us","eu"]);Gft=5,Hft=1,jft=60,Wft=2,Vft=1,zft=[408,429,500,502,503,504],SV=class{constructor(e){var n,r,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let s={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let a=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!a?(s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?s.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Bft.has(this.clientOptions.location)?s.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(s.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),s.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:Uft}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),s.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Fft,s.baseUrl="https://generativelanguage.googleapis.com/";s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}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.")}constructUrl(e,n,r){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===xO.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[o,a]of Object.entries(e.queryParams))i.searchParams.append(o,String(a));let s={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString()),this.unaryApiCall(i,s,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,s]of Object.entries(n))typeof s=="object"?r[i]=Object.assign(Object.assign({},r[i]),s):s!==void 0&&(r[i]=s);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 s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString()),this.streamApiCall(i,s,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}async includeExtraHttpOptionsToRequestInit(e,n,r){return n?.timeout&&n.timeout>0&&qft(n.timeout),n&&n.extraBody!==null&&Kft(e,n.extraBody),e.headers=await this.getHeadersInternal(n,r),e}async unaryApiCall(e,n,r,i,s,o,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,s,o,a).then(async c=>(await _3(c),new Vu(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,n,r,i,s,o,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,s,o,a).then(async c=>(await _3(c),this.processStreamResponse(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return pv(this,arguments,function*(){var r;let i=(r=e?.body)===null||r===void 0?void 0:r.getReader(),s=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let o="",a="data:",c=[`
523
+ `+n)}function mm(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,mm),t.emit("wsClientError",o,n,e)}else HS(n,r,i,s)}});var vat,Eat,wat,Sat,xat,bat,yW,Tat,ibe=ae(()=>{vat=ce(Yxe(),1),Eat=ce(uO(),1),wat=ce(iv(),1),Sat=ce(oW(),1),xat=ce(lW(),1),bat=ce(mW(),1),yW=ce(hO(),1),Tat=ce(rbe(),1)});var RAe={};yr(RAe,{ActivityHandling:()=>D6,AdapterSize:()=>ZW,AggregationMetric:()=>i6,ApiError:()=>sx,ApiSpec:()=>CW,AspectRatio:()=>XW,AudioResponseFormat:()=>K6,AudioTranscriptionConfigMode:()=>U6,AuthType:()=>TW,Batches:()=>HO,Behavior:()=>PW,BlockedReason:()=>jW,Caches:()=>jO,CancelTuningJobResponse:()=>ex,Chat:()=>VO,Chats:()=>WO,ComputeTokensResponse:()=>IO,ContentReferenceImage:()=>pV,ControlReferenceImage:()=>uV,ControlReferenceType:()=>_6,CountTokensResponse:()=>QS,CreateFileResponse:()=>UO,DeleteCachedContentResponse:()=>tx,DeleteFileResponse:()=>FO,DeleteModelResponse:()=>JS,Delivery:()=>YW,DocumentState:()=>l6,DynamicRetrievalConfigMode:()=>OW,EditImageResponse:()=>TO,EditMode:()=>E6,EmbedContentResponse:()=>YS,EmbeddingApiType:()=>KS,EndSensitivity:()=>N6,Environment:()=>RW,EvaluateDatasetResponse:()=>nV,FeatureSelectionPreference:()=>h6,FileSource:()=>R6,FileState:()=>C6,Files:()=>uTe,FinishReason:()=>qW,FunctionCallingConfigMode:()=>BW,FunctionResponse:()=>j6,FunctionResponseBlob:()=>G6,FunctionResponseFileData:()=>$6,FunctionResponsePart:()=>H6,FunctionResponseScheduling:()=>bW,GenerateContentResponse:()=>Bf,GenerateContentResponsePromptFeedback:()=>V6,GenerateContentResponseUsageMetadata:()=>z6,GenerateImagesResponse:()=>bO,GenerateVideosOperation:()=>ZS,GenerateVideosResponse:()=>Z6,GoogleGenAI:()=>Ez,HarmBlockMethod:()=>UW,HarmBlockThreshold:()=>FW,HarmCategory:()=>LW,HarmProbability:()=>$W,HarmSeverity:()=>GW,HttpElementLocation:()=>AW,HttpResponse:()=>Vu,ImagePromptLanguage:()=>g6,ImageResizeMode:()=>T6,ImageResponseFormat:()=>Y6,ImageSize:()=>JW,ImportFileOperation:()=>DO,ImportFileResponse:()=>rV,InlinedEmbedContentResponse:()=>oV,InlinedResponse:()=>iV,InteractionStatus:()=>k6,JobState:()=>SO,Language:()=>xW,ListBatchJobsResponse:()=>rx,ListCachedContentsResponse:()=>nx,ListDocumentsResponse:()=>OO,ListFileSearchStoresResponse:()=>MO,ListFilesResponse:()=>LO,ListModelsResponse:()=>XS,ListTuningJobsResponse:()=>kO,Live:()=>zO,LiveClientToolResponse:()=>hV,LiveMusicPlaybackControl:()=>gm,LiveMusicServerMessage:()=>$O,LiveSendToolResponseParameters:()=>mV,LiveServerMessage:()=>qO,MaskReferenceImage:()=>lV,MaskReferenceMode:()=>y6,MatchOperation:()=>t6,MediaModality:()=>VW,MediaProcessing:()=>d6,MediaResolution:()=>KW,Modality:()=>zS,ModelStage:()=>zW,Models:()=>_m,MusicGenerationMode:()=>B6,Operations:()=>YO,Outcome:()=>SW,PagedItem:()=>pl,Pager:()=>hl,PairwiseChoice:()=>s6,PartMediaResolutionLevel:()=>f6,PersonGeneration:()=>NW,PhishBlockThreshold:()=>kW,ProminentPeople:()=>DW,RawReferenceImage:()=>cV,RecontextImageResponse:()=>CO,RegisterFilesResponse:()=>BO,ReinforcementTuningAutoraterScorerParsedResponseConversionScorer:()=>tV,ReinforcementTuningParseResponseConfig:()=>eV,ReinforcementTuningThinkingLevel:()=>n6,ReplayResponse:()=>aV,ResourceScope:()=>xO,ResponseFormat:()=>Q6,ResponseParseType:()=>e6,SafetyFilterLevel:()=>m6,SafetyPolicy:()=>IW,Scale:()=>F6,SegmentImageResponse:()=>RO,SegmentMode:()=>w6,ServiceTier:()=>u6,Session:()=>KO,SingleEmbedContentResponse:()=>sV,StartSensitivity:()=>M6,StyleReferenceImage:()=>dV,SubjectReferenceImage:()=>fV,SubjectReferenceType:()=>v6,TextResponseFormat:()=>X6,ThinkingLevel:()=>MW,Tokens:()=>XO,ToolResponse:()=>q6,ToolType:()=>p6,TrafficType:()=>WW,TuningJobState:()=>r6,TuningMethod:()=>A6,TuningMode:()=>QW,TuningSpeed:()=>a6,TuningTask:()=>c6,TurnCompleteReason:()=>I6,TurnCoverage:()=>L6,Type:()=>Wu,UploadToFileSearchStoreOperation:()=>ix,UploadToFileSearchStoreResponse:()=>gV,UploadToFileSearchStoreResumableResponse:()=>NO,UpscaleImageResponse:()=>AO,UrlRetrievalStatus:()=>HW,VadSignalType:()=>P6,ValidateRewardResponse:()=>PO,VideoCompressionQuality:()=>b6,VideoGenerationMaskMode:()=>x6,VideoGenerationReferenceType:()=>S6,VideoOrientation:()=>o6,VideoResponseFormat:()=>J6,VoiceActivityType:()=>O6,createFunctionResponsePartFromBase64:()=>Wat,createFunctionResponsePartFromUri:()=>Vat,createModelContent:()=>ect,createPartFromBase64:()=>Xat,createPartFromCodeExecutionResult:()=>Jat,createPartFromExecutableCode:()=>Qat,createPartFromFunctionCall:()=>Kat,createPartFromFunctionResponse:()=>Yat,createPartFromText:()=>W6,createPartFromUri:()=>zat,createUserContent:()=>Zat,mcpToTool:()=>Zft,setDefaultBaseUrls:()=>Cat});function Cat(t){Vbe=t.geminiUrl,zbe=t.vertexUrl}function Rat(){return{geminiUrl:Vbe,vertexUrl:zbe}}function Iat(t,e,n,r){var i,s;if(!t?.baseUrl){let o=Rat();return e?(i=o.vertexUrl)!==null&&i!==void 0?i:n:(s=o.geminiUrl)!==null&&s!==void 0?s:r}return t.baseUrl}function Ce(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(r,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let s=e[i];return s!=null?String(s):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}function h(t,e,n){for(let s=0;s<e.length-1;s++){let o=e[s];if(o.endsWith("[]")){let a=o.slice(0,-2);if(!(a in t))if(Array.isArray(n))t[a]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${o}`);if(Array.isArray(t[a])){let c=t[a];if(Array.isArray(n))for(let l=0;l<c.length;l++){let u=c[l];h(u,e.slice(s+1),n[l])}else for(let l of c)h(l,e.slice(s+1),n)}return}else if(o.endsWith("[0]")){let a=o.slice(0,-3);a in t||(t[a]=[{}]);let c=t[a];h(c[0],e.slice(s+1),n);return}(!t[o]||typeof t[o]!="object")&&(t[o]={}),t=t[o]}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 p(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 s=i.slice(0,-2);if(s in t){let o=t[s];return Array.isArray(o)?o.map(a=>p(a,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 kat(t,e){for(let[n,r]of Object.entries(e)){let i=n.split("."),s=r.split("."),o=new Set,a=-1;for(let c=0;c<i.length;c++)if(i[c]==="*"){a=c;break}if(a!==-1&&s.length>a)for(let c=a;c<s.length;c++){let l=s[c];l!=="*"&&!l.endsWith("[]")&&!l.endsWith("[0]")&&o.add(l)}wW(t,i,s,0,o)}}function wW(t,e,n,r,i){if(r>=e.length||typeof t!="object"||t===null)return;let s=e[r];if(s.endsWith("[]")){let o=s.slice(0,-2),a=t;if(o in a&&Array.isArray(a[o]))for(let c of a[o])wW(c,e,n,r+1,i)}else if(s==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,a=Object.keys(o).filter(l=>!l.startsWith("_")&&!i.has(l)),c={};for(let l of a)c[l]=o[l];for(let[l,u]of Object.entries(c)){let d=[];for(let f of n.slice(r))f==="*"?d.push(l):d.push(f);h(o,d,u)}for(let l of a)delete o[l]}}else{let o=t;s in o&&wW(o[s],e,n,r+1,i)}}function wz(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function Pat(t){let e={},n=p(t,["operationName"]);n!=null&&h(e,["operationName"],n);let r=p(t,["resourceName"]);return r!=null&&h(e,["_url","resourceName"],r),e}function Oat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response","generateVideoResponse"]);return o!=null&&h(e,["response"],Nat(o)),e}function Mat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Dat(o)),e}function Nat(t){let e={},n=p(t,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>Lat(o))),h(e,["generatedVideos"],s)}let r=p(t,["raiMediaFilteredCount"]);r!=null&&h(e,["raiMediaFilteredCount"],r);let i=p(t,["raiMediaFilteredReasons"]);return i!=null&&h(e,["raiMediaFilteredReasons"],i),e}function Dat(t){let e={},n=p(t,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>Uat(o))),h(e,["generatedVideos"],s)}let r=p(t,["raiMediaFilteredCount"]);r!=null&&h(e,["raiMediaFilteredCount"],r);let i=p(t,["raiMediaFilteredReasons"]);return i!=null&&h(e,["raiMediaFilteredReasons"],i),e}function Lat(t){let e={},n=p(t,["video"]);return n!=null&&h(e,["video"],Hat(n)),e}function Uat(t){let e={},n=p(t,["_self"]);return n!=null&&h(e,["video"],jat(n)),e}function Fat(t){let e={},n=p(t,["operationName"]);return n!=null&&h(e,["_url","operationName"],n),e}function Bat(t){let e={},n=p(t,["operationName"]);return n!=null&&h(e,["_url","operationName"],n),e}function qat(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],$at(o)),e}function $at(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Sz(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Gat(o)),e}function Gat(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Hat(t){let e={},n=p(t,["uri"]);n!=null&&h(e,["uri"],n);let r=p(t,["encodedVideo"]);r!=null&&h(e,["videoBytes"],wz(r));let i=p(t,["encoding"]);return i!=null&&h(e,["mimeType"],i),e}function jat(t){let e={},n=p(t,["gcsUri"]);n!=null&&h(e,["uri"],n);let r=p(t,["bytesBase64Encoded"]);r!=null&&h(e,["videoBytes"],wz(r));let i=p(t,["mimeType"]);return i!=null&&h(e,["mimeType"],i),e}function Wat(t,e){return{inlineData:{data:t,mimeType:e}}}function Vat(t,e){return{fileData:{fileUri:t,mimeType:e}}}function zat(t,e,n){return Object.assign({fileData:{fileUri:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function W6(t){return{text:t}}function Kat(t,e){return{functionCall:{name:t,args:e}}}function Yat(t,e,n,r=[]){return{functionResponse:Object.assign({id:t,name:e,response:n},r.length>0&&{parts:r})}}function Xat(t,e,n){return Object.assign({inlineData:{data:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function Jat(t,e){return{codeExecutionResult:{outcome:t,output:e}}}function Qat(t,e){return{executableCode:{code:t,language:e}}}function sbe(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 Kbe(t){let e=[];if(typeof t=="string")e.push(W6(t));else if(sbe(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(W6(n));else if(sbe(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 Zat(t){return{role:"user",parts:Kbe(t)}}function ect(t){return{role:"model",parts:Kbe(t)}}function Kt(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 Ybe(t,e){let n=Kt(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 Xbe(t){return Array.isArray(t)?t.map(e=>GO(e)):[GO(t)]}function GO(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function Jbe(t){let e=GO(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Qbe(t){let e=GO(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function obe(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 Zbe(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>obe(e)):[obe(t)]}function yV(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function abe(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function cbe(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function Qr(t){if(t==null)throw new Error("ContentUnion is required");return yV(t)?t:{role:"user",parts:Zbe(t)}}function xz(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let r=Qr(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(t.isVertexAI()){let n=Qr(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=>Qr(n)):[Qr(e)]}function gs(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(abe(t)||cbe(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Qr(t)]}let e=[],n=[],r=yV(t[0]);for(let i of t){let s=yV(i);if(s!=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(s)e.push(i);else{if(abe(i)||cbe(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:Zbe(n)}),e}function tct(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1)e.type=Object.values(Wu).includes(n[0].toUpperCase())?n[0].toUpperCase():Wu.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let r of n)e.anyOf.push({type:Object.values(Wu).includes(r.toUpperCase())?r.toUpperCase():Wu.TYPE_UNSPECIFIED})}}function fv(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 s=t.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type instanceof Array&&tct(t.type,e);for(let[o,a]of Object.entries(t))if(a!=null)if(o=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;e.type=Object.values(Wu).includes(a.toUpperCase())?a.toUpperCase():Wu.TYPE_UNSPECIFIED}else if(n.includes(o))e[o]=fv(a);else if(r.includes(o)){let c=[];for(let l of a){if(l.type=="null"){e.nullable=!0;continue}c.push(fv(l))}e[o]=c}else if(i.includes(o)){let c={};for(let[l,u]of Object.entries(a))c[l]=fv(u);e[o]=c}else{if(o==="additionalProperties")continue;e[o]=a}return e}function bz(t){return fv(t)}function Tz(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 Az(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function gv(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=fv(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=fv(e.response));return t}function yv(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 nct(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 zu(t,e){if(typeof e!="string")throw new Error("name must be a string");return nct(t,e,"cachedContents")}function eTe(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 vm(t){return wz(t)}function rct(t){return t!=null&&typeof t=="object"&&"name"in t}function tTe(t){return t!=null&&typeof t=="object"&&"video"in t}function nTe(t){return t!=null&&typeof t=="object"&&"uri"in t}function Cz(t){var e;let n;if(rct(t)&&(n=t.name),!(nTe(t)&&(n=t.uri,n===void 0))&&!(tTe(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 rTe(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function iTe(t){for(let e of["models","tunedModels","publisherModels"])if(ict(t,e))return t[e];return[]}function ict(t,e){return t!==null&&typeof t=="object"&&e in t}function sct(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 oct(t,e={}){let n=[],r=new Set;for(let i of t){let s=i.name;if(r.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);r.add(s);let o=sct(i,e);o.functionDeclarations&&n.push(...o.functionDeclarations)}return{functionDeclarations:n}}function sTe(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 act(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 oTe(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 s=!1;for(let o of i){if(typeof o!="object"||o===null)continue;let c=o.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function _v(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 aTe(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 cct(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function lct(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 uct(t){let e={},n=p(t,["responsesFile"]);n!=null&&h(e,["fileName"],n);let r=p(t,["inlinedResponses","inlinedResponses"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>jct(o))),h(e,["inlinedResponses"],s)}let i=p(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["inlinedEmbedContentResponses"],s)}return e}function dct(t){let e={},n=p(t,["predictionsFormat"]);n!=null&&h(e,["format"],n);let r=p(t,["gcsDestination","outputUriPrefix"]);r!=null&&h(e,["gcsUri"],r);let i=p(t,["bigqueryDestination","outputUri"]);i!=null&&h(e,["bigqueryUri"],i);let s=p(t,["vertexMultimodalDatasetDestination"]);return s!=null&&h(e,["vertexDataset"],tlt(s)),e}function fct(t){let e={},n=p(t,["format"]);n!=null&&h(e,["predictionsFormat"],n);let r=p(t,["gcsUri"]);r!=null&&h(e,["gcsDestination","outputUriPrefix"],r);let i=p(t,["bigqueryUri"]);i!=null&&h(e,["bigqueryDestination","outputUri"],i);let s=p(t,["vertexDataset"]);if(s!=null&&h(e,["vertexMultimodalDatasetDestination"],nlt(s)),p(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(p(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(p(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 EO(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata","displayName"]);r!=null&&h(e,["displayName"],r);let i=p(t,["metadata","state"]);i!=null&&h(e,["state"],aTe(i));let s=p(t,["metadata","createTime"]);s!=null&&h(e,["createTime"],s);let o=p(t,["metadata","endTime"]);o!=null&&h(e,["endTime"],o);let a=p(t,["metadata","updateTime"]);a!=null&&h(e,["updateTime"],a);let c=p(t,["metadata","model"]);c!=null&&h(e,["model"],c);let l=p(t,["metadata","output"]);return l!=null&&h(e,["dest"],uct(oTe(l))),e}function _V(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["displayName"]);r!=null&&h(e,["displayName"],r);let i=p(t,["state"]);i!=null&&h(e,["state"],aTe(i));let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["createTime"]);o!=null&&h(e,["createTime"],o);let a=p(t,["startTime"]);a!=null&&h(e,["startTime"],a);let c=p(t,["endTime"]);c!=null&&h(e,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(e,["updateTime"],l);let u=p(t,["model"]);u!=null&&h(e,["model"],u);let d=p(t,["inputConfig"]);d!=null&&h(e,["src"],pct(d));let f=p(t,["outputConfig"]);f!=null&&h(e,["dest"],dct(oTe(f)));let m=p(t,["outputInfo"]);m!=null&&h(e,["outputInfo"],m);let g=p(t,["completionStats"]);return g!=null&&h(e,["completionStats"],g),e}function pct(t){let e={},n=p(t,["instancesFormat"]);n!=null&&h(e,["format"],n);let r=p(t,["gcsSource","uris"]);r!=null&&h(e,["gcsUri"],r);let i=p(t,["bigquerySource","inputUri"]);i!=null&&h(e,["bigqueryUri"],i);let s=p(t,["vertexMultimodalDatasetSource","datasetName"]);return s!=null&&h(e,["vertexDatasetName"],s),e}function hct(t,e){let n={};if(p(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(p(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(p(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(p(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=p(e,["fileName"]);r!=null&&h(n,["fileName"],r);let i=p(e,["inlinedRequests"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>Hct(t,o))),h(n,["requests","requests"],s)}return n}function mct(t){let e={},n=p(t,["format"]);n!=null&&h(e,["instancesFormat"],n);let r=p(t,["gcsUri"]);r!=null&&h(e,["gcsSource","uris"],r);let i=p(t,["bigqueryUri"]);i!=null&&h(e,["bigquerySource","inputUri"],i);let s=p(t,["vertexDatasetName"]);if(s!=null&&h(e,["vertexMultimodalDatasetSource","datasetName"],s),p(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(p(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 gct(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function yct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function _ct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function vct(t){let e={},n=p(t,["content"]);n!=null&&h(e,["content"],n);let r=p(t,["citationMetadata"]);r!=null&&h(e,["citationMetadata"],Ect(r));let i=p(t,["tokenCount"]);i!=null&&h(e,["tokenCount"],i);let s=p(t,["finishReason"]);s!=null&&h(e,["finishReason"],s);let o=p(t,["groundingMetadata"]);o!=null&&h(e,["groundingMetadata"],o);let a=p(t,["avgLogprobs"]);a!=null&&h(e,["avgLogprobs"],a);let c=p(t,["index"]);c!=null&&h(e,["index"],c);let l=p(t,["logprobsResult"]);l!=null&&h(e,["logprobsResult"],l);let u=p(t,["safetyRatings"]);if(u!=null){let f=u;Array.isArray(f)&&(f=f.map(m=>m)),h(e,["safetyRatings"],f)}let d=p(t,["urlContextMetadata"]);return d!=null&&h(e,["urlContextMetadata"],d),e}function Ect(t){let e={},n=p(t,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),h(e,["citations"],r)}return e}function cTe(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Jct(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function wct(t,e){let n={},r=p(t,["displayName"]);if(e!==void 0&&r!=null&&h(e,["batch","displayName"],r),p(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=p(t,["webhookConfig"]);return e!==void 0&&i!=null&&h(e,["batch","webhookConfig"],i),n}function Sct(t,e){let n={},r=p(t,["displayName"]);e!==void 0&&r!=null&&h(e,["displayName"],r);let i=p(t,["dest"]);if(e!==void 0&&i!=null&&h(e,["outputConfig"],fct(act(i))),p(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 lbe(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["_url","model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["batch","inputConfig"],hct(t,sTe(t,i)));let s=p(e,["config"]);return s!=null&&wct(s,n),n}function xct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["inputConfig"],mct(sTe(t,i)));let s=p(e,["config"]);return s!=null&&Sct(s,n),n}function bct(t,e){let n={},r=p(t,["displayName"]);return e!==void 0&&r!=null&&h(e,["batch","displayName"],r),n}function Tct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["_url","model"],Kt(t,r));let i=p(e,["src"]);i!=null&&h(n,["batch","inputConfig"],Oct(t,i));let s=p(e,["config"]);return s!=null&&bct(s,n),n}function Act(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Cct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Rct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["name"]);r!=null&&h(e,["name"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);return s!=null&&h(e,["error"],s),e}function Ict(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["name"]);r!=null&&h(e,["name"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);return s!=null&&h(e,["error"],s),e}function kct(t,e){let n={},r=p(e,["contents"]);if(r!=null){let s=xz(t,r);Array.isArray(s)&&(s=s.map(o=>o)),h(n,["requests[]","request","content"],s)}let i=p(e,["config"]);return i!=null&&(h(n,["_self"],Pct(i,n)),kat(n,{"requests[].*":"requests[].request.*"})),n}function Pct(t,e){let n={},r=p(t,["taskType"]);e!==void 0&&r!=null&&h(e,["requests[]","taskType"],r);let i=p(t,["title"]);e!==void 0&&i!=null&&h(e,["requests[]","title"],i);let s=p(t,["outputDimensionality"]);if(e!==void 0&&s!=null&&h(e,["requests[]","outputDimensionality"],s),p(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(p(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(p(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(p(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 Oct(t,e){let n={},r=p(e,["fileName"]);r!=null&&h(n,["file_name"],r);let i=p(e,["inlinedRequests"]);return i!=null&&h(n,["requests"],kct(t,i)),n}function Mct(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function Nct(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 Dct(t){let e={},n=p(t,["allowedFunctionNames"]);n!=null&&h(e,["allowedFunctionNames"],n);let r=p(t,["mode"]);if(r!=null&&h(e,["mode"],r),p(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 Lct(t,e,n){let r={},i=p(e,["serviceTier"]);n!==void 0&&i!=null&&h(n,["serviceTier"],i);let s=p(e,["systemInstruction"]);n!==void 0&&s!=null&&h(n,["systemInstruction"],cTe(Qr(s)));let o=p(e,["temperature"]);o!=null&&h(r,["temperature"],o);let a=p(e,["topP"]);a!=null&&h(r,["topP"],a);let c=p(e,["topK"]);c!=null&&h(r,["topK"],c);let l=p(e,["candidateCount"]);l!=null&&h(r,["candidateCount"],l);let u=p(e,["maxOutputTokens"]);u!=null&&h(r,["maxOutputTokens"],u);let d=p(e,["stopSequences"]);d!=null&&h(r,["stopSequences"],d);let f=p(e,["responseLogprobs"]);f!=null&&h(r,["responseLogprobs"],f);let m=p(e,["logprobs"]);m!=null&&h(r,["logprobs"],m);let g=p(e,["presencePenalty"]);g!=null&&h(r,["presencePenalty"],g);let y=p(e,["frequencyPenalty"]);y!=null&&h(r,["frequencyPenalty"],y);let w=p(e,["seed"]);w!=null&&h(r,["seed"],w);let S=p(e,["responseMimeType"]);S!=null&&h(r,["responseMimeType"],S);let T=p(e,["responseSchema"]);T!=null&&h(r,["responseSchema"],bz(T));let R=p(e,["responseJsonSchema"]);if(R!=null&&h(r,["responseJsonSchema"],R),p(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(p(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 C=p(e,["safetySettings"]);if(n!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(F=>Qct(F))),h(n,["safetySettings"],P)}let D=p(e,["tools"]);if(n!==void 0&&D!=null){let P=yv(D);Array.isArray(P)&&(P=P.map(F=>elt(gv(F)))),h(n,["tools"],P)}let $=p(e,["toolConfig"]);if(n!==void 0&&$!=null&&h(n,["toolConfig"],Zct($)),p(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=p(e,["cachedContent"]);n!==void 0&&G!=null&&h(n,["cachedContent"],zu(t,G));let V=p(e,["responseModalities"]);V!=null&&h(r,["responseModalities"],V);let L=p(e,["mediaResolution"]);L!=null&&h(r,["mediaResolution"],L);let k=p(e,["speechConfig"]);if(k!=null&&h(r,["speechConfig"],Tz(k)),p(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 E=p(e,["thinkingConfig"]);E!=null&&h(r,["thinkingConfig"],E);let A=p(e,["audioTranscriptionConfig"]);A!=null&&h(r,["audioTranscriptionConfig"],A);let M=p(e,["imageConfig"]);M!=null&&h(r,["imageConfig"],Gct(M));let I=p(e,["enableEnhancedCivicAnswers"]);if(I!=null&&h(r,["enableEnhancedCivicAnswers"],I),p(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Uct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["candidates"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(u=>vct(u))),h(e,["candidates"],l)}let i=p(t,["modelVersion"]);i!=null&&h(e,["modelVersion"],i);let s=p(t,["promptFeedback"]);s!=null&&h(e,["promptFeedback"],s);let o=p(t,["responseId"]);o!=null&&h(e,["responseId"],o);let a=p(t,["usageMetadata"]);a!=null&&h(e,["usageMetadata"],a);let c=p(t,["modelStatus"]);return c!=null&&h(e,["modelStatus"],c),e}function Fct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function Bct(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],_v(t,r)),n}function qct(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],lct(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 $ct(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function Gct(t){let e={},n=p(t,["aspectRatio"]);n!=null&&h(e,["aspectRatio"],n);let r=p(t,["imageSize"]);if(r!=null&&h(e,["imageSize"],r),p(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(p(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(p(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(p(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(p(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 Hct(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["request","model"],Kt(t,r));let i=p(e,["contents"]);if(i!=null){let a=gs(i);Array.isArray(a)&&(a=a.map(c=>cTe(c))),h(n,["request","contents"],a)}let s=p(e,["metadata"]);s!=null&&h(n,["metadata"],s);let o=p(e,["config"]);return o!=null&&h(n,["request","generationConfig"],Lct(t,o,p(n,["request"],{}))),n}function jct(t){let e={},n=p(t,["response"]);n!=null&&h(e,["response"],Uct(n));let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["error"]);return i!=null&&h(e,["error"],i),e}function Wct(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);if(e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),p(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 Vct(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);e!==void 0&&i!=null&&h(e,["_query","pageToken"],i);let s=p(t,["filter"]);return e!==void 0&&s!=null&&h(e,["_query","filter"],s),n}function zct(t){let e={},n=p(t,["config"]);return n!=null&&Wct(n,e),e}function Kct(t){let e={},n=p(t,["config"]);return n!=null&&Vct(n,e),e}function Yct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["operations"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>EO(o))),h(e,["batchJobs"],s)}return e}function Xct(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["batchPredictionJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>_V(o))),h(e,["batchJobs"],s)}return e}function Jct(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],Mct(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],Nct(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],gct(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function Qct(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Zct(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],Dct(n));let r=p(t,["retrievalConfig"]);r!=null&&h(e,["retrievalConfig"],r);let i=p(t,["includeServerSideToolInvocations"]);return i!=null&&h(e,["includeServerSideToolInvocations"],i),e}function elt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],qct(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],$ct(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function tlt(t){let e={},n=p(t,["bigqueryDestination","outputUri"]);n!=null&&h(e,["bigqueryDestination"],n);let r=p(t,["displayName"]);return r!=null&&h(e,["displayName"],r),e}function nlt(t){let e={},n=p(t,["bigqueryDestination"]);n!=null&&h(e,["bigqueryDestination","outputUri"],n);let r=p(t,["displayName"]);return r!=null&&h(e,["displayName"],r),e}function rlt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 ilt(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function slt(t){let e={},n=p(t,["enablePromptInjectionDetection"]);n!=null&&h(e,["enablePromptInjectionDetection"],n);let r=p(t,["environment"]);r!=null&&h(e,["environment"],r);let i=p(t,["excludedPredefinedFunctions"]);if(i!=null&&h(e,["excludedPredefinedFunctions"],i),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function ube(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Rlt(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function dbe(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Ilt(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function olt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);e!==void 0&&i!=null&&h(e,["expireTime"],i);let s=p(t,["displayName"]);e!==void 0&&s!=null&&h(e,["displayName"],s);let o=p(t,["contents"]);if(e!==void 0&&o!=null){let u=gs(o);Array.isArray(u)&&(u=u.map(d=>ube(d))),h(e,["contents"],u)}let a=p(t,["systemInstruction"]);e!==void 0&&a!=null&&h(e,["systemInstruction"],ube(Qr(a)));let c=p(t,["tools"]);if(e!==void 0&&c!=null){let u=c;Array.isArray(u)&&(u=u.map(d=>Olt(d))),h(e,["tools"],u)}let l=p(t,["toolConfig"]);if(e!==void 0&&l!=null&&h(e,["toolConfig"],klt(l)),p(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 alt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);e!==void 0&&i!=null&&h(e,["expireTime"],i);let s=p(t,["displayName"]);e!==void 0&&s!=null&&h(e,["displayName"],s);let o=p(t,["contents"]);if(e!==void 0&&o!=null){let d=gs(o);Array.isArray(d)&&(d=d.map(f=>dbe(f))),h(e,["contents"],d)}let a=p(t,["systemInstruction"]);e!==void 0&&a!=null&&h(e,["systemInstruction"],dbe(Qr(a)));let c=p(t,["tools"]);if(e!==void 0&&c!=null){let d=c;Array.isArray(d)&&(d=d.map(f=>Mlt(f))),h(e,["tools"],d)}let l=p(t,["toolConfig"]);e!==void 0&&l!=null&&h(e,["toolConfig"],Plt(l));let u=p(t,["kmsKeyName"]);return e!==void 0&&u!=null&&h(e,["encryption_spec","kmsKeyName"],u),n}function clt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Ybe(t,r));let i=p(e,["config"]);return i!=null&&olt(i,n),n}function llt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["model"],Ybe(t,r));let i=p(e,["config"]);return i!=null&&alt(i,n),n}function ult(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function dlt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function flt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function plt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function hlt(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function mlt(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 glt(t){let e={},n=p(t,["allowedFunctionNames"]);n!=null&&h(e,["allowedFunctionNames"],n);let r=p(t,["mode"]);if(r!=null&&h(e,["mode"],r),p(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 ylt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function _lt(t,e){let n={},r=p(e,["name"]);return r!=null&&h(n,["_url","name"],zu(t,r)),n}function vlt(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],rlt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 Elt(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function wlt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function Slt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function xlt(t){let e={},n=p(t,["config"]);return n!=null&&wlt(n,e),e}function blt(t){let e={},n=p(t,["config"]);return n!=null&&Slt(n,e),e}function Tlt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["cachedContents"],s)}return e}function Alt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["cachedContents"],s)}return e}function Clt(t){let e={};if(p(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(p(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 Rlt(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],hlt(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],mlt(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],ilt(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function Ilt(t){let e={},n=p(t,["mediaResolution"]);if(n!=null&&h(e,["mediaResolution"],n),p(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(p(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=p(t,["audioTranscription"]);r!=null&&h(e,["audioTranscription"],r);let i=p(t,["codeExecutionResult"]);i!=null&&h(e,["codeExecutionResult"],i);let s=p(t,["executableCode"]);s!=null&&h(e,["executableCode"],s);let o=p(t,["fileData"]);o!=null&&h(e,["fileData"],o);let a=p(t,["functionCall"]);a!=null&&h(e,["functionCall"],a);let c=p(t,["functionResponse"]);c!=null&&h(e,["functionResponse"],c);let l=p(t,["inlineData"]);l!=null&&h(e,["inlineData"],l);let u=p(t,["text"]);u!=null&&h(e,["text"],u);let d=p(t,["thought"]);d!=null&&h(e,["thought"],d);let f=p(t,["thoughtSignature"]);f!=null&&h(e,["thoughtSignature"],f);let m=p(t,["videoMetadata"]);if(m!=null&&h(e,["videoMetadata"],m),p(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=p(t,["mediaProcessing"]);return g!=null&&h(e,["mediaProcessing"],g),e}function klt(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],glt(n));let r=p(t,["retrievalConfig"]);r!=null&&h(e,["retrievalConfig"],r);let i=p(t,["includeServerSideToolInvocations"]);return i!=null&&h(e,["includeServerSideToolInvocations"],i),e}function Plt(t){let e={},n=p(t,["functionCallingConfig"]);n!=null&&h(e,["functionCallingConfig"],n);let r=p(t,["retrievalConfig"]);if(r!=null&&h(e,["retrievalConfig"],r),p(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 Olt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],vlt(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],Elt(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function Mlt(t){let e={},n=p(t,["retrieval"]);n!=null&&h(e,["retrieval"],n);let r=p(t,["googleMaps"]);r!=null&&h(e,["googleMaps"],r);let i=p(t,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Clt(y))),h(e,["mcpServers"],g)}let s=p(t,["codeExecution"]);s!=null&&h(e,["codeExecution"],s);let o=p(t,["computerUse"]);o!=null&&h(e,["computerUse"],slt(o));let a=p(t,["enterpriseWebSearch"]);a!=null&&h(e,["enterpriseWebSearch"],a);let c=p(t,["exaAiSearch"]);c!=null&&h(e,["exaAiSearch"],c);let l=p(t,["functionDeclarations"]);if(l!=null){let g=l;Array.isArray(g)&&(g=g.map(y=>y)),h(e,["functionDeclarations"],g)}let u=p(t,["googleSearch"]);u!=null&&h(e,["googleSearch"],u);let d=p(t,["googleSearchRetrieval"]);d!=null&&h(e,["googleSearchRetrieval"],d);let f=p(t,["parallelAiSearch"]);f!=null&&h(e,["parallelAiSearch"],f);let m=p(t,["urlContext"]);if(m!=null&&h(e,["urlContext"],m),p(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 Nlt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);return e!==void 0&&i!=null&&h(e,["expireTime"],i),n}function Dlt(t,e){let n={},r=p(t,["ttl"]);e!==void 0&&r!=null&&h(e,["ttl"],r);let i=p(t,["expireTime"]);return e!==void 0&&i!=null&&h(e,["expireTime"],i),n}function Llt(t,e){let n={},r=p(e,["name"]);r!=null&&h(n,["_url","name"],zu(t,r));let i=p(e,["config"]);return i!=null&&Nlt(i,n),n}function Ult(t,e){let n={},r=p(e,["name"]);r!=null&&h(n,["_url","name"],zu(t,r));let i=p(e,["config"]);return i!=null&&Dlt(i,n),n}function Cr(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 fbe(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 Hn(t){return this instanceof Hn?(this.v=t,this):new Hn(t)}function pv(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(m){return function(g){return Promise.resolve(g).then(m,d)}}function a(m,g){r[m]&&(i[m]=function(y){return new Promise(function(w,S){s.push([m,y,w,S])>1||c(m,y)})},g&&(i[m]=g(i[m])))}function c(m,g){try{l(r[m](g))}catch(y){f(s[0][3],y)}}function l(m){m.value instanceof Hn?Promise.resolve(m.value.v).then(u,d):f(s[0][2],m)}function u(m){c("next",m)}function d(m){c("throw",m)}function f(m,g){m(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function VS(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 fbe=="function"?fbe(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Flt(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:lTe(n)}function lTe(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 Blt(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 pbe(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=[],s=!0;for(;r<n&&t[r].role==="model";)i.push(t[r]),s&&!lTe(t[r])&&(s=!1),r++;s?e.push(...i):e.pop()}return e}function qlt(t){let e={},n=p(t,["file"]);return n!=null&&h(e,["file"],n),e}function $lt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function Glt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","file"],Cz(n)),e}function Hlt(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function jlt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","file"],Cz(n)),e}function Wlt(t){let e={},n=p(t,["uris"]);return n!=null&&h(e,["uris"],n),e}function Vlt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function zlt(t){let e={},n=p(t,["config"]);return n!=null&&Vlt(n,e),e}function Klt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["files"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["files"],s)}return e}function Ylt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["files"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(e,["files"],i)}return e}function Xlt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 wO(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function Jlt(t){let e={},n=p(t,["enablePromptInjectionDetection"]);n!=null&&h(e,["enablePromptInjectionDetection"],n);let r=p(t,["environment"]);r!=null&&h(e,["environment"],r);let i=p(t,["excludedPredefinedFunctions"]);if(i!=null&&h(e,["excludedPredefinedFunctions"],i),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Qlt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>gut(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function Zlt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>yut(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function eut(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function tut(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 nut(t){let e={},n=p(t,["modelSelectionConfig"]);n!=null&&h(e,["modelConfig"],n);let r=p(t,["responseJsonSchema"]);r!=null&&h(e,["responseJsonSchema"],r);let i=p(t,["audioTranscriptionConfig"]);i!=null&&h(e,["audioTranscriptionConfig"],i);let s=p(t,["audioTimestamp"]);s!=null&&h(e,["audioTimestamp"],s);let o=p(t,["candidateCount"]);o!=null&&h(e,["candidateCount"],o);let a=p(t,["enableAffectiveDialog"]);a!=null&&h(e,["enableAffectiveDialog"],a);let c=p(t,["frequencyPenalty"]);c!=null&&h(e,["frequencyPenalty"],c);let l=p(t,["logprobs"]);l!=null&&h(e,["logprobs"],l);let u=p(t,["maxOutputTokens"]);u!=null&&h(e,["maxOutputTokens"],u);let d=p(t,["mediaResolution"]);d!=null&&h(e,["mediaResolution"],d);let f=p(t,["presencePenalty"]);f!=null&&h(e,["presencePenalty"],f);let m=p(t,["responseFormat"]);if(m!=null){let k=m;Array.isArray(k)&&(k=k.map(E=>E)),h(e,["responseFormat"],k)}let g=p(t,["responseLogprobs"]);g!=null&&h(e,["responseLogprobs"],g);let y=p(t,["responseMimeType"]);y!=null&&h(e,["responseMimeType"],y);let w=p(t,["responseModalities"]);w!=null&&h(e,["responseModalities"],w);let S=p(t,["responseSchema"]);S!=null&&h(e,["responseSchema"],S);let T=p(t,["routingConfig"]);T!=null&&h(e,["routingConfig"],T);let R=p(t,["seed"]);R!=null&&h(e,["seed"],R);let C=p(t,["speechConfig"]);C!=null&&h(e,["speechConfig"],dTe(C));let D=p(t,["stopSequences"]);D!=null&&h(e,["stopSequences"],D);let $=p(t,["temperature"]);$!=null&&h(e,["temperature"],$);let G=p(t,["thinkingConfig"]);G!=null&&h(e,["thinkingConfig"],G);let V=p(t,["topK"]);V!=null&&h(e,["topK"],V);let L=p(t,["topP"]);if(L!=null&&h(e,["topP"],L),p(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(p(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function rut(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],Xlt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 iut(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function sut(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],r);let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],Az(d));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],Qlt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let L=yv(y);Array.isArray(L)&&(L=L.map(k=>Sut(gv(k)))),h(e,["setup","tools"],L)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],Eut(w));let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);if(e!==void 0&&D!=null&&h(e,["setup","proactivity"],D),p(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let $=p(t,["avatarConfig"]);e!==void 0&&$!=null&&h(e,["setup","avatarConfig"],$);let G=p(t,["safetySettings"]);if(e!==void 0&&G!=null){let L=G;Array.isArray(L)&&(L=L.map(k=>vut(k))),h(e,["setup","safetySettings"],L)}let V=p(t,["translationConfig"]);return e!==void 0&&V!=null&&h(e,["setup","generationConfig","translationConfig"],V),n}function out(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],nut(r));let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],dTe(Az(d)));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],Zlt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let k=yv(y);Array.isArray(k)&&(k=k.map(E=>xut(gv(E)))),h(e,["setup","tools"],k)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],w);let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);e!==void 0&&D!=null&&h(e,["setup","proactivity"],D);let $=p(t,["explicitVadSignal"]);e!==void 0&&$!=null&&h(e,["setup","explicitVadSignal"],$);let G=p(t,["avatarConfig"]);e!==void 0&&G!=null&&h(e,["setup","avatarConfig"],G);let V=p(t,["safetySettings"]);if(e!==void 0&&V!=null){let k=V;Array.isArray(k)&&(k=k.map(E=>E)),h(e,["setup","safetySettings"],k)}let L=p(t,["translationConfig"]);return e!==void 0&&L!=null&&h(e,["setup","generationConfig","translationConfig"],L),n}function aut(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],sut(i,n)),n}function cut(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],out(i,n)),n}function lut(t){let e={},n=p(t,["musicGenerationConfig"]);return n!=null&&h(e,["musicGenerationConfig"],n),e}function uut(t){let e={},n=p(t,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),h(e,["weightedPrompts"],r)}return e}function dut(t){let e={},n=p(t,["media"]);if(n!=null){let l=Xbe(n);Array.isArray(l)&&(l=l.map(u=>wO(u))),h(e,["mediaChunks"],l)}let r=p(t,["audio"]);r!=null&&h(e,["audio"],wO(Qbe(r)));let i=p(t,["audioStreamEnd"]);i!=null&&h(e,["audioStreamEnd"],i);let s=p(t,["video"]);s!=null&&h(e,["video"],wO(Jbe(s)));let o=p(t,["text"]);o!=null&&h(e,["text"],o);let a=p(t,["activityStart"]);a!=null&&h(e,["activityStart"],a);let c=p(t,["activityEnd"]);return c!=null&&h(e,["activityEnd"],c),e}function fut(t){let e={},n=p(t,["media"]);if(n!=null){let l=Xbe(n);Array.isArray(l)&&(l=l.map(u=>u)),h(e,["mediaChunks"],l)}let r=p(t,["audio"]);r!=null&&h(e,["audio"],Qbe(r));let i=p(t,["audioStreamEnd"]);i!=null&&h(e,["audioStreamEnd"],i);let s=p(t,["video"]);s!=null&&h(e,["video"],Jbe(s));let o=p(t,["text"]);o!=null&&h(e,["text"],o);let a=p(t,["activityStart"]);a!=null&&h(e,["activityStart"],a);let c=p(t,["activityEnd"]);return c!=null&&h(e,["activityEnd"],c),e}function put(t){let e={},n=p(t,["setupComplete"]);n!=null&&h(e,["setupComplete"],n);let r=p(t,["serverContent"]);r!=null&&h(e,["serverContent"],r);let i=p(t,["toolCall"]);i!=null&&h(e,["toolCall"],i);let s=p(t,["toolCallCancellation"]);s!=null&&h(e,["toolCallCancellation"],s);let o=p(t,["usageMetadata"]);o!=null&&h(e,["usageMetadata"],but(o));let a=p(t,["goAway"]);a!=null&&h(e,["goAway"],a);let c=p(t,["sessionResumptionUpdate"]);c!=null&&h(e,["sessionResumptionUpdate"],c);let l=p(t,["voiceActivityDetectionSignal"]);l!=null&&h(e,["voiceActivityDetectionSignal"],l);let u=p(t,["voiceActivity"]);return u!=null&&h(e,["voiceActivity"],Tut(u)),e}function hut(t){let e={};if(p(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(p(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 mut(t){let e={},n=p(t,["speakerVoiceConfigs"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>wut(i))),h(e,["speakerVoiceConfigs"],r)}return e}function gut(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],eut(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],tut(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],wO(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function yut(t){let e={},n=p(t,["mediaResolution"]);if(n!=null&&h(e,["mediaResolution"],n),p(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(p(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=p(t,["audioTranscription"]);r!=null&&h(e,["audioTranscription"],r);let i=p(t,["codeExecutionResult"]);i!=null&&h(e,["codeExecutionResult"],i);let s=p(t,["executableCode"]);s!=null&&h(e,["executableCode"],s);let o=p(t,["fileData"]);o!=null&&h(e,["fileData"],o);let a=p(t,["functionCall"]);a!=null&&h(e,["functionCall"],a);let c=p(t,["functionResponse"]);c!=null&&h(e,["functionResponse"],c);let l=p(t,["inlineData"]);l!=null&&h(e,["inlineData"],l);let u=p(t,["text"]);u!=null&&h(e,["text"],u);let d=p(t,["thought"]);d!=null&&h(e,["thought"],d);let f=p(t,["thoughtSignature"]);f!=null&&h(e,["thoughtSignature"],f);let m=p(t,["videoMetadata"]);if(m!=null&&h(e,["videoMetadata"],m),p(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=p(t,["mediaProcessing"]);return g!=null&&h(e,["mediaProcessing"],g),e}function _ut(t){let e={},n=p(t,["mimeType"]);n!=null&&h(e,["mimeType"],n);let r=p(t,["voiceSampleAudio"]);if(r!=null&&h(e,["voiceSampleAudio"],r),p(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(p(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 vut(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Eut(t){let e={},n=p(t,["handle"]);if(n!=null&&h(e,["handle"],n),p(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 wut(t){let e={},n=p(t,["speaker"]);n!=null&&h(e,["speaker"],n);let r=p(t,["voiceConfig"]);return r!=null&&h(e,["voiceConfig"],fTe(r)),e}function dTe(t){let e={},n=p(t,["voiceConfig"]);n!=null&&h(e,["voiceConfig"],fTe(n));let r=p(t,["languageCode"]);r!=null&&h(e,["languageCode"],r);let i=p(t,["multiSpeakerVoiceConfig"]);return i!=null&&h(e,["multiSpeakerVoiceConfig"],mut(i)),e}function Sut(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],rut(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],iut(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function xut(t){let e={},n=p(t,["retrieval"]);n!=null&&h(e,["retrieval"],n);let r=p(t,["googleMaps"]);r!=null&&h(e,["googleMaps"],r);let i=p(t,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>hut(y))),h(e,["mcpServers"],g)}let s=p(t,["codeExecution"]);s!=null&&h(e,["codeExecution"],s);let o=p(t,["computerUse"]);o!=null&&h(e,["computerUse"],Jlt(o));let a=p(t,["enterpriseWebSearch"]);a!=null&&h(e,["enterpriseWebSearch"],a);let c=p(t,["exaAiSearch"]);c!=null&&h(e,["exaAiSearch"],c);let l=p(t,["functionDeclarations"]);if(l!=null){let g=l;Array.isArray(g)&&(g=g.map(y=>y)),h(e,["functionDeclarations"],g)}let u=p(t,["googleSearch"]);u!=null&&h(e,["googleSearch"],u);let d=p(t,["googleSearchRetrieval"]);d!=null&&h(e,["googleSearchRetrieval"],d);let f=p(t,["parallelAiSearch"]);f!=null&&h(e,["parallelAiSearch"],f);let m=p(t,["urlContext"]);if(m!=null&&h(e,["urlContext"],m),p(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 but(t){let e={},n=p(t,["candidatesTokenCount"]);n!=null&&h(e,["responseTokenCount"],n);let r=p(t,["candidatesTokensDetails"]);if(r!=null){let m=r;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["responseTokensDetails"],m)}let i=p(t,["cacheTokensDetails"]);if(i!=null){let m=i;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["cacheTokensDetails"],m)}let s=p(t,["cachedContentTokenCount"]);s!=null&&h(e,["cachedContentTokenCount"],s);let o=p(t,["promptTokenCount"]);o!=null&&h(e,["promptTokenCount"],o);let a=p(t,["promptTokensDetails"]);if(a!=null){let m=a;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["promptTokensDetails"],m)}let c=p(t,["thoughtsTokenCount"]);c!=null&&h(e,["thoughtsTokenCount"],c);let l=p(t,["toolUsePromptTokenCount"]);l!=null&&h(e,["toolUsePromptTokenCount"],l);let u=p(t,["toolUsePromptTokensDetails"]);if(u!=null){let m=u;Array.isArray(m)&&(m=m.map(g=>g)),h(e,["toolUsePromptTokensDetails"],m)}let d=p(t,["totalTokenCount"]);d!=null&&h(e,["totalTokenCount"],d);let f=p(t,["trafficType"]);return f!=null&&h(e,["trafficType"],f),e}function Tut(t){let e={},n=p(t,["type"]);n!=null&&h(e,["voiceActivityType"],n);let r=p(t,["audioOffset"]);return r!=null&&h(e,["audioOffset"],r),e}function fTe(t){let e={},n=p(t,["replicatedVoiceConfig"]);n!=null&&h(e,["replicatedVoiceConfig"],_ut(n));let r=p(t,["prebuiltVoiceConfig"]);return r!=null&&h(e,["prebuiltVoiceConfig"],r),e}function Aut(t,e){let n={},r=p(t,["apiKey"]);if(r!=null&&h(n,["apiKey"],r),p(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(p(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(p(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(p(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(p(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(p(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 Cut(t,e){let n={},r=p(t,["data"]);if(r!=null&&h(n,["data"],r),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function Rut(t,e){let n={},r=p(t,["content"]);r!=null&&h(n,["content"],r);let i=p(t,["citationMetadata"]);i!=null&&h(n,["citationMetadata"],Iut(i));let s=p(t,["tokenCount"]);s!=null&&h(n,["tokenCount"],s);let o=p(t,["finishReason"]);o!=null&&h(n,["finishReason"],o);let a=p(t,["groundingMetadata"]);a!=null&&h(n,["groundingMetadata"],a);let c=p(t,["avgLogprobs"]);c!=null&&h(n,["avgLogprobs"],c);let l=p(t,["index"]);l!=null&&h(n,["index"],l);let u=p(t,["logprobsResult"]);u!=null&&h(n,["logprobsResult"],u);let d=p(t,["safetyRatings"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(g=>g)),h(n,["safetyRatings"],m)}let f=p(t,["urlContextMetadata"]);return f!=null&&h(n,["urlContextMetadata"],f),n}function Iut(t,e){let n={},r=p(t,["citationSources"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(n,["citations"],i)}return n}function kut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let o=gs(s);Array.isArray(o)&&(o=o.map(a=>vv(a))),h(r,["contents"],o)}return r}function Put(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["tokensInfo"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["tokensInfo"],s)}return n}function Out(t,e){let n={},r=p(t,["enablePromptInjectionDetection"]);r!=null&&h(n,["enablePromptInjectionDetection"],r);let i=p(t,["environment"]);i!=null&&h(n,["environment"],i);let s=p(t,["excludedPredefinedFunctions"]);if(s!=null&&h(n,["excludedPredefinedFunctions"],s),p(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Mut(t,e){let n={},r=p(t,["values"]);r!=null&&h(n,["values"],r);let i=p(t,["statistics"]);return i!=null&&h(n,["statistics"],Nut(i)),n}function Nut(t,e){let n={},r=p(t,["truncated"]);r!=null&&h(n,["truncated"],r);let i=p(t,["token_count"]);i!=null&&h(n,["tokenCount"],i);let s=p(t,["tokensDetails"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(a=>a)),h(n,["tokensDetails"],o)}return n}function lx(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Bdt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function vv(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>qdt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function Dut(t,e){let n={},r=p(t,["controlType"]);r!=null&&h(n,["controlType"],r);let i=p(t,["enableControlImageComputation"]);return i!=null&&h(n,["computeControl"],i),n}function Lut(t,e){let n={};if(p(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(p(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(p(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 Uut(t,e,n){let r={},i=p(t,["systemInstruction"]);e!==void 0&&i!=null&&h(e,["systemInstruction"],vv(Qr(i)));let s=p(t,["tools"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>gTe(c))),h(e,["tools"],a)}let o=p(t,["generationConfig"]);return e!==void 0&&o!=null&&h(e,["generationConfig"],xdt(o)),r}function Fut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>lx(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&Lut(o),r}function But(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>vv(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&Uut(o,r),r}function qut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["totalTokens"]);i!=null&&h(n,["totalTokens"],i);let s=p(t,["cachedContentTokenCount"]);return s!=null&&h(n,["cachedContentTokenCount"],s),n}function $ut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["totalTokens"]);return i!=null&&h(n,["totalTokens"],i),n}function Gut(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Hut(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function jut(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function Wut(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function Vut(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["negativePrompt"]);e!==void 0&&s!=null&&h(e,["parameters","negativePrompt"],s);let o=p(t,["numberOfImages"]);e!==void 0&&o!=null&&h(e,["parameters","sampleCount"],o);let a=p(t,["aspectRatio"]);e!==void 0&&a!=null&&h(e,["parameters","aspectRatio"],a);let c=p(t,["guidanceScale"]);e!==void 0&&c!=null&&h(e,["parameters","guidanceScale"],c);let l=p(t,["seed"]);e!==void 0&&l!=null&&h(e,["parameters","seed"],l);let u=p(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&h(e,["parameters","safetySetting"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["includeSafetyAttributes"]);e!==void 0&&f!=null&&h(e,["parameters","includeSafetyAttributes"],f);let m=p(t,["includeRaiReason"]);e!==void 0&&m!=null&&h(e,["parameters","includeRaiReason"],m);let g=p(t,["language"]);e!==void 0&&g!=null&&h(e,["parameters","language"],g);let y=p(t,["outputMimeType"]);e!==void 0&&y!=null&&h(e,["parameters","outputOptions","mimeType"],y);let w=p(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&h(e,["parameters","outputOptions","compressionQuality"],w);let S=p(t,["addWatermark"]);e!==void 0&&S!=null&&h(e,["parameters","addWatermark"],S);let T=p(t,["labels"]);e!==void 0&&T!=null&&h(e,["labels"],T);let R=p(t,["editMode"]);e!==void 0&&R!=null&&h(e,["parameters","editMode"],R);let C=p(t,["baseSteps"]);return e!==void 0&&C!=null&&h(e,["parameters","editConfig","baseSteps"],C),r}function zut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["referenceImages"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(l=>Vdt(l))),h(r,["instances[0]","referenceImages"],c)}let a=p(e,["config"]);return a!=null&&Vut(a,r),r}function Kut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o1(o))),h(n,["generatedImages"],s)}return n}function Yut(t,e,n){let r={},i=p(t,["taskType"]);e!==void 0&&i!=null&&h(e,["requests[]","taskType"],i);let s=p(t,["title"]);e!==void 0&&s!=null&&h(e,["requests[]","title"],s);let o=p(t,["outputDimensionality"]);if(e!==void 0&&o!=null&&h(e,["requests[]","outputDimensionality"],o),p(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(p(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(p(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(p(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 Xut(t,e,n){let r={},i=p(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let d=p(t,["taskType"]);e!==void 0&&d!=null&&h(e,["instances[]","task_type"],d)}else if(i==="EMBED_CONTENT"){let d=p(t,["taskType"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","taskType"],d)}let s=p(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let d=p(t,["title"]);e!==void 0&&d!=null&&h(e,["instances[]","title"],d)}else if(s==="EMBED_CONTENT"){let d=p(t,["title"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","title"],d)}let o=p(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let d=p(t,["outputDimensionality"]);e!==void 0&&d!=null&&h(e,["parameters","outputDimensionality"],d)}else if(o==="EMBED_CONTENT"){let d=p(t,["outputDimensionality"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","outputDimensionality"],d)}let a=p(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let d=p(t,["mimeType"]);e!==void 0&&d!=null&&h(e,["instances[]","mimeType"],d)}let c=p(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let d=p(t,["autoTruncate"]);e!==void 0&&d!=null&&h(e,["parameters","autoTruncate"],d)}else if(c==="EMBED_CONTENT"){let d=p(t,["autoTruncate"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","autoTruncate"],d)}let l=p(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="EMBED_CONTENT"){let d=p(t,["documentOcr"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","documentOcr"],d)}let u=p(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="EMBED_CONTENT"){let d=p(t,["audioTrackExtraction"]);e!==void 0&&d!=null&&h(e,["embedContentConfig","audioTrackExtraction"],d)}return r}function Jut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let l=xz(t,s);Array.isArray(l)&&(l=l.map(u=>u)),h(r,["requests[]","content"],l)}let o=p(e,["content"]);o!=null&&lx(Qr(o));let a=p(e,["config"]);a!=null&&Yut(a,r);let c=p(e,["model"]);return c!==void 0&&h(r,["requests[]","model"],Kt(t,c)),r}function Qut(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let c=p(e,["contents"]);if(c!=null){let l=xz(t,c);Array.isArray(l)&&(l=l.map(u=>u)),h(r,["instances[]","content"],l)}}let o=p(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="EMBED_CONTENT"){let c=p(e,["content"]);c!=null&&h(r,["content"],vv(Qr(c)))}let a=p(e,["config"]);return a!=null&&Xut(a,r,n),r}function Zut(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),h(n,["embeddings"],o)}let s=p(t,["metadata"]);return s!=null&&h(n,["metadata"],s),n}function edt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions[]","embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>Mut(a))),h(n,["embeddings"],o)}let s=p(t,["metadata"]);if(s!=null&&h(n,["metadata"],s),e&&p(e,["embeddingApiType"])==="EMBED_CONTENT"){let o=p(t,["embedding"]),a=p(t,["usageMetadata"]),c=p(t,["truncated"]);if(o){let l={};a&&a.promptTokenCount&&(l.tokenCount=a.promptTokenCount),a&&a.promptTokensDetails&&(l.tokensDetails=a.promptTokensDetails),c&&(l.truncated=c),o.statistics=l,h(n,["embeddings"],[o])}}return n}function tdt(t,e){let n={},r=p(t,["endpoint"]);r!=null&&h(n,["name"],r);let i=p(t,["deployedModelId"]);return i!=null&&h(n,["deployedModelId"],i),n}function ndt(t,e){let n={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["fileUri"]);r!=null&&h(n,["fileUri"],r);let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function rdt(t,e){let n={},r=p(t,["args"]);r!=null&&h(n,["args"],r);let i=p(t,["id"]);i!=null&&h(n,["id"],i);let s=p(t,["name"]);if(s!=null&&h(n,["name"],s),p(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(p(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 idt(t,e){let n={},r=p(t,["allowedFunctionNames"]);r!=null&&h(n,["allowedFunctionNames"],r);let i=p(t,["mode"]);if(i!=null&&h(n,["mode"],i),p(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 sdt(t,e,n,r){let i={},s=p(e,["serviceTier"]);n!==void 0&&s!=null&&h(n,["serviceTier"],s);let o=p(e,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],lx(Qr(o)));let a=p(e,["temperature"]);a!=null&&h(i,["temperature"],a);let c=p(e,["topP"]);c!=null&&h(i,["topP"],c);let l=p(e,["topK"]);l!=null&&h(i,["topK"],l);let u=p(e,["candidateCount"]);u!=null&&h(i,["candidateCount"],u);let d=p(e,["maxOutputTokens"]);d!=null&&h(i,["maxOutputTokens"],d);let f=p(e,["stopSequences"]);f!=null&&h(i,["stopSequences"],f);let m=p(e,["responseLogprobs"]);m!=null&&h(i,["responseLogprobs"],m);let g=p(e,["logprobs"]);g!=null&&h(i,["logprobs"],g);let y=p(e,["presencePenalty"]);y!=null&&h(i,["presencePenalty"],y);let w=p(e,["frequencyPenalty"]);w!=null&&h(i,["frequencyPenalty"],w);let S=p(e,["seed"]);S!=null&&h(i,["seed"],S);let T=p(e,["responseMimeType"]);T!=null&&h(i,["responseMimeType"],T);let R=p(e,["responseSchema"]);R!=null&&h(i,["responseSchema"],bz(R));let C=p(e,["responseJsonSchema"]);if(C!=null&&h(i,["responseJsonSchema"],C),p(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(p(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 D=p(e,["safetySettings"]);if(n!==void 0&&D!=null){let F=D;Array.isArray(F)&&(F=F.map(X=>Kdt(X))),h(n,["safetySettings"],F)}let $=p(e,["tools"]);if(n!==void 0&&$!=null){let F=yv($);Array.isArray(F)&&(F=F.map(X=>rft(gv(X)))),h(n,["tools"],F)}let G=p(e,["toolConfig"]);if(n!==void 0&&G!=null&&h(n,["toolConfig"],tft(G)),p(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let V=p(e,["cachedContent"]);n!==void 0&&V!=null&&h(n,["cachedContent"],zu(t,V));let L=p(e,["responseModalities"]);L!=null&&h(i,["responseModalities"],L);let k=p(e,["mediaResolution"]);k!=null&&h(i,["mediaResolution"],k);let E=p(e,["speechConfig"]);if(E!=null&&h(i,["speechConfig"],Tz(E)),p(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 A=p(e,["thinkingConfig"]);A!=null&&h(i,["thinkingConfig"],A);let M=p(e,["audioTranscriptionConfig"]);M!=null&&h(i,["audioTranscriptionConfig"],M);let I=p(e,["imageConfig"]);I!=null&&h(i,["imageConfig"],Rdt(I));let P=p(e,["enableEnhancedCivicAnswers"]);if(P!=null&&h(i,["enableEnhancedCivicAnswers"],P),p(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function odt(t,e,n,r){let i={},s=p(e,["serviceTier"]);n!==void 0&&s!=null&&h(n,["serviceTier"],s);let o=p(e,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],vv(Qr(o)));let a=p(e,["temperature"]);a!=null&&h(i,["temperature"],a);let c=p(e,["topP"]);c!=null&&h(i,["topP"],c);let l=p(e,["topK"]);l!=null&&h(i,["topK"],l);let u=p(e,["candidateCount"]);u!=null&&h(i,["candidateCount"],u);let d=p(e,["maxOutputTokens"]);d!=null&&h(i,["maxOutputTokens"],d);let f=p(e,["stopSequences"]);f!=null&&h(i,["stopSequences"],f);let m=p(e,["responseLogprobs"]);m!=null&&h(i,["responseLogprobs"],m);let g=p(e,["logprobs"]);g!=null&&h(i,["logprobs"],g);let y=p(e,["presencePenalty"]);y!=null&&h(i,["presencePenalty"],y);let w=p(e,["frequencyPenalty"]);w!=null&&h(i,["frequencyPenalty"],w);let S=p(e,["seed"]);S!=null&&h(i,["seed"],S);let T=p(e,["responseMimeType"]);T!=null&&h(i,["responseMimeType"],T);let R=p(e,["responseSchema"]);R!=null&&h(i,["responseSchema"],bz(R));let C=p(e,["responseJsonSchema"]);C!=null&&h(i,["responseJsonSchema"],C);let D=p(e,["routingConfig"]);D!=null&&h(i,["routingConfig"],D);let $=p(e,["modelSelectionConfig"]);$!=null&&h(i,["modelConfig"],$);let G=p(e,["safetySettings"]);if(n!==void 0&&G!=null){let q=G;Array.isArray(q)&&(q=q.map(pe=>pe)),h(n,["safetySettings"],q)}let V=p(e,["tools"]);if(n!==void 0&&V!=null){let q=yv(V);Array.isArray(q)&&(q=q.map(pe=>gTe(gv(pe)))),h(n,["tools"],q)}let L=p(e,["toolConfig"]);n!==void 0&&L!=null&&h(n,["toolConfig"],nft(L));let k=p(e,["labels"]);n!==void 0&&k!=null&&h(n,["labels"],k);let E=p(e,["cachedContent"]);n!==void 0&&E!=null&&h(n,["cachedContent"],zu(t,E));let A=p(e,["responseModalities"]);A!=null&&h(i,["responseModalities"],A);let M=p(e,["mediaResolution"]);M!=null&&h(i,["mediaResolution"],M);let I=p(e,["speechConfig"]);I!=null&&h(i,["speechConfig"],mTe(Tz(I)));let P=p(e,["audioTimestamp"]);P!=null&&h(i,["audioTimestamp"],P);let F=p(e,["thinkingConfig"]);F!=null&&h(i,["thinkingConfig"],F);let X=p(e,["audioTranscriptionConfig"]);X!=null&&h(i,["audioTranscriptionConfig"],X);let N=p(e,["imageConfig"]);if(N!=null&&h(i,["imageConfig"],Idt(N)),p(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 b=p(e,["modelArmorConfig"]);return n!==void 0&&b!=null&&h(n,["modelArmorConfig"],b),i}function hbe(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>lx(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&h(r,["generationConfig"],sdt(t,o,r)),r}function mbe(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["contents"]);if(s!=null){let a=gs(s);Array.isArray(a)&&(a=a.map(c=>vv(c))),h(r,["contents"],a)}let o=p(e,["config"]);return o!=null&&h(r,["generationConfig"],odt(t,o,r)),r}function gbe(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(d=>Rut(d))),h(n,["candidates"],u)}let s=p(t,["modelVersion"]);s!=null&&h(n,["modelVersion"],s);let o=p(t,["promptFeedback"]);o!=null&&h(n,["promptFeedback"],o);let a=p(t,["responseId"]);a!=null&&h(n,["responseId"],a);let c=p(t,["usageMetadata"]);c!=null&&h(n,["usageMetadata"],c);let l=p(t,["modelStatus"]);return l!=null&&h(n,["modelStatus"],l),n}function ybe(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(d=>d)),h(n,["candidates"],u)}let s=p(t,["createTime"]);s!=null&&h(n,["createTime"],s);let o=p(t,["modelVersion"]);o!=null&&h(n,["modelVersion"],o);let a=p(t,["promptFeedback"]);a!=null&&h(n,["promptFeedback"],a);let c=p(t,["responseId"]);c!=null&&h(n,["responseId"],c);let l=p(t,["usageMetadata"]);return l!=null&&h(n,["usageMetadata"],l),n}function adt(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["negativePrompt"]);e!==void 0&&s!=null&&h(e,["parameters","negativePrompt"],s);let o=p(t,["numberOfImages"]);e!==void 0&&o!=null&&h(e,["parameters","sampleCount"],o);let a=p(t,["aspectRatio"]);e!==void 0&&a!=null&&h(e,["parameters","aspectRatio"],a);let c=p(t,["guidanceScale"]);e!==void 0&&c!=null&&h(e,["parameters","guidanceScale"],c);let l=p(t,["seed"]);e!==void 0&&l!=null&&h(e,["parameters","seed"],l);let u=p(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&h(e,["parameters","safetySetting"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["includeSafetyAttributes"]);e!==void 0&&f!=null&&h(e,["parameters","includeSafetyAttributes"],f);let m=p(t,["includeRaiReason"]);e!==void 0&&m!=null&&h(e,["parameters","includeRaiReason"],m);let g=p(t,["language"]);e!==void 0&&g!=null&&h(e,["parameters","language"],g);let y=p(t,["outputMimeType"]);e!==void 0&&y!=null&&h(e,["parameters","outputOptions","mimeType"],y);let w=p(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&h(e,["parameters","outputOptions","compressionQuality"],w);let S=p(t,["addWatermark"]);e!==void 0&&S!=null&&h(e,["parameters","addWatermark"],S);let T=p(t,["labels"]);e!==void 0&&T!=null&&h(e,["labels"],T);let R=p(t,["imageSize"]);e!==void 0&&R!=null&&h(e,["parameters","sampleImageSize"],R);let C=p(t,["enhancePrompt"]);return e!==void 0&&C!=null&&h(e,["parameters","enhancePrompt"],C),r}function cdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["config"]);return o!=null&&adt(o,r),r}function ldt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>o1(a))),h(n,["generatedImages"],o)}let s=p(t,["positivePromptSafetyAttributes"]);return s!=null&&h(n,["positivePromptSafetyAttributes"],hTe(s)),n}function udt(t,e,n){let r={},i=p(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i),p(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=p(t,["durationSeconds"]);if(e!==void 0&&s!=null&&h(e,["parameters","durationSeconds"],s),p(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=p(t,["aspectRatio"]);e!==void 0&&o!=null&&h(e,["parameters","aspectRatio"],o);let a=p(t,["resolution"]);e!==void 0&&a!=null&&h(e,["parameters","resolution"],a);let c=p(t,["personGeneration"]);if(e!==void 0&&c!=null&&h(e,["parameters","personGeneration"],c),p(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let l=p(t,["negativePrompt"]);e!==void 0&&l!=null&&h(e,["parameters","negativePrompt"],l);let u=p(t,["enhancePrompt"]);if(e!==void 0&&u!=null&&h(e,["parameters","enhancePrompt"],u),p(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=p(t,["lastFrame"]);e!==void 0&&d!=null&&h(e,["instances[0]","lastFrame"],a1(d));let f=p(t,["referenceImages"]);if(e!==void 0&&f!=null){let g=f;Array.isArray(g)&&(g=g.map(y=>gft(y))),h(e,["instances[0]","referenceImages"],g)}if(p(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(p(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=p(t,["webhookConfig"]);if(e!==void 0&&m!=null&&h(e,["webhookConfig"],m),p(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function ddt(t,e,n){let r={},i=p(t,["numberOfVideos"]);e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i);let s=p(t,["outputGcsUri"]);e!==void 0&&s!=null&&h(e,["parameters","storageUri"],s);let o=p(t,["fps"]);e!==void 0&&o!=null&&h(e,["parameters","fps"],o);let a=p(t,["durationSeconds"]);e!==void 0&&a!=null&&h(e,["parameters","durationSeconds"],a);let c=p(t,["seed"]);e!==void 0&&c!=null&&h(e,["parameters","seed"],c);let l=p(t,["aspectRatio"]);e!==void 0&&l!=null&&h(e,["parameters","aspectRatio"],l);let u=p(t,["resolution"]);e!==void 0&&u!=null&&h(e,["parameters","resolution"],u);let d=p(t,["personGeneration"]);e!==void 0&&d!=null&&h(e,["parameters","personGeneration"],d);let f=p(t,["pubsubTopic"]);e!==void 0&&f!=null&&h(e,["parameters","pubsubTopic"],f);let m=p(t,["negativePrompt"]);e!==void 0&&m!=null&&h(e,["parameters","negativePrompt"],m);let g=p(t,["enhancePrompt"]);e!==void 0&&g!=null&&h(e,["parameters","enhancePrompt"],g);let y=p(t,["generateAudio"]);e!==void 0&&y!=null&&h(e,["parameters","generateAudio"],y);let w=p(t,["lastFrame"]);e!==void 0&&w!=null&&h(e,["instances[0]","lastFrame"],oc(w));let S=p(t,["referenceImages"]);if(e!==void 0&&S!=null){let $=S;Array.isArray($)&&($=$.map(G=>yft(G))),h(e,["instances[0]","referenceImages"],$)}let T=p(t,["mask"]);e!==void 0&&T!=null&&h(e,["instances[0]","mask"],mft(T));let R=p(t,["compressionQuality"]);e!==void 0&&R!=null&&h(e,["parameters","compressionQuality"],R);let C=p(t,["labels"]);if(e!==void 0&&C!=null&&h(e,["labels"],C),p(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 D=p(t,["resizeMode"]);return e!==void 0&&D!=null&&h(e,["parameters","resizeMode"],D),r}function fdt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["metadata"]);i!=null&&h(n,["metadata"],i);let s=p(t,["done"]);s!=null&&h(n,["done"],s);let o=p(t,["error"]);o!=null&&h(n,["error"],o);let a=p(t,["response","generateVideoResponse"]);return a!=null&&h(n,["response"],gdt(a)),n}function pdt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["metadata"]);i!=null&&h(n,["metadata"],i);let s=p(t,["done"]);s!=null&&h(n,["done"],s);let o=p(t,["error"]);o!=null&&h(n,["error"],o);let a=p(t,["response"]);return a!=null&&h(n,["response"],ydt(a)),n}function hdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["image"]);o!=null&&h(r,["instances[0]","image"],a1(o));let a=p(e,["video"]);a!=null&&h(r,["instances[0]","video"],yTe(a));let c=p(e,["source"]);c!=null&&_dt(c,r);let l=p(e,["config"]);return l!=null&&udt(l,r),r}function mdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["prompt"]);s!=null&&h(r,["instances[0]","prompt"],s);let o=p(e,["image"]);o!=null&&h(r,["instances[0]","image"],oc(o));let a=p(e,["video"]);a!=null&&h(r,["instances[0]","video"],_Te(a));let c=p(e,["source"]);c!=null&&vdt(c,r);let l=p(e,["config"]);return l!=null&&ddt(l,r),r}function gdt(t,e){let n={},r=p(t,["generatedSamples"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>wdt(a))),h(n,["generatedVideos"],o)}let i=p(t,["raiMediaFilteredCount"]);i!=null&&h(n,["raiMediaFilteredCount"],i);let s=p(t,["raiMediaFilteredReasons"]);return s!=null&&h(n,["raiMediaFilteredReasons"],s),n}function ydt(t,e){let n={},r=p(t,["videos"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>Sdt(a))),h(n,["generatedVideos"],o)}let i=p(t,["raiMediaFilteredCount"]);i!=null&&h(n,["raiMediaFilteredCount"],i);let s=p(t,["raiMediaFilteredReasons"]);return s!=null&&h(n,["raiMediaFilteredReasons"],s),n}function _dt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],a1(s));let o=p(t,["video"]);return e!==void 0&&o!=null&&h(e,["instances[0]","video"],yTe(o)),r}function vdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],oc(s));let o=p(t,["video"]);return e!==void 0&&o!=null&&h(e,["instances[0]","video"],_Te(o)),r}function o1(t,e){let n={},r=p(t,["_self"]);r!=null&&h(n,["image"],pTe(r));let i=p(t,["raiFilteredReason"]);i!=null&&h(n,["raiFilteredReason"],i);let s=p(t,["_self"]);s!=null&&h(n,["safetyAttributes"],hTe(s));let o=p(t,["prompt"]);return o!=null&&h(n,["enhancedPrompt"],o),n}function Edt(t,e){let n={},r=p(t,["_self"]);r!=null&&h(n,["mask"],pTe(r));let i=p(t,["labels"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["labels"],s)}return n}function wdt(t,e){let n={},r=p(t,["video"]);return r!=null&&h(n,["video"],pft(r)),n}function Sdt(t,e){let n={},r=p(t,["_self"]);return r!=null&&h(n,["video"],hft(r)),n}function xdt(t,e){let n={},r=p(t,["modelSelectionConfig"]);r!=null&&h(n,["modelConfig"],r);let i=p(t,["responseJsonSchema"]);i!=null&&h(n,["responseJsonSchema"],i);let s=p(t,["audioTranscriptionConfig"]);s!=null&&h(n,["audioTranscriptionConfig"],s);let o=p(t,["audioTimestamp"]);o!=null&&h(n,["audioTimestamp"],o);let a=p(t,["candidateCount"]);a!=null&&h(n,["candidateCount"],a);let c=p(t,["enableAffectiveDialog"]);c!=null&&h(n,["enableAffectiveDialog"],c);let l=p(t,["frequencyPenalty"]);l!=null&&h(n,["frequencyPenalty"],l);let u=p(t,["logprobs"]);u!=null&&h(n,["logprobs"],u);let d=p(t,["maxOutputTokens"]);d!=null&&h(n,["maxOutputTokens"],d);let f=p(t,["mediaResolution"]);f!=null&&h(n,["mediaResolution"],f);let m=p(t,["presencePenalty"]);m!=null&&h(n,["presencePenalty"],m);let g=p(t,["responseFormat"]);if(g!=null){let E=g;Array.isArray(E)&&(E=E.map(A=>A)),h(n,["responseFormat"],E)}let y=p(t,["responseLogprobs"]);y!=null&&h(n,["responseLogprobs"],y);let w=p(t,["responseMimeType"]);w!=null&&h(n,["responseMimeType"],w);let S=p(t,["responseModalities"]);S!=null&&h(n,["responseModalities"],S);let T=p(t,["responseSchema"]);T!=null&&h(n,["responseSchema"],T);let R=p(t,["routingConfig"]);R!=null&&h(n,["routingConfig"],R);let C=p(t,["seed"]);C!=null&&h(n,["seed"],C);let D=p(t,["speechConfig"]);D!=null&&h(n,["speechConfig"],mTe(D));let $=p(t,["stopSequences"]);$!=null&&h(n,["stopSequences"],$);let G=p(t,["temperature"]);G!=null&&h(n,["temperature"],G);let V=p(t,["thinkingConfig"]);V!=null&&h(n,["thinkingConfig"],V);let L=p(t,["topK"]);L!=null&&h(n,["topK"],L);let k=p(t,["topP"]);if(k!=null&&h(n,["topP"],k),p(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(p(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function bdt(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Tdt(t,e,n){let r={},i=p(e,["model"]);return i!=null&&h(r,["_url","name"],Kt(t,i)),r}function Adt(t,e){let n={},r=p(t,["authConfig"]);r!=null&&h(n,["authConfig"],Aut(r));let i=p(t,["enableWidget"]);if(i!=null&&h(n,["enableWidget"],i),p(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 Cdt(t,e){let n={};if(p(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(p(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=p(t,["searchTypes"]);r!=null&&h(n,["searchTypes"],r);let i=p(t,["timeRangeFilter"]);return i!=null&&h(n,["timeRangeFilter"],i),n}function Rdt(t,e){let n={},r=p(t,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);let i=p(t,["imageSize"]);if(i!=null&&h(n,["imageSize"],i),p(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(p(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(p(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(p(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(p(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 Idt(t,e){let n={},r=p(t,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);let i=p(t,["imageSize"]);i!=null&&h(n,["imageSize"],i);let s=p(t,["personGeneration"]);s!=null&&h(n,["personGeneration"],s);let o=p(t,["outputMimeType"]);o!=null&&h(n,["imageOutputOptions","mimeType"],o);let a=p(t,["outputCompressionQuality"]);a!=null&&h(n,["imageOutputOptions","compressionQuality"],a);let c=p(t,["imageOutputOptions"]);c!=null&&h(n,["imageOutputOptions"],c);let l=p(t,["prominentPeople"]);return l!=null&&h(n,["prominentPeople"],l),n}function pTe(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["bytesBase64Encoded"]);i!=null&&h(n,["imageBytes"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function a1(t,e){let n={};if(p(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["imageBytes"]);r!=null&&h(n,["bytesBase64Encoded"],vm(r));let i=p(t,["mimeType"]);return i!=null&&h(n,["mimeType"],i),n}function oc(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["imageBytes"]);i!=null&&h(n,["bytesBase64Encoded"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function kdt(t,e,n,r){let i={},s=p(e,["pageSize"]);n!==void 0&&s!=null&&h(n,["_query","pageSize"],s);let o=p(e,["pageToken"]);n!==void 0&&o!=null&&h(n,["_query","pageToken"],o);let a=p(e,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);let c=p(e,["queryBase"]);return n!==void 0&&c!=null&&h(n,["_url","models_url"],rTe(t,c)),i}function Pdt(t,e,n,r){let i={},s=p(e,["pageSize"]);n!==void 0&&s!=null&&h(n,["_query","pageSize"],s);let o=p(e,["pageToken"]);n!==void 0&&o!=null&&h(n,["_query","pageToken"],o);let a=p(e,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);let c=p(e,["queryBase"]);return n!==void 0&&c!=null&&h(n,["_url","models_url"],rTe(t,c)),i}function Odt(t,e,n){let r={},i=p(e,["config"]);return i!=null&&kdt(t,i,r),r}function Mdt(t,e,n){let r={},i=p(e,["config"]);return i!=null&&Pdt(t,i,r),r}function Ndt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["_self"]);if(s!=null){let o=iTe(s);Array.isArray(o)&&(o=o.map(a=>vV(a))),h(n,["models"],o)}return n}function Ddt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["_self"]);if(s!=null){let o=iTe(s);Array.isArray(o)&&(o=o.map(a=>EV(a))),h(n,["models"],o)}return n}function Ldt(t,e){let n={},r=p(t,["maskMode"]);r!=null&&h(n,["maskMode"],r);let i=p(t,["segmentationClasses"]);i!=null&&h(n,["maskClasses"],i);let s=p(t,["maskDilation"]);return s!=null&&h(n,["dilation"],s),n}function Udt(t,e){let n={};if(p(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(p(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 vV(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["displayName"]);i!=null&&h(n,["displayName"],i);let s=p(t,["description"]);s!=null&&h(n,["description"],s);let o=p(t,["version"]);o!=null&&h(n,["version"],o);let a=p(t,["_self"]);a!=null&&h(n,["tunedModelInfo"],ift(a));let c=p(t,["inputTokenLimit"]);c!=null&&h(n,["inputTokenLimit"],c);let l=p(t,["outputTokenLimit"]);l!=null&&h(n,["outputTokenLimit"],l);let u=p(t,["supportedGenerationMethods"]);u!=null&&h(n,["supportedActions"],u);let d=p(t,["temperature"]);d!=null&&h(n,["temperature"],d);let f=p(t,["maxTemperature"]);f!=null&&h(n,["maxTemperature"],f);let m=p(t,["topP"]);m!=null&&h(n,["topP"],m);let g=p(t,["topK"]);g!=null&&h(n,["topK"],g);let y=p(t,["thinking"]);return y!=null&&h(n,["thinking"],y),n}function EV(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["name"],r);let i=p(t,["displayName"]);i!=null&&h(n,["displayName"],i);let s=p(t,["description"]);s!=null&&h(n,["description"],s);let o=p(t,["versionId"]);o!=null&&h(n,["version"],o);let a=p(t,["deployedModels"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(m=>tdt(m))),h(n,["endpoints"],f)}let c=p(t,["labels"]);c!=null&&h(n,["labels"],c);let l=p(t,["_self"]);l!=null&&h(n,["tunedModelInfo"],sft(l));let u=p(t,["defaultCheckpointId"]);u!=null&&h(n,["defaultCheckpointId"],u);let d=p(t,["checkpoints"]);if(d!=null){let f=d;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["checkpoints"],f)}return n}function Fdt(t,e){let n={},r=p(t,["speakerVoiceConfigs"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>eft(s))),h(n,["speakerVoiceConfigs"],i)}return n}function Bdt(t,e){let n={},r=p(t,["mediaResolution"]);r!=null&&h(n,["mediaResolution"],r);let i=p(t,["toolCall"]);i!=null&&h(n,["toolCall"],i);let s=p(t,["toolResponse"]);s!=null&&h(n,["toolResponse"],s);let o=p(t,["audioTranscription"]);o!=null&&h(n,["audioTranscription"],o);let a=p(t,["codeExecutionResult"]);a!=null&&h(n,["codeExecutionResult"],a);let c=p(t,["executableCode"]);c!=null&&h(n,["executableCode"],c);let l=p(t,["fileData"]);l!=null&&h(n,["fileData"],ndt(l));let u=p(t,["functionCall"]);u!=null&&h(n,["functionCall"],rdt(u));let d=p(t,["functionResponse"]);d!=null&&h(n,["functionResponse"],d);let f=p(t,["inlineData"]);f!=null&&h(n,["inlineData"],Cut(f));let m=p(t,["text"]);m!=null&&h(n,["text"],m);let g=p(t,["thought"]);g!=null&&h(n,["thought"],g);let y=p(t,["thoughtSignature"]);y!=null&&h(n,["thoughtSignature"],y);let w=p(t,["videoMetadata"]);w!=null&&h(n,["videoMetadata"],w);let S=p(t,["partMetadata"]);S!=null&&h(n,["partMetadata"],S);let T=p(t,["mediaProcessing"]);return T!=null&&h(n,["mediaProcessing"],T),n}function qdt(t,e){let n={},r=p(t,["mediaResolution"]);if(r!=null&&h(n,["mediaResolution"],r),p(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(p(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=p(t,["audioTranscription"]);i!=null&&h(n,["audioTranscription"],i);let s=p(t,["codeExecutionResult"]);s!=null&&h(n,["codeExecutionResult"],s);let o=p(t,["executableCode"]);o!=null&&h(n,["executableCode"],o);let a=p(t,["fileData"]);a!=null&&h(n,["fileData"],a);let c=p(t,["functionCall"]);c!=null&&h(n,["functionCall"],c);let l=p(t,["functionResponse"]);l!=null&&h(n,["functionResponse"],l);let u=p(t,["inlineData"]);u!=null&&h(n,["inlineData"],u);let d=p(t,["text"]);d!=null&&h(n,["text"],d);let f=p(t,["thought"]);f!=null&&h(n,["thought"],f);let m=p(t,["thoughtSignature"]);m!=null&&h(n,["thoughtSignature"],m);let g=p(t,["videoMetadata"]);if(g!=null&&h(n,["videoMetadata"],g),p(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 y=p(t,["mediaProcessing"]);return y!=null&&h(n,["mediaProcessing"],y),n}function $dt(t,e){let n={},r=p(t,["productImage"]);return r!=null&&h(n,["image"],oc(r)),n}function Gdt(t,e,n){let r={},i=p(t,["numberOfImages"]);e!==void 0&&i!=null&&h(e,["parameters","sampleCount"],i);let s=p(t,["baseSteps"]);e!==void 0&&s!=null&&h(e,["parameters","baseSteps"],s);let o=p(t,["outputGcsUri"]);e!==void 0&&o!=null&&h(e,["parameters","storageUri"],o);let a=p(t,["seed"]);e!==void 0&&a!=null&&h(e,["parameters","seed"],a);let c=p(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&h(e,["parameters","safetySetting"],c);let l=p(t,["personGeneration"]);e!==void 0&&l!=null&&h(e,["parameters","personGeneration"],l);let u=p(t,["addWatermark"]);e!==void 0&&u!=null&&h(e,["parameters","addWatermark"],u);let d=p(t,["outputMimeType"]);e!==void 0&&d!=null&&h(e,["parameters","outputOptions","mimeType"],d);let f=p(t,["outputCompressionQuality"]);e!==void 0&&f!=null&&h(e,["parameters","outputOptions","compressionQuality"],f);let m=p(t,["enhancePrompt"]);e!==void 0&&m!=null&&h(e,["parameters","enhancePrompt"],m);let g=p(t,["labels"]);return e!==void 0&&g!=null&&h(e,["labels"],g),r}function Hdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["source"]);s!=null&&Wdt(s,r);let o=p(e,["config"]);return o!=null&&Gdt(o,r),r}function jdt(t,e){let n={},r=p(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>o1(s))),h(n,["generatedImages"],i)}return n}function Wdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["personImage"]);e!==void 0&&s!=null&&h(e,["instances[0]","personImage","image"],oc(s));let o=p(t,["productImages"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(c=>$dt(c))),h(e,["instances[0]","productImages"],a)}return r}function Vdt(t,e){let n={},r=p(t,["referenceImage"]);r!=null&&h(n,["referenceImage"],oc(r));let i=p(t,["referenceId"]);i!=null&&h(n,["referenceId"],i);let s=p(t,["referenceType"]);s!=null&&h(n,["referenceType"],s);let o=p(t,["maskImageConfig"]);o!=null&&h(n,["maskImageConfig"],Ldt(o));let a=p(t,["controlImageConfig"]);a!=null&&h(n,["controlImageConfig"],Dut(a));let c=p(t,["styleImageConfig"]);c!=null&&h(n,["styleImageConfig"],c);let l=p(t,["subjectImageConfig"]);return l!=null&&h(n,["subjectImageConfig"],l),n}function zdt(t,e){let n={},r=p(t,["mimeType"]);r!=null&&h(n,["mimeType"],r);let i=p(t,["voiceSampleAudio"]);if(i!=null&&h(n,["voiceSampleAudio"],i),p(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(p(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 hTe(t,e){let n={},r=p(t,["safetyAttributes","categories"]);r!=null&&h(n,["categories"],r);let i=p(t,["safetyAttributes","scores"]);i!=null&&h(n,["scores"],i);let s=p(t,["contentType"]);return s!=null&&h(n,["contentType"],s),n}function Kdt(t,e){let n={},r=p(t,["category"]);if(r!=null&&h(n,["category"],r),p(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=p(t,["threshold"]);return i!=null&&h(n,["threshold"],i),n}function Ydt(t,e){let n={},r=p(t,["image"]);return r!=null&&h(n,["image"],oc(r)),n}function Xdt(t,e,n){let r={},i=p(t,["mode"]);e!==void 0&&i!=null&&h(e,["parameters","mode"],i);let s=p(t,["maxPredictions"]);e!==void 0&&s!=null&&h(e,["parameters","maxPredictions"],s);let o=p(t,["confidenceThreshold"]);e!==void 0&&o!=null&&h(e,["parameters","confidenceThreshold"],o);let a=p(t,["maskDilation"]);e!==void 0&&a!=null&&h(e,["parameters","maskDilation"],a);let c=p(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&h(e,["parameters","binaryColorThreshold"],c);let l=p(t,["labels"]);return e!==void 0&&l!=null&&h(e,["labels"],l),r}function Jdt(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["source"]);s!=null&&Zdt(s,r);let o=p(e,["config"]);return o!=null&&Xdt(o,r),r}function Qdt(t,e){let n={},r=p(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>Edt(s))),h(n,["generatedMasks"],i)}return n}function Zdt(t,e,n){let r={},i=p(t,["prompt"]);e!==void 0&&i!=null&&h(e,["instances[0]","prompt"],i);let s=p(t,["image"]);e!==void 0&&s!=null&&h(e,["instances[0]","image"],oc(s));let o=p(t,["scribbleImage"]);return e!==void 0&&o!=null&&h(e,["instances[0]","scribble"],Ydt(o)),r}function eft(t,e){let n={},r=p(t,["speaker"]);r!=null&&h(n,["speaker"],r);let i=p(t,["voiceConfig"]);return i!=null&&h(n,["voiceConfig"],vTe(i)),n}function mTe(t,e){let n={},r=p(t,["voiceConfig"]);r!=null&&h(n,["voiceConfig"],vTe(r));let i=p(t,["languageCode"]);i!=null&&h(n,["languageCode"],i);let s=p(t,["multiSpeakerVoiceConfig"]);return s!=null&&h(n,["multiSpeakerVoiceConfig"],Fdt(s)),n}function tft(t,e){let n={},r=p(t,["functionCallingConfig"]);r!=null&&h(n,["functionCallingConfig"],idt(r));let i=p(t,["retrievalConfig"]);i!=null&&h(n,["retrievalConfig"],i);let s=p(t,["includeServerSideToolInvocations"]);return s!=null&&h(n,["includeServerSideToolInvocations"],s),n}function nft(t,e){let n={},r=p(t,["functionCallingConfig"]);r!=null&&h(n,["functionCallingConfig"],r);let i=p(t,["retrievalConfig"]);if(i!=null&&h(n,["retrievalConfig"],i),p(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 rft(t,e){let n={};if(p(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=p(t,["googleMaps"]);r!=null&&h(n,["googleMaps"],Adt(r));let i=p(t,["mcpServers"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["mcpServers"],f)}let s=p(t,["codeExecution"]);s!=null&&h(n,["codeExecution"],s);let o=p(t,["computerUse"]);if(o!=null&&h(n,["computerUse"],o),p(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(p(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=p(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(m=>m)),h(n,["functionDeclarations"],f)}let c=p(t,["googleSearch"]);c!=null&&h(n,["googleSearch"],Cdt(c));let l=p(t,["googleSearchRetrieval"]);if(l!=null&&h(n,["googleSearchRetrieval"],l),p(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 u=p(t,["urlContext"]);u!=null&&h(n,["urlContext"],u);let d=p(t,["fileSearch"]);return d!=null&&h(n,["fileSearch"],d),n}function gTe(t,e){let n={},r=p(t,["retrieval"]);r!=null&&h(n,["retrieval"],r);let i=p(t,["googleMaps"]);i!=null&&h(n,["googleMaps"],i);let s=p(t,["mcpServers"]);if(s!=null){let y=s;Array.isArray(y)&&(y=y.map(w=>Udt(w))),h(n,["mcpServers"],y)}let o=p(t,["codeExecution"]);o!=null&&h(n,["codeExecution"],o);let a=p(t,["computerUse"]);a!=null&&h(n,["computerUse"],Out(a));let c=p(t,["enterpriseWebSearch"]);c!=null&&h(n,["enterpriseWebSearch"],c);let l=p(t,["exaAiSearch"]);l!=null&&h(n,["exaAiSearch"],l);let u=p(t,["functionDeclarations"]);if(u!=null){let y=u;Array.isArray(y)&&(y=y.map(w=>w)),h(n,["functionDeclarations"],y)}let d=p(t,["googleSearch"]);d!=null&&h(n,["googleSearch"],d);let f=p(t,["googleSearchRetrieval"]);f!=null&&h(n,["googleSearchRetrieval"],f);let m=p(t,["parallelAiSearch"]);m!=null&&h(n,["parallelAiSearch"],m);let g=p(t,["urlContext"]);if(g!=null&&h(n,["urlContext"],g),p(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 ift(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["createTime"]);i!=null&&h(n,["createTime"],i);let s=p(t,["updateTime"]);return s!=null&&h(n,["updateTime"],s),n}function sft(t,e){let n={},r=p(t,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["createTime"]);i!=null&&h(n,["createTime"],i);let s=p(t,["updateTime"]);return s!=null&&h(n,["updateTime"],s),n}function oft(t,e,n){let r={},i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["description"]);e!==void 0&&s!=null&&h(e,["description"],s);let o=p(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&h(e,["defaultCheckpointId"],o),r}function aft(t,e,n){let r={},i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["description"]);e!==void 0&&s!=null&&h(e,["description"],s);let o=p(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&h(e,["defaultCheckpointId"],o),r}function cft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","name"],Kt(t,i));let s=p(e,["config"]);return s!=null&&oft(s,r),r}function lft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["config"]);return s!=null&&aft(s,r),r}function uft(t,e,n){let r={},i=p(t,["outputGcsUri"]);e!==void 0&&i!=null&&h(e,["parameters","storageUri"],i);let s=p(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&h(e,["parameters","safetySetting"],s);let o=p(t,["personGeneration"]);e!==void 0&&o!=null&&h(e,["parameters","personGeneration"],o);let a=p(t,["includeRaiReason"]);e!==void 0&&a!=null&&h(e,["parameters","includeRaiReason"],a);let c=p(t,["outputMimeType"]);e!==void 0&&c!=null&&h(e,["parameters","outputOptions","mimeType"],c);let l=p(t,["outputCompressionQuality"]);e!==void 0&&l!=null&&h(e,["parameters","outputOptions","compressionQuality"],l);let u=p(t,["enhanceInputImage"]);e!==void 0&&u!=null&&h(e,["parameters","upscaleConfig","enhanceInputImage"],u);let d=p(t,["imagePreservationFactor"]);e!==void 0&&d!=null&&h(e,["parameters","upscaleConfig","imagePreservationFactor"],d);let f=p(t,["labels"]);e!==void 0&&f!=null&&h(e,["labels"],f);let m=p(t,["numberOfImages"]);e!==void 0&&m!=null&&h(e,["parameters","sampleCount"],m);let g=p(t,["mode"]);return e!==void 0&&g!=null&&h(e,["parameters","mode"],g),r}function dft(t,e,n){let r={},i=p(e,["model"]);i!=null&&h(r,["_url","model"],Kt(t,i));let s=p(e,["image"]);s!=null&&h(r,["instances[0]","image"],oc(s));let o=p(e,["upscaleFactor"]);o!=null&&h(r,["parameters","upscaleConfig","upscaleFactor"],o);let a=p(e,["config"]);return a!=null&&uft(a,r),r}function fft(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o1(o))),h(n,["generatedImages"],s)}return n}function pft(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["uri"],r);let i=p(t,["encodedVideo"]);i!=null&&h(n,["videoBytes"],vm(i));let s=p(t,["encoding"]);return s!=null&&h(n,["mimeType"],s),n}function hft(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["uri"],r);let i=p(t,["bytesBase64Encoded"]);i!=null&&h(n,["videoBytes"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function mft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["_self"],oc(r));let i=p(t,["maskMode"]);return i!=null&&h(n,["maskMode"],i),n}function gft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["image"],a1(r));let i=p(t,["referenceType"]);return i!=null&&h(n,["referenceType"],i),n}function yft(t,e){let n={},r=p(t,["image"]);r!=null&&h(n,["image"],oc(r));let i=p(t,["referenceType"]);return i!=null&&h(n,["referenceType"],i),n}function yTe(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["uri"],r);let i=p(t,["videoBytes"]);i!=null&&h(n,["encodedVideo"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["encoding"],s),n}function _Te(t,e){let n={},r=p(t,["uri"]);r!=null&&h(n,["gcsUri"],r);let i=p(t,["videoBytes"]);i!=null&&h(n,["bytesBase64Encoded"],vm(i));let s=p(t,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function vTe(t,e){let n={},r=p(t,["replicatedVoiceConfig"]);r!=null&&h(n,["replicatedVoiceConfig"],zdt(r));let i=p(t,["prebuiltVoiceConfig"]);return i!=null&&h(n,["prebuiltVoiceConfig"],i),n}function _ft(t,e,n){let r={},i=p(e,["displayName"]);n!==void 0&&i!=null&&h(n,["displayName"],i);let s=p(e,["embeddingModel"]);return n!==void 0&&s!=null&&h(n,["embeddingModel"],Kt(t,s)),r}function vft(t,e){let n={},r=p(e,["config"]);return r!=null&&_ft(t,r,n),n}function Eft(t,e){let n={},r=p(t,["force"]);return e!==void 0&&r!=null&&h(e,["_query","force"],r),n}function wft(t){let e={},n=p(t,["name"]);n!=null&&h(e,["_url","name"],n);let r=p(t,["config"]);return r!=null&&Eft(r,e),e}function Sft(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","name"],n),e}function xft(t,e){let n={},r=p(t,["customMetadata"]);if(e!==void 0&&r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["customMetadata"],s)}let i=p(t,["chunkingConfig"]);return e!==void 0&&i!=null&&h(e,["chunkingConfig"],i),n}function bft(t){let e={},n=p(t,["name"]);n!=null&&h(e,["name"],n);let r=p(t,["metadata"]);r!=null&&h(e,["metadata"],r);let i=p(t,["done"]);i!=null&&h(e,["done"],i);let s=p(t,["error"]);s!=null&&h(e,["error"],s);let o=p(t,["response"]);return o!=null&&h(e,["response"],Aft(o)),e}function Tft(t){let e={},n=p(t,["fileSearchStoreName"]);n!=null&&h(e,["_url","file_search_store_name"],n);let r=p(t,["fileName"]);r!=null&&h(e,["fileName"],r);let i=p(t,["config"]);return i!=null&&xft(i,e),e}function Aft(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["parent"]);r!=null&&h(e,["parent"],r);let i=p(t,["documentName"]);return i!=null&&h(e,["documentName"],i),e}function Cft(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function Rft(t){let e={},n=p(t,["config"]);return n!=null&&Cft(n,e),e}function Ift(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["fileSearchStores"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["fileSearchStores"],s)}return e}function ETe(t,e){let n={},r=p(t,["mimeType"]);e!==void 0&&r!=null&&h(e,["mimeType"],r);let i=p(t,["displayName"]);e!==void 0&&i!=null&&h(e,["displayName"],i);let s=p(t,["customMetadata"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>c)),h(e,["customMetadata"],a)}let o=p(t,["chunkingConfig"]);return e!==void 0&&o!=null&&h(e,["chunkingConfig"],o),n}function kft(t){let e={},n=p(t,["fileSearchStoreName"]);n!=null&&h(e,["_url","file_search_store_name"],n);let r=p(t,["config"]);return r!=null&&ETe(r,e),e}function Pft(t){let e={},n=p(t,["sdkHttpResponse"]);return n!=null&&h(e,["sdkHttpResponse"],n),e}function qft(t){let n=globalThis[Symbol.for("undici.globalDispatcher.1")];if(n)for(let r of Object.getOwnPropertySymbols(n)){let i=r.description;if(i?.includes("headers timeout")||i?.includes("body timeout")){let s=n[r];typeof s=="number"&&(n[r]=Math.max(s,t))}}}function $ft(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 s=()=>r.abort();return e&&(e.aborted?r.abort():e.addEventListener("abort",s)),{signal:r.signal,dispose:()=>{i!==void 0&&clearTimeout(i),e?.removeEventListener("abort",s)}}}async function _W(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 sx({message:i,status:n}):new Error(i)}}function Kft(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{let s=JSON.parse(t.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))n=s;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function r(s,o){let a=Object.assign({},s);for(let c in o)if(Object.prototype.hasOwnProperty.call(o,c)){let l=o[c],u=a[c];l&&typeof l=="object"&&!Array.isArray(l)&&u&&typeof u=="object"&&!Array.isArray(u)?a[c]=r(u,l):(u&&l&&typeof u!=typeof l&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof u}, New type: ${typeof l}. Overwriting.`),a[c]=l)}return a}let i=r(n,e);t.body=JSON.stringify(i)}function STe(t){for(let e of t)if(Xft(e)||typeof e=="object"&&"inputSchema"in e)return!0;return wTe}function xTe(t){var e;let n=(e=t[wV])!==null&&e!==void 0?e:"";t[wV]=(n+` ${Yft}`).trimStart()}function Xft(t){return t!==null&&typeof t=="object"&&t instanceof ox}function Jft(t){return pv(this,arguments,function*(n,r=100){let i,s=0;for(;s<r;){let o=yield Hn(n.listTools({cursor:i}));for(let a of o.tools)yield yield Hn(a),s++;if(!o.nextCursor)break;i=o.nextCursor}})}function Qft(t){return t!==null&&typeof t=="object"&&"listTools"in t&&typeof t.listTools=="function"}function Zft(...t){if(wTe=!0,t.length===0)throw new Error("No MCP clients provided");let e=t[t.length-1];return Qft(e)?ox.create(t,{}):ox.create(t.slice(0,t.length-1),e)}async function ept(t,e,n){let r=new $O,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(r,i),e(r)}function tpt(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function npt(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}async function ipt(t,e,n){let r=new qO,i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;let s=JSON.parse(i);if(t.isVertexAI()){let o=put(s);Object.assign(r,o)}else Object.assign(r,s);e(r)}function opt(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function apt(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}function vbe(t){var e,n,r;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let o of(n=t?.tools)!==null&&n!==void 0?n:[])if(hv(o)){i=!0;break}if(!i)return!0;let s=(r=t?.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0):!1}function hv(t){return"callTool"in t&&typeof t.callTool=="function"}function cpt(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=>hv(i)))!==null&&r!==void 0?r:!1}function Ebe(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((r,i)=>{if(hv(r))return;let s=r;s.functionDeclarations&&s.functionDeclarations.length>0&&n.push(i)}),n}function wbe(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}function lpt(t){let e={},n=p(t,["apiKey"]);if(n!=null&&h(e,["apiKey"],n),p(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(p(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(p(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(p(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(p(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(p(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 upt(t){let e={},n=p(t,["data"]);if(n!=null&&h(e,["data"],n),p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function dpt(t){let e={},n=p(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Ept(s))),h(e,["parts"],i)}let r=p(t,["role"]);return r!=null&&h(e,["role"],r),e}function fpt(t,e,n){let r={},i=p(e,["expireTime"]);n!==void 0&&i!=null&&h(n,["expireTime"],i);let s=p(e,["newSessionExpireTime"]);n!==void 0&&s!=null&&h(n,["newSessionExpireTime"],s);let o=p(e,["uses"]);n!==void 0&&o!=null&&h(n,["uses"],o);let a=p(e,["liveConnectConstraints"]);n!==void 0&&a!=null&&h(n,["bidiGenerateContentSetup"],vpt(t,a));let c=p(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&h(n,["fieldMask"],c),r}function ppt(t,e){let n={},r=p(e,["config"]);return r!=null&&h(n,["config"],fpt(t,r,n)),n}function hpt(t){let e={};if(p(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=p(t,["fileUri"]);n!=null&&h(e,["fileUri"],n);let r=p(t,["mimeType"]);return r!=null&&h(e,["mimeType"],r),e}function mpt(t){let e={},n=p(t,["args"]);n!=null&&h(e,["args"],n);let r=p(t,["id"]);r!=null&&h(e,["id"],r);let i=p(t,["name"]);if(i!=null&&h(e,["name"],i),p(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(p(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 gpt(t){let e={},n=p(t,["authConfig"]);n!=null&&h(e,["authConfig"],lpt(n));let r=p(t,["enableWidget"]);if(r!=null&&h(e,["enableWidget"],r),p(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 ypt(t){let e={};if(p(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(p(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=p(t,["searchTypes"]);n!=null&&h(e,["searchTypes"],n);let r=p(t,["timeRangeFilter"]);return r!=null&&h(e,["timeRangeFilter"],r),e}function _pt(t,e){let n={},r=p(t,["generationConfig"]);e!==void 0&&r!=null&&h(e,["setup","generationConfig"],r);let i=p(t,["responseModalities"]);e!==void 0&&i!=null&&h(e,["setup","generationConfig","responseModalities"],i);let s=p(t,["temperature"]);e!==void 0&&s!=null&&h(e,["setup","generationConfig","temperature"],s);let o=p(t,["topP"]);e!==void 0&&o!=null&&h(e,["setup","generationConfig","topP"],o);let a=p(t,["topK"]);e!==void 0&&a!=null&&h(e,["setup","generationConfig","topK"],a);let c=p(t,["maxOutputTokens"]);e!==void 0&&c!=null&&h(e,["setup","generationConfig","maxOutputTokens"],c);let l=p(t,["mediaResolution"]);e!==void 0&&l!=null&&h(e,["setup","generationConfig","mediaResolution"],l);let u=p(t,["seed"]);e!==void 0&&u!=null&&h(e,["setup","generationConfig","seed"],u);let d=p(t,["speechConfig"]);e!==void 0&&d!=null&&h(e,["setup","generationConfig","speechConfig"],Az(d));let f=p(t,["thinkingConfig"]);e!==void 0&&f!=null&&h(e,["setup","generationConfig","thinkingConfig"],f);let m=p(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&h(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=p(t,["systemInstruction"]);e!==void 0&&g!=null&&h(e,["setup","systemInstruction"],dpt(Qr(g)));let y=p(t,["tools"]);if(e!==void 0&&y!=null){let L=yv(y);Array.isArray(L)&&(L=L.map(k=>xpt(gv(k)))),h(e,["setup","tools"],L)}let w=p(t,["sessionResumption"]);e!==void 0&&w!=null&&h(e,["setup","sessionResumption"],Spt(w));let S=p(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&h(e,["setup","inputAudioTranscription"],S);let T=p(t,["outputAudioTranscription"]);e!==void 0&&T!=null&&h(e,["setup","outputAudioTranscription"],T);let R=p(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&h(e,["setup","realtimeInputConfig"],R);let C=p(t,["contextWindowCompression"]);e!==void 0&&C!=null&&h(e,["setup","contextWindowCompression"],C);let D=p(t,["proactivity"]);if(e!==void 0&&D!=null&&h(e,["setup","proactivity"],D),p(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let $=p(t,["avatarConfig"]);e!==void 0&&$!=null&&h(e,["setup","avatarConfig"],$);let G=p(t,["safetySettings"]);if(e!==void 0&&G!=null){let L=G;Array.isArray(L)&&(L=L.map(k=>wpt(k))),h(e,["setup","safetySettings"],L)}let V=p(t,["translationConfig"]);return e!==void 0&&V!=null&&h(e,["setup","generationConfig","translationConfig"],V),n}function vpt(t,e){let n={},r=p(e,["model"]);r!=null&&h(n,["setup","model"],Kt(t,r));let i=p(e,["config"]);return i!=null&&h(n,["config"],_pt(i,n)),n}function Ept(t){let e={},n=p(t,["mediaResolution"]);n!=null&&h(e,["mediaResolution"],n);let r=p(t,["toolCall"]);r!=null&&h(e,["toolCall"],r);let i=p(t,["toolResponse"]);i!=null&&h(e,["toolResponse"],i);let s=p(t,["audioTranscription"]);s!=null&&h(e,["audioTranscription"],s);let o=p(t,["codeExecutionResult"]);o!=null&&h(e,["codeExecutionResult"],o);let a=p(t,["executableCode"]);a!=null&&h(e,["executableCode"],a);let c=p(t,["fileData"]);c!=null&&h(e,["fileData"],hpt(c));let l=p(t,["functionCall"]);l!=null&&h(e,["functionCall"],mpt(l));let u=p(t,["functionResponse"]);u!=null&&h(e,["functionResponse"],u);let d=p(t,["inlineData"]);d!=null&&h(e,["inlineData"],upt(d));let f=p(t,["text"]);f!=null&&h(e,["text"],f);let m=p(t,["thought"]);m!=null&&h(e,["thought"],m);let g=p(t,["thoughtSignature"]);g!=null&&h(e,["thoughtSignature"],g);let y=p(t,["videoMetadata"]);y!=null&&h(e,["videoMetadata"],y);let w=p(t,["partMetadata"]);w!=null&&h(e,["partMetadata"],w);let S=p(t,["mediaProcessing"]);return S!=null&&h(e,["mediaProcessing"],S),e}function wpt(t){let e={},n=p(t,["category"]);if(n!=null&&h(e,["category"],n),p(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=p(t,["threshold"]);return r!=null&&h(e,["threshold"],r),e}function Spt(t){let e={},n=p(t,["handle"]);if(n!=null&&h(e,["handle"],n),p(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 xpt(t){let e={};if(p(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=p(t,["googleMaps"]);n!=null&&h(e,["googleMaps"],gpt(n));let r=p(t,["mcpServers"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["mcpServers"],d)}let i=p(t,["codeExecution"]);i!=null&&h(e,["codeExecution"],i);let s=p(t,["computerUse"]);if(s!=null&&h(e,["computerUse"],s),p(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(p(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 o=p(t,["functionDeclarations"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),h(e,["functionDeclarations"],d)}let a=p(t,["googleSearch"]);a!=null&&h(e,["googleSearch"],ypt(a));let c=p(t,["googleSearchRetrieval"]);if(c!=null&&h(e,["googleSearchRetrieval"],c),p(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 l=p(t,["urlContext"]);l!=null&&h(e,["urlContext"],l);let u=p(t,["fileSearch"]);return u!=null&&h(e,["fileSearch"],u),e}function bpt(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&&Object.keys(r).length>0){let i=Object.keys(r).map(s=>`${n}.${s}`);e.push(...i)}else e.push(n)}return e.join(",")}function Tpt(t,e){let n=null,r=t.bidiGenerateContentSetup;if(typeof r=="object"&&r!==null&&"setup"in r){let s=r.setup;typeof s=="object"&&s!==null?(t.bidiGenerateContentSetup=s,n=s):delete t.bidiGenerateContentSetup}else r!==void 0&&delete t.bidiGenerateContentSetup;let i=t.fieldMask;if(n){let s=bpt(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)s?t.fieldMask=s:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let o=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],a=[];i.length>0&&(a=i.map(l=>o.includes(l)?`generationConfig.${l}`:l));let c=[];s&&c.push(s),a.length>0&&c.push(...a),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}function Apt(t,e){let n={},r=p(t,["force"]);return e!==void 0&&r!=null&&h(e,["_query","force"],r),n}function Cpt(t){let e={},n=p(t,["name"]);n!=null&&h(e,["_url","name"],n);let r=p(t,["config"]);return r!=null&&Apt(r,e),e}function Rpt(t){let e={},n=p(t,["name"]);return n!=null&&h(e,["_url","name"],n),e}function Ipt(t,e){let n={},r=p(t,["pageSize"]);e!==void 0&&r!=null&&h(e,["_query","pageSize"],r);let i=p(t,["pageToken"]);return e!==void 0&&i!=null&&h(e,["_query","pageToken"],i),n}function kpt(t){let e={},n=p(t,["parent"]);n!=null&&h(e,["_url","parent"],n);let r=p(t,["config"]);return r!=null&&Ipt(r,e),e}function Ppt(t){let e={},n=p(t,["sdkHttpResponse"]);n!=null&&h(e,["sdkHttpResponse"],n);let r=p(t,["nextPageToken"]);r!=null&&h(e,["nextPageToken"],r);let i=p(t,["documents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),h(e,["documents"],s)}return e}function Opt(){return"Deno"in globalThis}function ax(){var t,e,n,r,i,s;if(gO)return gO;let o=globalThis,a={};return Opt()?a=(r=(n=(e=(t=o.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:{}:a=(s=(i=o.process)===null||i===void 0?void 0:i.env)!==null&&s!==void 0?s:{},gO=a,gO}function Mpt(t){var e,n;let r=Object.assign({},t),i=ax();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}function Npt(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 Dpt(t,e){if(TTe(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return bTe(n)?Sbe(n):Sbe(void 0)}function Lpt(t){var e,n;if(TTe(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(bTe(t))return t.default_headers}function Sbe(t){var e,n;let r=ax(),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 ATe(i)?i:void 0}function Upt(t){var e,n;let r={};for(let[s,o]of t){let a=s.toLowerCase();a!=="authorization"&&a!=="x-goog-api-key"&&(r[s]=o)}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 ATe(i)?i:void 0}function xbe(t,e){if(e)for(let[n,r]of new Headers(e))t.get(n)===null&&t.set(n,r)}function Fpt(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 Bpt(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",$pt(e.access_token))}}function qpt(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function $pt(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function bTe(t){return typeof t=="object"&&t!==null}function TTe(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function ATe(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}function ym(t){return Vpt(t)?t:t instanceof na?Gpt(t):t instanceof Gf?Hpt(t):t}function Gpt(t){let e=jpt(t),n=ys.generate(t.statusCode,e,t.message,t.headers);return jS(n,"body",t.body),jS(n,"contentType",t.contentType),jS(n,"rawResponse",t.rawResponse),jS(n,"statusCode",t.statusCode),jS(n,"cause",t),n}function Hpt(t){return t instanceof ZO?new PV({message:t.message}):t instanceof QO?new kV({message:t.message}):t instanceof e1?new mv({message:t.message,cause:t}):new mv({message:t.message,cause:t})}function jpt(t){let e=bbe(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=bbe(t,"error");return n&&typeof n=="object"?n:void 0}function bbe(t,e){return t&&typeof t=="object"?t[e]:void 0}function Tbe(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function Wpt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vpt(t){return typeof t=="object"&&t!==null?ys.prototype.isPrototypeOf(t):!1}function jS(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function uv(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(Abe),[s="",...o]=i;if(s.split("/").length!==2)return!1;let a=r.split(Abe),[c="",...l]=a,[u="",d=""]=c.split("/");if(!u||!d||s!=="*/*"&&c!==s&&`${u}/*`!==s&&`*/${d}`!==s||l.length<o.length)return!1;let f=new Set(l);for(let m of o)if(!f.has(m))return!1;return!0}function kt(t,e){let n=`${t.status}`,r=Array.isArray(e)?e:[e];return r.length?r.some(i=>{let s=`${i}`;if(s==="default")return!0;if(!Kpt.test(`${s}`))return s===n;let o=s.charAt(0);if(!o)throw new Error("Invalid status code range");let a=n.charAt(0);if(!a)throw new Error(`Invalid response status code: ${n}`);return a===o}):!1}function Ypt(t,e,n){return kt(t,e)&&uv(t,n)}function CTe(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 RTe(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 Xpt(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 Jpt(t){let e=new RV;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}function Cbe(t){return{ok:!0,value:t}}function ju(t){return{ok:!1,error:t}}function Rz(t){return btoa(String.fromCodePoint(...t))}function Qpt(t){return new TextEncoder().encode(t)}function Zpt(t){return Rz(Qpt(t))}function Mt(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(i={}){return t.replace(n,function(s,o){if(!eht.call(i,o))throw new Error(`Parameter '${o}' is required`);let a=i[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Parameter '${o}' must be a string or number`);return`${a}`}).replace(/^\/+/,"")}}function tht(t){var e;let n=t.server_url,r={};if(!n){let s=(e=t.server_idx)!==null&&e!==void 0?e:0;if(s<0||s>=Rbe.length)throw new Error(`Invalid server index ${s}`);n=Rbe[s]||""}let i=Mt(n)(r);return new URL(i)}function rht(...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):iht(e)}}function iht(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 o of t)if(o.aborted)return o;function r(){e.abort(this.reason),s()}let i=[];function s(){for(let o of i){let a=o.deref();a&&a.removeEventListener("abort",r)}}for(let o of t)i.push(new WeakRef(o)),o.addEventListener("abort",r);return n}function $t(t){let e={};for(let[n,r]of Object.entries(t))typeof r<"u"&&(e[n]=r);return e}function Hf(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}function ITe(t,e){return c1(t,e==="percentExceptReserved"?"percent":e)}function c1(t,e){switch(e){case"percent":return encodeURIComponent(t);case"percentExceptReserved":return encodeURIComponent(t).replace(sht,n=>decodeURIComponent(n));default:return t}}function oht(t){return(e,n,r)=>{let i="",s=r?.explode?PTe(e,n):[[e,n]];if(s.every(([l,u])=>u==null))return;let o=l=>c1(l,r?.charEncoding),a=l=>o(OTe(l)),c=o(t);return s.forEach(([l,u])=>{var d,f;let m="",g=null;u!=null&&(Array.isArray(u)?g=(d=NTe(u,y=>`${a(y)}`))===null||d===void 0?void 0:d.join(c):Hf(u)?g=(f=DTe(Object.entries(u),([y,w])=>`${o(y)}${c}${a(w)}`))===null||f===void 0?void 0:f.join(c):g=`${a(u)}`,g!=null&&(m=`${ITe(l,r?.charEncoding)}=${g}`,!(!m||m==="=")&&(i+=`&${m}`)))}),i.slice(1)}}function ac(t,e,n){if(typeof e>"u")return;let i=(s=>c1(s,n?.charEncoding))(JSON.stringify(e,MTe));return n?.explode?i:`${ITe(t,n?.charEncoding)}=${i}`}function PTe(t,e){return Array.isArray(e)?e.map(n=>[t,n]):Hf(e)?Object.entries(e??{}).map(([r,i])=>[r,i]):[[t,e]]}function OTe(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?Rz(t):typeof t=="object"?JSON.stringify(t,MTe):`${t}`}function MTe(t,e){return e instanceof Uint8Array?Rz(e):e}function NTe(t,e){let n=t.reduce((r,i)=>{if(i==null)return r;let s=e(i);return s==null||r.push(s),r},[]);return n.length?n:null}function DTe(t,e){let n=[];for(let[r,i]of t){if(i==null)continue;let s=e([r,i]);s!=null&&n.push(s)}return n.length?n:null}function aht(...t){return t.filter(Boolean).join("&")}function cht(t){return function(n,r){var i,s,o;let a=Object.assign(Object.assign({},r),{explode:(i=r?.explode)!==null&&i!==void 0?i:!0,charEncoding:(s=r?.charEncoding)!==null&&s!==void 0?s:"percent"}),c=new Set((o=r?.allowEmptyValue)!==null&&o!==void 0?o:[]),l=Object.entries(n).map(([u,d])=>c.has(u)&&(d==null||d===""||Array.isArray(d)&&d.length===0)?`${encodeURIComponent(u)}=`:t(u,d,a));return aht(...l)}}async function lht(t,e){var n;switch(e.config.strategy){case"backoff":return fht(kbe(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:Ibe);case"attempt-count-backoff":return pht(kbe(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},Ibe),e.config.backoff),e.config);default:return await t(0)}}function kbe(t,e){return async n=>{try{let r=await t(n);if(dht(r,e.statusCodes))throw new jf("Response failed with retryable status code",r);return r}catch(r){throw r instanceof jf||e.retryConnectionErrors&&(RTe(r)||CTe(r))?r:new cx("Permanent error",{cause:r})}}}function dht(t,e){let n=`${t.status}`;return e.some(r=>{if(!uht.test(r))return r===n;let i=r.charAt(0);if(!i)throw new Error("Invalid status code range");let s=n.charAt(0);if(!s)throw new Error(`Invalid response status code: ${n}`);return s===i})}async function fht(t,e){let{maxElapsedTime:n,initialInterval:r,exponent:i,maxInterval:s}=e,o=Date.now(),a=0;for(;;)try{return await t(a)}catch(c){if(c instanceof cx)throw c.cause;if(Date.now()-o>n){if(c instanceof jf)return c.response;throw c}let u=0;c instanceof jf&&(u=LTe(c.response)),u<=0&&(u=r*Math.pow(a,i)+Math.random()*1e3);let d=Math.min(u,s);await UTe(d),a++}}async function pht(t,e,n){let r=0;for(;;)try{return await t(r)}catch(i){if(i instanceof cx)throw i.cause;if(r>=n.maxRetries){if(i instanceof jf)return i.response;throw i}let s=0;i instanceof jf&&(s=LTe(i.response)),s<=0&&(s=e.initialInterval*Math.pow(e.exponent,r)*(1-Math.random()*.25));let o=Math.min(s,e.maxInterval);await UTe(o),r++}}function LTe(t){let e=t.headers.get("retry-after-ms");if(e){let s=Number(e);if(Number.isFinite(s)&&s>=0)return s}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 s=i-Date.now();return s>0?Math.ceil(s):0}return 0}async function UTe(t){return new Promise(e=>setTimeout(e,t))}async function ght(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,s]of e.headers.entries())t.log(`${i}: ${s}`);switch(t.groupEnd(),t.group("Body:"),!0){case FTe.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[s,o]of i){let a=o instanceof Blob?"<Blob>":o;t.log(`${s}: ${a}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function yht(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[s,o]of e.headers.entries())t.log(`${s}: ${o}`);switch(t.groupEnd(),t.group("Body:"),!0){case(uv(e,"application/json")||FTe.test(i)&&!Pbe.test(i)):t.log(await e.clone().json());break;case(uv(e,"application/jsonl")||Pbe.test(i)):case uv(e,"text/event-stream"):t.log(`<${r}>`);break;case uv(e,"text/*"):t.log(await e.clone().text());break;case uv(e,"multipart/form-data"):{let s=await e.clone().formData();for(let[o,a]of s){let c=a instanceof Blob?"<Blob>":a;t.log(`${o}: ${c}`)}break}default:t.log(`<${r}>`);break}t.groupEnd(),t.groupEnd()}function Obe(t){try{return JSON.parse(t)}catch{return t}}function _ht(t,e={}){var n,r;let i=e.flattened===!0,s=(n=e.sentinel)!==null&&n!==void 0?n:"";return new qV(t,o=>s!==""&&o.data===s?{done:!0,value:void 0}:i?{done:!1,value:o.data==null?void 0:Obe(o.data)}:{done:!1,value:Object.assign(Object.assign({},o),{data:o.data==null?o.data:Obe(o.data)})},{dataRequired:(r=e.dataRequired)!==null&&r!==void 0?r:!0})}function Eht(t,e,n){for(let r=n;r<e;r++)if(!(t[r]!==ea&&t[r]!==ta))for(let i of BTe){if(r+i.length>e)continue;let s=!0;for(let o=0;o<i.length;o++)if(t[r+o]!==i[o]){s=!1;break}if(s)return{index:r,length:i.length}}return null}function wht(t,e,n,r){let s=new TextDecoder().decode(t).split(/\r\n|\r|\n/),o=[],a={},c=!0;for(let l of s){if(!l||l.startsWith(":"))continue;c=!1;let u=l.indexOf(":"),d=l,f="";u>0&&(d=l.slice(0,u),f=l[u+1]===" "?l.slice(u+2):l.slice(u+1)),d==="data"?o.push(f):d==="event"?a.event=f:d==="id"&&!f.includes("\0")?n.eventId=f:d==="retry"&&/^\d+$/.test(f)&&(a.retry=Number(f))}if(!c){if(a.id=n.eventId,o.length)a.data=o.join(`
524
+ `);else if(r)return;return e(a)}}function Wf(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function tn(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function qTe(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function $Te(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function Be(t){return{enc:"fail",codes:t}}function Gt(...t){return async function(n,r,i){let s,o;for(let f of t){let{codes:m}=f,g="ctype"in f?f.ctype:Sht[f.enc];if(g&&Ypt(n,m,g)){o=f;break}else if(!g&&kt(n,m)){o=f;break}}if(!o)return[{ok:!1,error:new r1("Unexpected Status or Content-Type",{response:n,request:r,body:await n.text().catch(()=>"")})},s];let a=o.enc,c="";switch(a){case"json":c=await n.text();try{s=JSON.parse(c)}catch(f){if(!("err"in o))throw f;s=c}break;case"jsonl":s=n.body;break;case"bytes":s=new Uint8Array(await n.arrayBuffer());break;case"stream":s=n.body;break;case"text":c=await n.text(),s=c;break;case"sse":if(n.body){let f="sse"in o&&o.sse||{};s=_ht(n.body,f)}else s=null;break;case"nil":c=await n.text(),s=void 0;break;case"fail":c=await n.text(),s=c;break;default:throw new Error(`Unsupported response type: ${a}`)}if(o.enc==="fail")return[{ok:!1,error:new r1("API error occurred",{request:r,response:n,body:c})},s];let l=o.key||i?.resultKey,u,d=o.hdrs?{headers:bht(n.headers)}:null;return"err"in o?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),Hf(s)?s:null):l?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),{[l]:s}):o.hdrs?u=Object.assign(Object.assign(Object.assign({},i?.extraFields),d),Hf(s)?s:null):u=s,"err"in o?[{ok:!1,error:o.errorClass?new o.errorClass(u,{request:r,response:n,body:c}):u},s]:[{ok:!0,value:u},s]}}function bht(t){let e={};for(let[n,r]of t.entries())e[n]=r.split(xht);return e}function Tht(...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":Aht(e,r);break;case"http:custom":break;case"http:bearer":_O(e,r);break;case"oauth2":_O(e,r);break;case"oauth2:password":_O(e,r);break;case"oauth2:client_credentials":break;case"openIdConnect":_O(e,r);break;default:throw $V.unrecognizedType(i)}}),e)}function Aht(t,e){e.value!=null&&(t.basic=e.value)}function _O(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 Ht(t,e){var n,r;let i=[[{fieldName:"accessToken",type:"http:custom",value:(n=t?.access_token)!==null&&n!==void 0?n:ax().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(r=t?.api_key)!==null&&r!==void 0?r:ax().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return Tht(...i)}async function jt(t){if(t!=null)return typeof t=="function"?t():t}function qt(t){let e=t.$inspect(),n=e.then(([i,s])=>{if(!i.ok)throw i.error;return[i.value,s]}),r=e.then(([i,s])=>{var o;if(!i.ok&&!(!((o=s.response)===null||o===void 0)&&o.ok))throw i.error;return s});return n.catch(()=>{}),r.catch(()=>{}),new At(n,r)}function HTe(t,e,n,r){return new At(Cht(t,e,n,r))}async function Cht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function jTe(t,e,n,r){return new At(Rht(t,e,n,r))}async function Rht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function WTe(t,e,n,r){return new At(Iht(t,e,n,r))}async function Iht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/agents/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function VTe(t,e,n,r,i,s){return new At(kht(t,e,n,r,i,s))}async function kht(t,e,n,r,i,s){var o,a,c;let u={api_version:e,page_size:n,page_token:r,parent:i},d=null,f={api_version:De("api_version",(o=u?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/agents")(f),g=cc({page_size:u?.page_size,page_token:u?.page_token,parent:u?.parent}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(Be("4XX"),Be("5XX"),tn("default"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function zTe(t,e,n,r){return new At(Pht(t,e,n,r))}async function Pht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function KTe(t,e,n,r){return new At(Oht(t,e,n,r))}async function Oht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function YTe(t,e,n,r){return new At(Mht(t,e,n,r))}async function Mht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/credentials/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function XTe(t,e,n,r,i){return new At(Nht(t,e,n,r,i))}async function Nht(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/credentials")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(tn(200),Be("4XX"),Be("5XX"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function JTe(t,e,n,r,i,s){return new At(Dht(t,e,n,r,i,s))}async function Dht(t,e,n,r,i,s){var o,a,c;let u={id:e,body:n,api_version:r,update_mask:i},d=ac("body",u.body,{explode:!0}),f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",u.id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/credentials/{id}")(f),g=cc({update_mask:u.update_mask}),y=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"PATCH",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function QTe(t,e,n,r){return new At(Lht(t,e,n,r))}async function Lht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function ZTe(t,e,n,r){return new At(Uht(t,e,n,r))}async function Uht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function eAe(t,e,n,r){return new At(Fht(t,e,n,r))}async function Fht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/environments/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function tAe(t,e,n,r,i){return new At(Bht(t,e,n,r,i))}async function Bht(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/environments")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function nAe(t,e,n,r,i,s,o,a){return new At(qht(t,e,n,r,i,s,o,a))}async function qht(t,e,n,r,i,s,o,a){var c,l,u;let f={environment:e,path:n,api_version:r,page_size:i,page_token:s,recursive:o},m=null,g={api_version:De("api_version",(c=f.api_version)!==null&&c!==void 0?c:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:De("environment",f.environment,{explode:!1,charEncoding:"percent"}),path:De("path",f.path,{explode:!1,charEncoding:"percentExceptReserved"})},y=Mt("/{api_version}/environments/{environment}/files/{path}")(g),w=cc({page_size:f.page_size,page_token:f.page_token,recursive:f.recursive}),S=new Headers($t({Accept:"application/json"})),T=await jt(t._options.security),R=Ht(T),C={options:t._options,base_url:(u=(l=a?.server_url)!==null&&l!==void 0?l:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:R,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"]},D=t._createRequest(C,{security:R,method:"GET",baseURL:a?.server_url,path:y,headers:S,query:w,body:m,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!D.ok)return[D,{status:"invalid"}];let $=D.value,G=await t._do($,{context:C,isErrorStatusCode:k=>kt({status:k},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!G.ok)return[G,{status:"request-error",request:$}];let V=G.value,[L]=await Gt(tn(200),Be("4XX"),Be("5XX"))(V,$);return L.ok?[L,{status:"complete",request:$,response:V}]:[L,{status:"complete",request:$,response:V}]}function rAe(t,e,n,r,i,s,o,a,c,l,u){return new At($ht(t,e,n,r,i,s,o,a,c,l,u))}async function $ht(t,e,n,r,i,s,o,a,c,l,u){var d,f,m;let y={environment:e,path:n,"X-Goog-Upload-Command":r,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":s,"X-Goog-Upload-Protocol":o,api_version:a,extract:c,overwrite:l},w=null,S={api_version:De("api_version",(d=y.api_version)!==null&&d!==void 0?d:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:De("environment",y.environment,{explode:!1,charEncoding:"percent"}),path:De("path",y.path,{explode:!1,charEncoding:"percentExceptReserved"})},T=Mt("/upload/{api_version}/environments/{environment}/files/{path}")(S),R=cc({extract:y.extract,overwrite:y.overwrite}),C=new Headers($t({Accept:"*/*","X-Goog-Upload-Command":De("X-Goog-Upload-Command",y["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":De("X-Goog-Upload-Header-Content-Length",y["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":De("X-Goog-Upload-Header-Content-Type",y["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":De("X-Goog-Upload-Protocol",y["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),D=await jt(t._options.security),$=Ht(D),G={options:t._options,base_url:(m=(f=u?.server_url)!==null&&f!==void 0?f:t._baseURL)!==null&&m!==void 0?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:$,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"]},V=t._createRequest(G,{security:$,method:"PUT",baseURL:u?.server_url,path:T,headers:C,query:R,body:w,userAgent:t._options.user_agent,timeout_ms:u?.timeout_ms||t._options.timeout_ms||-1},u);if(!V.ok)return[V,{status:"invalid"}];let L=V.value,k=await t._do(L,{context:G,isErrorStatusCode:I=>kt({status:I},["4XX","5XX"]),retryConfig:G.retry_config,retryCodes:G.retry_codes});if(!k.ok)return[k,{status:"request-error",request:L}];let E=k.value,A={httpMeta:{response:E,request:L}},[M]=await Gt($Te(200,{hdrs:!0}),Be("4XX"),Be("5XX"))(E,L,{extraFields:A});return M.ok?[M,{status:"complete",request:L,response:E}]:[M,{status:"complete",request:L,response:E}]}function iAe(t,e,n,r){return new At(Ght(t,e,n,r))}async function Ght(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/interactions/{id}/cancel")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,C={httpMeta:{response:R,request:S}},[D]=await Gt(tn(200),Wf("4XX",KV),Wf("5XX",zV))(R,S,{extraFields:C});return D.ok?[D,{status:"complete",request:S,response:R}]:[D,{status:"complete",request:S,response:R}]}function sAe(t,e,n,r){return new At(Hht(t,e,n,r))}async function Hht(t,e,n,r){var i,s,o,a;let c={body:e,api_version:n},l=c,u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(i=l.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/interactions")(d),m=new Headers($t({"Content-Type":"application/json",Accept:!((s=c?.body)===null||s===void 0)&&s.stream?"text/event-stream":"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:r?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,D={httpMeta:{response:C,request:T}},[$]=await Gt(tn(200),qTe(200,{sentinel:"[DONE]",flattened:!0}),Wf("4XX",XV),Wf("5XX",YV))(C,T,{extraFields:D});return $.ok?[$,{status:"complete",request:T,response:C}]:[$,{status:"complete",request:T,response:C}]}function jht(t,e,n,r){return new At(Wht(t,e,n,r))}async function Wht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/interactions/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,C={httpMeta:{response:R,request:S}},[D]=await Gt($Te(200),Wf("4XX",QV),Wf("5XX",JV))(R,S,{extraFields:C});return D.ok?[D,{status:"complete",request:S,response:R}]:[D,{status:"complete",request:S,response:R}]}function oAe(t,e,n,r,i,s,o){return new At(Vht(t,e,n,r,i,s,o))}async function Vht(t,e,n,r,i,s,o){var a,c,l;let u={id:e,api_version:n,include_input:r,last_event_id:i,stream:s},d=u,f=null,m={api_version:De("api_version",(a=d.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",d.id,{explode:!1,charEncoding:"percent"})},g=Mt("/{api_version}/interactions/{id}")(m),y=cc({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),w=new Headers($t({Accept:u?.stream?"text/event-stream":"application/json"})),S=await jt(t._options.security),T=Ht(S),R={options:t._options,base_url:(l=(c=o?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&l!==void 0?l:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:T,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(R,{security:T,method:"GET",baseURL:o?.server_url,path:g,headers:w,query:y,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!C.ok)return[C,{status:"invalid"}];let D=C.value,$=await t._do(D,{context:R,isErrorStatusCode:k=>kt({status:k},["4XX","5XX"]),retryConfig:R.retry_config,retryCodes:R.retry_codes});if(!$.ok)return[$,{status:"request-error",request:D}];let G=$.value,V={httpMeta:{response:G,request:D}},[L]=await Gt(tn(200),qTe(200,{sentinel:"[DONE]",flattened:!0}),Wf("4XX",ez),Wf("5XX",ZV))(G,D,{extraFields:V});return L.ok?[L,{status:"complete",request:D,response:G}]:[L,{status:"complete",request:D,response:G}]}function aAe(t,e,n,r){return new At(zht(t,e,n,r))}async function zht(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function cAe(t,e,n,r){return new At(Kht(t,e,n,r))}async function Kht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function lAe(t,e,n,r){return new At(Yht(t,e,n,r))}async function Yht(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function uAe(t,e,n,r,i,s){return new At(Xht(t,e,n,r,i,s))}async function Xht(t,e,n,r,i,s){var o,a,c;let u={trigger_id:e,api_version:n,page_size:r,page_token:i},d=null,f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:De("trigger_id",u.trigger_id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/triggers/{trigger_id}/executions")(f),g=cc({page_size:u.page_size,page_token:u.page_token}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function dAe(t,e,n,r,i,s){return new At(Jht(t,e,n,r,i,s))}async function Jht(t,e,n,r,i,s){var o,a,c;let u={api_version:e,filter:n,page_size:r,page_token:i},d=null,f={api_version:De("api_version",(o=u?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/triggers")(f),g=cc({filter:u?.filter,page_size:u?.page_size,page_token:u?.page_token}),y=new Headers($t({Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"GET",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(tn(200),Be("4XX"),Be("5XX"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function fAe(t,e,n,r){return new At(Qht(t,e,n,r))}async function Qht(t,e,n,r){var i,s,o;let c={trigger_id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:De("trigger_id",c.trigger_id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/triggers/{trigger_id}/executions")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(tn(200),Be("4XX"),Be("5XX"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function pAe(t,e,n,r,i){return new At(Zht(t,e,n,r,i))}async function Zht(t,e,n,r,i){var s,o,a;let l={id:e,body:n,api_version:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/triggers/{id}")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"PATCH",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(tn(200),Be("4XX"),Be("5XX"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function hAe(t,e,n,r){return new At(emt(t,e,n,r))}async function emt(t,e,n,r){var i,s,o;let c={body:e,api_version:n},l=ac("body",c.body,{explode:!0}),u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks")(u),f=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"POST",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function mAe(t,e,n,r){return new At(tmt(t,e,n,r))}async function tmt(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"DELETE",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function gAe(t,e,n,r){return new At(nmt(t,e,n,r))}async function nmt(t,e,n,r){var i,s,o;let c={id:e,api_version:n},l=null,u={api_version:De("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",c.id,{explode:!1,charEncoding:"percent"})},d=Mt("/{api_version}/webhooks/{id}")(u),f=new Headers($t({Accept:"application/json"})),m=await jt(t._options.security),g=Ht(m),y={options:t._options,base_url:(o=(s=r?.server_url)!==null&&s!==void 0?s:t._baseURL)!==null&&o!==void 0?o:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:g,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"]},w=t._createRequest(y,{security:g,method:"GET",baseURL:r?.server_url,path:d,headers:f,body:l,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!w.ok)return[w,{status:"invalid"}];let S=w.value,T=await t._do(S,{context:y,isErrorStatusCode:D=>kt({status:D},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:S}];let R=T.value,[C]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(R,S);return C.ok?[C,{status:"complete",request:S,response:R}]:[C,{status:"complete",request:S,response:R}]}function yAe(t,e,n,r,i){return new At(rmt(t,e,n,r,i))}async function rmt(t,e,n,r,i){var s,o,a;let l={api_version:e,page_size:n,page_token:r},u=null,d={api_version:De("api_version",(s=l?.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks")(d),m=cc({page_size:l?.page_size,page_token:l?.page_token}),g=new Headers($t({Accept:"application/json"})),y=await jt(t._options.security),w=Ht(y),S={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:w,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"]},T=t._createRequest(S,{security:w,method:"GET",baseURL:i?.server_url,path:f,headers:g,query:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];let R=T.value,C=await t._do(R,{context:S,isErrorStatusCode:G=>kt({status:G},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!C.ok)return[C,{status:"request-error",request:R}];let D=C.value,[$]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(D,R);return $.ok?[$,{status:"complete",request:R,response:D}]:[$,{status:"complete",request:R,response:D}]}function _Ae(t,e,n,r,i){return new At(imt(t,e,n,r,i))}async function imt(t,e,n,r,i){var s,o,a;let l={id:e,api_version:n,body:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks/{id}:ping")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function vAe(t,e,n,r,i){return new At(smt(t,e,n,r,i))}async function smt(t,e,n,r,i){var s,o,a;let l={id:e,api_version:n,body:r},u=ac("body",l.body,{explode:!0}),d={api_version:De("api_version",(s=l.api_version)!==null&&s!==void 0?s:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",l.id,{explode:!1,charEncoding:"percent"})},f=Mt("/{api_version}/webhooks/{id}:rotateSigningSecret")(d),m=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),g=await jt(t._options.security),y=Ht(g),w={options:t._options,base_url:(a=(o=i?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:y,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"]},S=t._createRequest(w,{security:y,method:"POST",baseURL:i?.server_url,path:f,headers:m,body:u,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!S.ok)return[S,{status:"invalid"}];let T=S.value,R=await t._do(T,{context:w,isErrorStatusCode:$=>kt({status:$},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!R.ok)return[R,{status:"request-error",request:T}];let C=R.value,[D]=await Gt(Be("4XX"),Be("5XX"),tn("default"))(C,T);return D.ok?[D,{status:"complete",request:T,response:C}]:[D,{status:"complete",request:T,response:C}]}function EAe(t,e,n,r,i,s){return new At(omt(t,e,n,r,i,s))}async function omt(t,e,n,r,i,s){var o,a,c;let u={id:e,api_version:n,update_mask:r,body:i},d=ac("body",u.body,{explode:!0}),f={api_version:De("api_version",(o=u.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:De("id",u.id,{explode:!1,charEncoding:"percent"})},m=Mt("/{api_version}/webhooks/{id}")(f),g=cc({update_mask:u.update_mask}),y=new Headers($t({"Content-Type":"application/json",Accept:"application/json"})),w=await jt(t._options.security),S=Ht(w),T={options:t._options,base_url:(c=(a=s?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:S,security_source:t._options.security,retry_config:s?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(T,{security:S,method:"PATCH",baseURL:s?.server_url,path:m,headers:y,query:g,body:d,userAgent:t._options.user_agent,timeout_ms:s?.timeout_ms||t._options.timeout_ms||-1},s);if(!R.ok)return[R,{status:"invalid"}];let C=R.value,D=await t._do(C,{context:T,isErrorStatusCode:V=>kt({status:V},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!D.ok)return[D,{status:"request-error",request:C}];let $=D.value,[G]=await Gt(Be("4XX"),Be("5XX"),tn("default"))($,C);return G.ok?[G,{status:"complete",request:C,response:$}]:[G,{status:"complete",request:C,response:$}]}function lmt(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function umt(t){let e=dmt(t.getApiVersion()),n=t.getProject(),r=t.getLocation();return t.isVertexAI()&&e&&n&&r?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(r)}`:e}function ra(t,e={}){var n,r,i,s,o,a,c;let l=e.http_client||(n=t.getFetch)===null||n===void 0?void 0:n.call(t),u=(r=e.http_client)!==null&&r!==void 0?r:l?new t1({fetcher:l}):void 0;return new amt(Object.assign(Object.assign({},e),{http_client:u,api_version:(i=e.api_version)!==null&&i!==void 0?i:umt(t),security:(s=e.security)!==null&&s!==void 0?s:new CV({defaultHeaders:Object.assign(Object.assign({},(o=t.getDefaultHeaders)===null||o===void 0?void 0:o.call(t)),(a=t.getHeaders)===null||a===void 0?void 0:a.call(t)),getAuthHeaders:f=>t.getAuthHeaders(f)}),server_url:(c=e.server_url)!==null&&c!==void 0?c:lmt(t)}))}function dmt(t){return t.replace(/^\/+|\/+$/g,"")}function It(t,e=!1){var n,r,i,s;if(!t&&!e)return;let o=t??{},{timeout:a,maxRetries:c,defaultBaseURL:l,query:u,body:d,fetchOptions:f}=o,m=Cr(o,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),g=Object.assign({},m);i1(u)?g.extra_query=u:Nbe("query",u),i1(d)?g.extra_body=d:Nbe("body",d);let y=(n=m.fetch_options)!==null&&n!==void 0?n:f;y&&(g.fetch_options=y);let w=(r=m.server_url)!==null&&r!==void 0?r:l;w&&(g.server_url=w);let S=(i=m.timeout_ms)!==null&&i!==void 0?i:a;if(S!==void 0&&(g.timeout_ms=S),c!==void 0&&(g.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let T=new Headers((s=g.headers)!==null&&s!==void 0?s:y?.headers);T.set("Accept","text/event-stream"),g.headers=T}return g}function Nbe(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 en(t){let[e,n]=await t.$inspect();if(!e.ok)throw ym(e.error);return fmt(e.value,n)}async function vW(t){try{return await t()}catch(e){throw ym(e)}}function Dbe(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 s=e[Symbol.asyncIterator]();return{async next(...o){try{return await s.next(...o)}catch(a){throw ym(a)}},async return(o){if(!s.return)return{done:!0,value:o};try{return await s.return(o)}catch(a){throw ym(a)}},async throw(o){if(!s.throw)throw ym(o);try{return await s.throw(o)}catch(a){throw ym(a)}},[Symbol.asyncIterator](){return this}}}}})}function fmt(t,e){return!i1(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:pmt(e.response,t)})}function pmt(t,e){let n={};for(let[r,i]of t.headers.entries())n[r]=i;return{headers:n,responseInternal:t,json:async()=>e}}function EW(t){let e=hmt(t);return e?gmt(e):t}function hmt(t){if(i1(t)){if(Array.isArray(t.steps))return t;if(mmt(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,r=Cr(t,["outputs"]);return Object.assign(Object.assign({},r),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function mmt(t){let e=t.model;return typeof e=="string"&&cmt.has(e)}function i1(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gmt(t){var e,n;let r=ymt(t),i=(e=r.steps)!==null&&e!==void 0?e:[],s=[],o=!1;e:for(let d=i.length-1;d>=0;d--){let f=i[d];if(f.type==="user_input")break;if(f.type!=="model_output"||!f.content){if(o)break;continue}let m=f.content;for(let g=m.length-1;g>=0;g--){let y=m[g];if(y.type==="text")o=!0,s.push((n=y.text)!==null&&n!==void 0?n:"");else if(o)break e}}let a,c,l;for(let d=i.length-1;d>=0;d--){let f=i[d];if(f.type==="user_input")break;if(f.type==="model_output"&&f.content)for(let m=f.content.length-1;m>=0;m--){let g=f.content[m];g.type==="image"&&!a&&(a=g),g.type==="audio"&&!c&&(c=g),g.type==="video"&&!l&&(l=g)}}let u=s.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},r),u&&{output_text:u}),a?{output_image:a}:{}),c?{output_audio:c}:{}),l?{output_video:l}:{})}function ymt(t){return Object.assign(Object.assign({},t),{created:Lbe(t.created),updated:Lbe(t.updated)})}function Lbe(t){return t instanceof Date?t.toISOString():t}function _mt(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]}function vmt(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==WS||Array.isArray(e.scopes)&&e.scopes.indexOf(WS)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${WS}`)}else return e.scopes=[WS],e;return e}else return e={scopes:[WS]},e}async function Emt(t,e){var n,r,i;let s=Cz(t.file);if(s!==void 0)return await e.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal});if(tTe(t.file)){let o=(i=t.file.video)===null||i===void 0?void 0:i.videoBytes;if(typeof o=="string")return o;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(nTe(t.file)){let o=t.file.videoBytes;if(typeof o=="string")return o;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}function wmt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Smt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function xmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function bmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function mz(t,e){let n={},r=p(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Umt(o))),h(n,["parts"],s)}let i=p(t,["role"]);return i!=null&&h(n,["role"],i),n}function Tmt(t,e,n){let r={};if(p(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=p(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&h(e,["displayName"],i),p(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let s=p(t,["epochCount"]);e!==void 0&&s!=null&&h(e,["tuningTask","hyperparameters","epochCount"],s);let o=p(t,["learningRateMultiplier"]);if(o!=null&&h(r,["tuningTask","hyperparameters","learningRateMultiplier"],o),p(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(p(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(p(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(p(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(p(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 a=p(t,["batchSize"]);e!==void 0&&a!=null&&h(e,["tuningTask","hyperparameters","batchSize"],a);let c=p(t,["learningRate"]);if(e!==void 0&&c!=null&&h(e,["tuningTask","hyperparameters","learningRate"],c),p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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(p(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 Amt(t,e,n){let r={},i=p(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec"],vO(I))}else if(i==="PREFERENCE_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec"],vO(I))}else if(i==="DISTILLATION"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["distillationSpec"],vO(I))}else if(i==="REINFORCEMENT_TUNING"){let I=p(t,["validationDataset"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec"],vO(I))}let s=p(t,["tunedModelDisplayName"]);e!==void 0&&s!=null&&h(e,["tunedModelDisplayName"],s);let o=p(t,["description"]);e!==void 0&&o!=null&&h(e,["description"],o);let a=p(n,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","epochCount"],I)}else if(a==="PREFERENCE_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],I)}else if(a==="DISTILLATION"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","epochCount"],I)}else if(a==="REINFORCEMENT_TUNING"){let I=p(t,["epochCount"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","epochCount"],I)}let c=p(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="PREFERENCE_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="DISTILLATION"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","learningRateMultiplier"],I)}else if(c==="REINFORCEMENT_TUNING"){let I=p(t,["learningRateMultiplier"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],I)}let l=p(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","exportLastCheckpointOnly"],I)}else if(l==="PREFERENCE_TUNING"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],I)}else if(l==="DISTILLATION"){let I=p(t,["exportLastCheckpointOnly"]);e!==void 0&&I!=null&&h(e,["distillationSpec","exportLastCheckpointOnly"],I)}let u=p(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","adapterSize"],I)}else if(u==="PREFERENCE_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],I)}else if(u==="DISTILLATION"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","adapterSize"],I)}else if(u==="REINFORCEMENT_TUNING"){let I=p(t,["adapterSize"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],I)}let d=p(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let I=p(t,["tuningMode"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","tuningMode"],I)}else if(d==="DISTILLATION"){let I=p(t,["tuningMode"]);e!==void 0&&I!=null&&h(e,["distillationSpec","tuningMode"],I)}let f=p(t,["customBaseModel"]);e!==void 0&&f!=null&&h(e,["customBaseModel"],f);let m=p(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","batchSize"],I)}else if(m==="DISTILLATION"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","batchSize"],I)}else if(m==="REINFORCEMENT_TUNING"){let I=p(t,["batchSize"]);e!==void 0&&I!=null&&h(e,["reinforcementTuningSpec","hyperParameters","batchSize"],I)}let g=p(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){let I=p(t,["learningRate"]);e!==void 0&&I!=null&&h(e,["supervisedTuningSpec","hyperParameters","learningRate"],I)}else if(g==="DISTILLATION"){let I=p(t,["learningRate"]);e!==void 0&&I!=null&&h(e,["distillationSpec","hyperParameters","learningRate"],I)}let y=p(t,["labels"]);e!==void 0&&y!=null&&h(e,["labels"],y);let w=p(t,["beta"]);e!==void 0&&w!=null&&h(e,["preferenceOptimizationSpec","hyperParameters","beta"],w);let S=p(t,["baseTeacherModel"]);e!==void 0&&S!=null&&h(e,["distillationSpec","baseTeacherModel"],S);let T=p(t,["tunedTeacherModelSource"]);e!==void 0&&T!=null&&h(e,["distillationSpec","tunedTeacherModelSource"],T);let R=p(t,["sftLossWeightMultiplier"]);e!==void 0&&R!=null&&h(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],R);let C=p(t,["outputUri"]);e!==void 0&&C!=null&&h(e,["outputUri"],C);let D=p(t,["rewardConfig"]);e!==void 0&&D!=null&&h(e,["reinforcementTuningSpec","singleRewardConfig"],D);let $=p(t,["compositeRewardConfig"]);e!==void 0&&$!=null&&h(e,["reinforcementTuningSpec","compositeRewardConfig"],$);let G=p(t,["samplesPerPrompt"]);e!==void 0&&G!=null&&h(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],G);let V=p(t,["evaluateInterval"]);e!==void 0&&V!=null&&h(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],V);let L=p(t,["checkpointInterval"]);e!==void 0&&L!=null&&h(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],L);let k=p(t,["maxOutputTokens"]);e!==void 0&&k!=null&&h(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],k);let E=p(t,["thinkingLevel"]);e!==void 0&&E!=null&&h(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],E);let A=p(t,["validationDatasetUri"]);e!==void 0&&A!=null&&h(e,["reinforcementTuningSpec","validationDatasetUri"],A);let M=p(t,["encryptionSpec"]);return e!==void 0&&M!=null&&h(e,["encryptionSpec"],M),r}function Cmt(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["preTunedModel"]);i!=null&&h(n,["preTunedModel"],i);let s=p(t,["trainingDataset"]);s!=null&&qmt(s);let o=p(t,["config"]);return o!=null&&Tmt(o,n),n}function Rmt(t,e){let n={},r=p(t,["baseModel"]);r!=null&&h(n,["baseModel"],r);let i=p(t,["preTunedModel"]);i!=null&&h(n,["preTunedModel"],i);let s=p(t,["trainingDataset"]);s!=null&&$mt(s,n,e);let o=p(t,["config"]);return o!=null&&Amt(o,n,e),n}function wAe(t,e){let n={},r=p(t,["epochCount"]);r!=null&&h(n,["epochCount"],r);let i=p(t,["learningRateMultiplier"]);i!=null&&h(n,["learningRateMultiplier"],i);let s=p(t,["adapterSize"]);s!=null&&h(n,["adapterSize"],s);let o=p(t,["batchSize"]);o!=null&&h(n,["batchSize"],o);let a=p(t,["learningRate"]);a!=null&&h(n,["learningRate"],a);let c=p(t,["generationConfig"]);return c!=null&&h(n,["generationConfig"],Pmt(c)),n}function Imt(t,e){let n={},r=p(t,["promptDatasetUri"]);r!=null&&h(n,["promptDatasetUri"],r);let i=p(t,["validationDatasetUri"]);i!=null&&h(n,["validationDatasetUri"],i);let s=p(t,["baseTeacherModel"]);s!=null&&h(n,["baseTeacherModel"],s);let o=p(t,["tunedTeacherModelSource"]);o!=null&&h(n,["tunedTeacherModelSource"],o);let a=p(t,["hyperparameters"]);return a!=null&&h(n,["hyperparameters"],wAe(a)),n}function kmt(t,e){let n={},r=p(t,["baseTeacherModel"]);r!=null&&h(n,["baseTeacherModel"],r);let i=p(t,["hyperParameters"]);i!=null&&h(n,["hyperParameters"],wAe(i));let s=p(t,["pipelineRootDirectory"]);s!=null&&h(n,["pipelineRootDirectory"],s);let o=p(t,["promptDatasetUri"]);o!=null&&h(n,["promptDatasetUri"],o);let a=p(t,["studentModel"]);a!=null&&h(n,["studentModel"],a);let c=p(t,["trainingDatasetUri"]);c!=null&&h(n,["trainingDatasetUri"],c);let l=p(t,["tunedTeacherModelSource"]);l!=null&&h(n,["tunedTeacherModelSource"],l);let u=p(t,["tuningMode"]);u!=null&&h(n,["tuningMode"],u);let d=p(t,["validationDatasetUri"]);return d!=null&&h(n,["validationDatasetUri"],d),n}function Pmt(t,e){let n={},r=p(t,["modelConfig"]);r!=null&&h(n,["modelSelectionConfig"],r);let i=p(t,["responseJsonSchema"]);i!=null&&h(n,["responseJsonSchema"],i);let s=p(t,["audioTranscriptionConfig"]);s!=null&&h(n,["audioTranscriptionConfig"],s);let o=p(t,["audioTimestamp"]);o!=null&&h(n,["audioTimestamp"],o);let a=p(t,["candidateCount"]);a!=null&&h(n,["candidateCount"],a);let c=p(t,["enableAffectiveDialog"]);c!=null&&h(n,["enableAffectiveDialog"],c);let l=p(t,["frequencyPenalty"]);l!=null&&h(n,["frequencyPenalty"],l);let u=p(t,["logprobs"]);u!=null&&h(n,["logprobs"],u);let d=p(t,["maxOutputTokens"]);d!=null&&h(n,["maxOutputTokens"],d);let f=p(t,["mediaResolution"]);f!=null&&h(n,["mediaResolution"],f);let m=p(t,["presencePenalty"]);m!=null&&h(n,["presencePenalty"],m);let g=p(t,["responseFormat"]);if(g!=null){let E=g;Array.isArray(E)&&(E=E.map(A=>A)),h(n,["responseFormat"],E)}let y=p(t,["responseLogprobs"]);y!=null&&h(n,["responseLogprobs"],y);let w=p(t,["responseMimeType"]);w!=null&&h(n,["responseMimeType"],w);let S=p(t,["responseModalities"]);S!=null&&h(n,["responseModalities"],S);let T=p(t,["responseSchema"]);T!=null&&h(n,["responseSchema"],T);let R=p(t,["routingConfig"]);R!=null&&h(n,["routingConfig"],R);let C=p(t,["seed"]);C!=null&&h(n,["seed"],C);let D=p(t,["speechConfig"]);D!=null&&h(n,["speechConfig"],D);let $=p(t,["stopSequences"]);$!=null&&h(n,["stopSequences"],$);let G=p(t,["temperature"]);G!=null&&h(n,["temperature"],G);let V=p(t,["thinkingConfig"]);V!=null&&h(n,["thinkingConfig"],V);let L=p(t,["topK"]);L!=null&&h(n,["topK"],L);let k=p(t,["topP"]);return k!=null&&h(n,["topP"],k),n}function Omt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Mmt(t,e){let n={},r=p(t,["name"]);return r!=null&&h(n,["_url","name"],r),n}function Nmt(t,e,n){let r={},i=p(t,["pageSize"]);e!==void 0&&i!=null&&h(e,["_query","pageSize"],i);let s=p(t,["pageToken"]);e!==void 0&&s!=null&&h(e,["_query","pageToken"],s);let o=p(t,["filter"]);return e!==void 0&&o!=null&&h(e,["_query","filter"],o),r}function Dmt(t,e){let n={},r=p(t,["config"]);return r!=null&&Nmt(r,n),n}function Lmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["nextPageToken"]);i!=null&&h(n,["nextPageToken"],i);let s=p(t,["tuningJobs"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(a=>gz(a))),h(n,["tuningJobs"],o)}return n}function Umt(t,e){let n={},r=p(t,["mediaResolution"]);if(r!=null&&h(n,["mediaResolution"],r),p(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(p(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=p(t,["audioTranscription"]);i!=null&&h(n,["audioTranscription"],i);let s=p(t,["codeExecutionResult"]);s!=null&&h(n,["codeExecutionResult"],s);let o=p(t,["executableCode"]);o!=null&&h(n,["executableCode"],o);let a=p(t,["fileData"]);a!=null&&h(n,["fileData"],a);let c=p(t,["functionCall"]);c!=null&&h(n,["functionCall"],c);let l=p(t,["functionResponse"]);l!=null&&h(n,["functionResponse"],l);let u=p(t,["inlineData"]);u!=null&&h(n,["inlineData"],u);let d=p(t,["text"]);d!=null&&h(n,["text"],d);let f=p(t,["thought"]);f!=null&&h(n,["thought"],f);let m=p(t,["thoughtSignature"]);m!=null&&h(n,["thoughtSignature"],m);let g=p(t,["videoMetadata"]);if(g!=null&&h(n,["videoMetadata"],g),p(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 y=p(t,["mediaProcessing"]);return y!=null&&h(n,["mediaProcessing"],y),n}function Fmt(t,e){let n={},r=p(t,["references"]);r!=null&&h(n,["references"],r);let i=p(t,["contents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>mz(a))),h(n,["contents"],o)}let s=p(t,["systemInstruction"]);return s!=null&&h(n,["systemInstruction"],mz(s)),n}function Bmt(t,e){let n={},r=p(t,["name"]);r!=null&&h(n,["model"],r);let i=p(t,["name"]);return i!=null&&h(n,["endpoint"],i),n}function qmt(t,e){let n={};if(p(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(p(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=p(t,["examples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),h(n,["examples","examples"],i)}return n}function $mt(t,e,n){let r={},i=p(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(i==="PREFERENCE_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(i==="DISTILLATION"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["distillationSpec","promptDatasetUri"],o)}else if(i==="REINFORCEMENT_TUNING"){let o=p(t,["gcsUri"]);e!==void 0&&o!=null&&h(e,["reinforcementTuningSpec","trainingDatasetUri"],o)}let s=p(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(s==="PREFERENCE_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(s==="DISTILLATION"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["distillationSpec","promptDatasetUri"],o)}else if(s==="REINFORCEMENT_TUNING"){let o=p(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&h(e,["reinforcementTuningSpec","trainingDatasetUri"],o)}if(p(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 Gmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["state"]);s!=null&&h(n,["state"],eTe(s));let o=p(t,["createTime"]);o!=null&&h(n,["createTime"],o);let a=p(t,["tuningTask","startTime"]);a!=null&&h(n,["startTime"],a);let c=p(t,["tuningTask","completeTime"]);c!=null&&h(n,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(n,["updateTime"],l);let u=p(t,["description"]);u!=null&&h(n,["description"],u);let d=p(t,["baseModel"]);d!=null&&h(n,["baseModel"],d);let f=p(t,["_self"]);return f!=null&&h(n,["tunedModel"],Bmt(f)),n}function gz(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["state"]);s!=null&&h(n,["state"],eTe(s));let o=p(t,["createTime"]);o!=null&&h(n,["createTime"],o);let a=p(t,["startTime"]);a!=null&&h(n,["startTime"],a);let c=p(t,["endTime"]);c!=null&&h(n,["endTime"],c);let l=p(t,["updateTime"]);l!=null&&h(n,["updateTime"],l);let u=p(t,["error"]);u!=null&&h(n,["error"],u);let d=p(t,["description"]);d!=null&&h(n,["description"],d);let f=p(t,["baseModel"]);f!=null&&h(n,["baseModel"],f);let m=p(t,["tunedModel"]);m!=null&&h(n,["tunedModel"],m);let g=p(t,["preTunedModel"]);g!=null&&h(n,["preTunedModel"],g);let y=p(t,["supervisedTuningSpec"]);y!=null&&h(n,["supervisedTuningSpec"],y);let w=p(t,["preferenceOptimizationSpec"]);w!=null&&h(n,["preferenceOptimizationSpec"],w);let S=p(t,["distillationSamplingSpec"]);S!=null&&h(n,["distillationSamplingSpec"],Imt(S));let T=p(t,["distillationSpec"]);T!=null&&h(n,["distillationSpec"],kmt(T));let R=p(t,["reinforcementTuningSpec"]);R!=null&&h(n,["reinforcementTuningSpec"],R);let C=p(t,["tuningDataStats"]);C!=null&&h(n,["tuningDataStats"],C);let D=p(t,["encryptionSpec"]);D!=null&&h(n,["encryptionSpec"],D);let $=p(t,["partnerModelTuningSpec"]);$!=null&&h(n,["partnerModelTuningSpec"],$);let G=p(t,["customBaseModel"]);G!=null&&h(n,["customBaseModel"],G);let V=p(t,["evaluateDatasetRuns"]);if(V!=null){let q=V;Array.isArray(q)&&(q=q.map(pe=>pe)),h(n,["evaluateDatasetRuns"],q)}let L=p(t,["experiment"]);L!=null&&h(n,["experiment"],L);let k=p(t,["fullFineTuningSpec"]);k!=null&&h(n,["fullFineTuningSpec"],k);let E=p(t,["labels"]);E!=null&&h(n,["labels"],E);let A=p(t,["outputUri"]);A!=null&&h(n,["outputUri"],A);let M=p(t,["pipelineJob"]);M!=null&&h(n,["pipelineJob"],M);let I=p(t,["serviceAccount"]);I!=null&&h(n,["serviceAccount"],I);let P=p(t,["tunedModelDisplayName"]);P!=null&&h(n,["tunedModelDisplayName"],P);let F=p(t,["tuningJobMetadata"]);F!=null&&h(n,["tuningJobMetadata"],F);let X=p(t,["tuningJobState"]);X!=null&&h(n,["tuningJobState"],X);let N=p(t,["veoLoraTuningSpec"]);N!=null&&h(n,["veoLoraTuningSpec"],N);let b=p(t,["veoTuningSpec"]);return b!=null&&h(n,["veoTuningSpec"],b),n}function Hmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["name"]);i!=null&&h(n,["name"],i);let s=p(t,["metadata"]);s!=null&&h(n,["metadata"],s);let o=p(t,["done"]);o!=null&&h(n,["done"],o);let a=p(t,["error"]);return a!=null&&h(n,["error"],a),n}function vO(t,e){let n={},r=p(t,["gcsUri"]);r!=null&&h(n,["validationDatasetUri"],r);let i=p(t,["vertexDatasetResource"]);return i!=null&&h(n,["validationDatasetUri"],i),n}function jmt(t,e){let n={},r=p(t,["parent"]);r!=null&&h(n,["_url","parent"],r);let i=p(t,["sampleResponse"]);i!=null&&h(n,["sampleResponse"],mz(i));let s=p(t,["example"]);s!=null&&h(n,["example"],Fmt(s));let o=p(t,["singleRewardConfig"]);o!=null&&h(n,["singleRewardConfig"],o);let a=p(t,["compositeRewardConfig"]);return a!=null&&h(n,["compositeRewardConfig"],a),n}function Wmt(t,e){let n={},r=p(t,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);let i=p(t,["overallReward"]);i!=null&&h(n,["overallReward"],i);let s=p(t,["error"]);s!=null&&h(n,["error"],s);let o=p(t,["rewardInfoDetails"]);return o!=null&&h(n,["rewardInfoDetails"],o),n}async function Vmt(t,e,n,r){var i;let s=await AAe(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return o.file}async function zmt(t,e,n,r){var i;let s=await AAe(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Sz(o),c=new ix;return Object.assign(c,a),c}async function AAe(t,e,n,r){var i,s,o;let a=e,c=r?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(c){let m=new URL(c),g=new URL(e);g.protocol=m.protocol,g.host=m.host,g.port=m.port,a=g.toString()}let l=0,u=0,d=new Vu(new Response),f="upload";for(l=t.size;u<l;){let m=Math.min(SAe,l-u),g=t.slice(u,u+m);u+m>=l&&(f+=", finalize");let y=0,w=bAe;for(;y<xAe;){let S=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":f,"X-Goog-Upload-Offset":String(u)});if(d=await n.request({path:"",body:g,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:a,headers:S})}),!((s=d?.headers)===null||s===void 0)&&s[qf])break;y++,await CAe(w),w=w*TAe}if(u+=m,((o=d?.headers)===null||o===void 0?void 0:o[qf])!=="active")break;if(l<=u)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}async function Kmt(t){return{size:t.size,type:t.type}}function CAe(t){return new Promise(e=>setTimeout(e,t))}function Xmt(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=$f("GOOGLE_GENAI_USE_ENTERPRISE"),r=$f("GOOGLE_GENAI_USE_VERTEXAI"),i=Fbe(n),s=Fbe(r);return n!==void 0&&r!==void 0&&i!==s&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?i:r!==void 0?s:!1}function $f(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 Fbe(t){return t===void 0?!1:t.toLowerCase()==="true"}function Jmt(){let t=$f("GOOGLE_API_KEY"),e=$f("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}var Bbe,qbe,$be,s1,Gbe,Hbe,jbe,Wbe,Vbe,zbe,ic,SW,xW,bW,Wu,TW,AW,CW,RW,IW,kW,PW,OW,MW,NW,DW,LW,UW,FW,BW,qW,$W,GW,HW,jW,WW,VW,zW,KW,zS,YW,XW,JW,QW,ZW,e6,t6,n6,SO,r6,i6,s6,o6,a6,c6,l6,u6,d6,f6,p6,xO,h6,KS,m6,g6,y6,_6,v6,E6,w6,S6,x6,b6,T6,A6,C6,R6,I6,k6,P6,O6,M6,N6,D6,L6,U6,F6,B6,gm,q6,$6,G6,H6,j6,Vu,V6,z6,Bf,YS,bO,TO,AO,CO,RO,XS,JS,K6,Y6,X6,J6,Q6,QS,IO,Z6,ZS,eV,tV,nV,kO,ex,PO,tx,nx,OO,MO,NO,rV,DO,LO,UO,FO,BO,iV,sV,oV,rx,aV,cV,lV,uV,dV,fV,pV,qO,hV,mV,$O,gV,ix,pl,hl,HO,jO,WO,VO,sx,uTe,Oft,Mft,Nft,wV,Dft,Lft,Uft,Fft,Bft,Gft,Hft,jft,Wft,Vft,zft,SV,Yft,wTe,ox,xV,bV,rpt,zO,spt,KO,_be,_m,YO,XO,TV,AV,gO,CV,RV,Gf,JO,dv,QO,ZO,e1,na,IV,ys,kV,mv,PV,OV,MV,NV,DV,LV,UV,FV,BV,zpt,t1,Abe,Kpt,n1,eht,Rbe,nht,sht,kTe,De,cc,Ibe,cx,jf,uht,yO,hht,mht,sc,FTe,Pbe,r1,qV,ea,ta,BTe,vht,Sht,xht,Mbe,$V,GTe,At,GV,HV,jV,WV,VV,zV,KV,YV,XV,JV,QV,ZV,ez,tz,nz,rz,amt,cmt,iz,sz,oz,az,cz,lz,uz,Ube,WS,dz,fz,pz,hz,yz,SAe,xAe,bAe,TAe,qf,_z,vz,Ymt,Ez,IAe=ae(()=>{Bbe=ce(uEe(),1),qbe=ce(exe(),1),$be=require("fs"),s1=ce(require("fs/promises"),1),Gbe=require("fs/promises"),Hbe=require("node:stream"),jbe=require("node:stream/promises");ibe();Wbe=ce(require("path"),1);ic=class{};(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(SW||(SW={}));(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(xW||(xW={}));(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(bW||(bW={}));(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"})(Wu||(Wu={}));(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"})(TW||(TW={}));(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"})(AW||(AW={}));(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(CW||(CW={}));(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(RW||(RW={}));(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"})(IW||(IW={}));(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"})(kW||(kW={}));(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(PW||(PW={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(OW||(OW={}));(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(MW||(MW={}));(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(NW||(NW={}));(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(DW||(DW={}));(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"})(LW||(LW={}));(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(UW||(UW={}));(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"})(FW||(FW={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(BW||(BW={}));(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"})(qW||(qW={}));(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})($W||($W={}));(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"})(GW||(GW={}));(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"})(HW||(HW={}));(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"})(jW||(jW={}));(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(WW||(WW={}));(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(VW||(VW={}));(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"})(zW||(zW={}));(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"})(KW||(KW={}));(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(zS||(zS={}));(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(YW||(YW={}));(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"})(XW||(XW={}));(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"})(JW||(JW={}));(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"})(QW||(QW={}));(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"})(ZW||(ZW={}));(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(e6||(e6={}));(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})(t6||(t6={}));(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(n6||(n6={}));(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"})(SO||(SO={}));(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"})(r6||(r6={}));(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"})(i6||(i6={}));(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(s6||(s6={}));(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(o6||(o6={}));(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(a6||(a6={}));(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"})(c6||(c6={}));(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(l6||(l6={}));(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(u6||(u6={}));(function(t){t.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",t.STATIC="STATIC",t.AGENTIC="AGENTIC"})(d6||(d6={}));(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"})(f6||(f6={}));(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"})(p6||(p6={}));(function(t){t.COLLECTION="COLLECTION"})(xO||(xO={}));(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(h6||(h6={}));(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(KS||(KS={}));(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"})(m6||(m6={}));(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"})(g6||(g6={}));(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"})(y6||(y6={}));(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"})(_6||(_6={}));(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"})(v6||(v6={}));(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"})(E6||(E6={}));(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(w6||(w6={}));(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(S6||(S6={}));(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(x6||(x6={}));(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(b6||(b6={}));(function(t){t.CROP="CROP",t.PAD="PAD"})(T6||(T6={}));(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(A6||(A6={}));(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(C6||(C6={}));(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(R6||(R6={}));(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"})(I6||(I6={}));(function(t){t.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",t.IN_PROGRESS="IN_PROGRESS",t.REQUIRES_ACTION="REQUIRES_ACTION",t.IDLE="IDLE"})(k6||(k6={}));(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"})(P6||(P6={}));(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(O6||(O6={}));(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(M6||(M6={}));(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(N6||(N6={}));(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(D6||(D6={}));(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"})(L6||(L6={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.VERBATIM="VERBATIM",t.SMART="SMART"})(U6||(U6={}));(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"})(F6||(F6={}));(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(B6||(B6={}));(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(gm||(gm={}));q6=class{},$6=class{},G6=class{},H6=class{};j6=class{};Vu=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()}},V6=class{},z6=class{},Bf=class{get text(){var e,n,r,i,s,o,a,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 l="",u=!1,d=[];for(let f of(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)!==null&&c!==void 0?c:[]){for(let[m,g]of Object.entries(f))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(g!==null||g!==void 0)&&d.push(m);if(typeof f.text=="string"){if(typeof f.thought=="boolean"&&f.thought)continue;u=!0,l+=f.text}}return d.length>0&&console.warn(`there are non-text parts ${d} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,n,r,i,s,o,a,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 l="",u=[];for(let d of(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)!==null&&c!==void 0?c:[]){for(let[f,m]of Object.entries(d))f!=="inlineData"&&(m!==null||m!==void 0)&&u.push(f);d.inlineData&&typeof d.inlineData.data=="string"&&(l+=atob(d.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,n,r,i,s,o,a,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 l=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(u=>u.functionCall).map(u=>u.functionCall).filter(u=>u!==void 0);if(l?.length!==0)return l}get executableCode(){var e,n,r,i,s,o,a,c,l;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 u=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(d=>d.executableCode).map(d=>d.executableCode).filter(d=>d!==void 0);if(u?.length!==0)return(l=u?.[0])===null||l===void 0?void 0:l.code}get codeExecutionResult(){var e,n,r,i,s,o,a,c,l;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 u=(c=(a=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||a===void 0?void 0:a.parts)===null||c===void 0?void 0:c.filter(d=>d.codeExecutionResult).map(d=>d.codeExecutionResult).filter(d=>d!==void 0);if(u?.length!==0)return(l=u?.[0])===null||l===void 0?void 0:l.output}},YS=class{},bO=class{},TO=class{},AO=class{},CO=class{},RO=class{},XS=class{},JS=class{},K6=class{},Y6=class{},X6=class{},J6=class{},Q6=class{},QS=class{},IO=class{},Z6=class{},ZS=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,i,s=e;return n?i=Mat(s):i=Oat(s),Object.assign(r,i),r}},eV=class{},tV=class{},nV=class{},kO=class{},ex=class{},PO=class{},tx=class{},nx=class{},OO=class{},MO=class{},NO=class{},rV=class{},DO=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=qat(e);return Object.assign(r,s),r}},LO=class{},UO=class{},FO=class{},BO=class{},iV=class{},sV=class{},oV=class{},rx=class{},aV=class{},cV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},lV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},uV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},dV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},fV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},pV=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},qO=class{get text(){var e,n,r;let i="",s=!1,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[c,l]of Object.entries(a))c!=="text"&&c!=="thought"&&l!==null&&o.push(c);if(typeof a.text=="string"){if(typeof a.thought=="boolean"&&a.thought)continue;s=!0,i+=a.text}}return o.length>0&&console.warn(`there are non-text parts ${o} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),s?i:void 0}get data(){var e,n,r;let i="",s=[];for(let o 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[a,c]of Object.entries(o))a!=="inlineData"&&c!==null&&s.push(a);o.inlineData&&typeof o.inlineData.data=="string"&&(i+=atob(o.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}},hV=class{},mV=class{constructor(){this.functionResponses=[]}},$O=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},gV=class{},ix=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=Sz(e);return Object.assign(r,s),r}};(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"})(pl||(pl={}));hl=class{constructor(e,n,r,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,r,i)}init(e,n,r){var i,s;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let o={config:{}};!r||Object.keys(r).length===0?o={config:{}}:typeof r=="object"?o=Object.assign({},r):o=r,o.config&&(o.config.pageToken=n.nextPageToken),this.paramsInternal=o,this.pageInternalSize=(s=(i=o.config)===null||i===void 0?void 0:i.pageSize)!==null&&s!==void 0?s:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};HO=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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=lbe(this.apiClient,e),r=n._url,i=Ce("{model}:batchGenerateContent",r),a=n.batch.inputConfig.requests,c=a.requests,l=[];for(let u of c){let d=Object.assign({},u);if(d.systemInstruction){let f=d.systemInstruction;delete d.systemInstruction;let m=d.request;m.systemInstruction=f,d.request=m}l.push(d)}return a.requests=l,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 s=this.getGcsUri(e),o=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?r.dest=`${s.slice(0,-6)}/dest`:r.dest=`${s}_dest_${i}`;else if(o)r.dest=`${o}_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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=xct(this.apiClient,e);return a=Ce("batchPredictionJobs",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>_V(u))}else{let l=lbe(this.apiClient,e);return a=Ce("{model}:batchGenerateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>EO(u))}}async createEmbeddingsInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Tct(this.apiClient,e);return s=Ce("{model}:asyncBatchEmbedContent",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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=>EO(c))}}async get(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Bct(this.apiClient,e);return a=Ce("batchPredictionJobs/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>_V(u))}else{let l=Fct(this.apiClient,e);return a=Ce("batches/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>EO(u))}}async cancel(e){var n,r,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let c=_ct(this.apiClient,e);o=Ce("batchPredictionJobs/{name}:cancel",c._url),a=c._query,delete c._url,delete c._query,await 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})}else{let c=yct(this.apiClient,e);o=Ce("batches/{name}:cancel",c._url),a=c._query,delete c._url,delete c._query,await this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Kct(e);return a=Ce("batchPredictionJobs",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Xct(u),f=new rx;return Object.assign(f,d),f})}else{let l=zct(e);return a=Ce("batches",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Yct(u),f=new rx;return Object.assign(f,d),f})}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Cct(this.apiClient,e);return a=Ce("batchPredictionJobs/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Ict(u))}else{let l=Act(this.apiClient,e);return a=Ce("batches/{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Rct(u))}}};jO=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=llt(this.apiClient,e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=clt(this.apiClient,e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async get(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=_lt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=ylt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=dlt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=plt(u),f=new tx;return Object.assign(f,d),f})}else{let l=ult(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=flt(u),f=new tx;return Object.assign(f,d),f})}}async update(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Ult(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>u)}else{let l=Llt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>u)}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=blt(e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Alt(u),f=new nx;return Object.assign(f,d),f})}else{let l=xlt(e);return a=Ce("cachedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Tlt(u),f=new nx;return Object.assign(f,d),f})}}};WO=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new VO(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},VO=class{constructor(e,n,r,i={},s=[]){this.apiClient=e,this.modelsModule=n,this.model=r,this.config=i,this.history=s,this.sendPromise=Promise.resolve(),Blt(s)}async sendMessage(e){var n;await this.sendPromise;let r=Qr(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 s,o,a;let c=await i,l=(o=(s=c.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content,u=c.automaticFunctionCallingHistory,d=this.getHistory(!0).length,f=[];u!=null&&(f=(a=u.slice(d))!==null&&a!==void 0?a:[]);let m=l?[l]:[];this.recordHistory(r,m,f)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let r=Qr(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 s=await i;return this.processStreamResponse(s,r)}getHistory(e=!1){let n=e?pbe(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return pv(this,arguments,function*(){var i,s,o,a,c,l;let u=[];try{for(var d=!0,f=VS(e),m;m=yield Hn(f.next()),i=m.done,!i;d=!0){a=m.value,d=!1;let g=a;if(Flt(g)){let y=(l=(c=g.candidates)===null||c===void 0?void 0:c[0])===null||l===void 0?void 0:l.content;y!==void 0&&u.push(y)}yield yield Hn(g)}}catch(g){s={error:g}}finally{try{!d&&!i&&(o=f.return)&&(yield Hn(o.call(f)))}finally{if(s)throw s.error}}this.recordHistory(n,u)})}recordHistory(e,n,r){let i=[];n.length>0&&n.every(s=>s.role!==void 0)?i=n:i.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...pbe(r)):this.history.push(e),this.history.push(...i)}};sx=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}};uTe=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=zlt(e);return s=Ce("files",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Klt(c),u=new LO;return Object.assign(u,l),u})}}async createInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=qlt(e);return s=Ce("upload/v1beta/files",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=$lt(c),u=new UO;return Object.assign(u,l),u})}}async get(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=jlt(e);return s=Ce("files/{file}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Glt(e);return s=Ce("files/{file}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,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}).then(c=>c.json().then(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Hlt(c),u=new FO;return Object.assign(u,l),u})}}async registerFilesInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Wlt(e);return s=Ce("files:register",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ylt(c),u=new BO;return Object.assign(u,l),u})}}};Oft="Content-Type",Mft="X-Server-Timeout",Nft="User-Agent",wV="x-goog-api-client",Dft="2.23.0",Lft=`google-genai-sdk/${Dft}`,Uft="v1beta1",Fft="v1beta",Bft=new Set(["us","eu"]);Gft=5,Hft=1,jft=60,Wft=2,Vft=1,zft=[408,429,500,502,503,504],SV=class{constructor(e){var n,r,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let s={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let a=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!a?(s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?s.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Bft.has(this.clientOptions.location)?s.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(s.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),s.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:Uft}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),s.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Fft,s.baseUrl="https://generativelanguage.googleapis.com/";s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}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.")}constructUrl(e,n,r){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===xO.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[o,a]of Object.entries(e.queryParams))i.searchParams.append(o,String(a));let s={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString()),this.unaryApiCall(i,s,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,s]of Object.entries(n))typeof s=="object"?r[i]=Object.assign(Object.assign({},r[i]),s):s!==void 0&&(r[i]=s);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 s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString()),this.streamApiCall(i,s,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}async includeExtraHttpOptionsToRequestInit(e,n,r){return n?.timeout&&n.timeout>0&&qft(n.timeout),n&&n.extraBody!==null&&Kft(e,n.extraBody),e.headers=await this.getHeadersInternal(n,r),e}async unaryApiCall(e,n,r,i,s,o,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,s,o,a).then(async c=>(await _W(c),new Vu(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,n,r,i,s,o,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i,s,o,a).then(async c=>(await _W(c),this.processStreamResponse(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return pv(this,arguments,function*(){var r;let i=(r=e?.body)===null||r===void 0?void 0:r.getReader(),s=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let o="",a="data:",c=[`
525
525
 
526
526
  `,"\r\r",`\r
527
527
  \r
528
- `];for(;;){let{done:l,value:u}=yield Hn(i.read());if(l){if(o.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let d=s.decode(u,{stream:!0});try{let g=JSON.parse(d);if("error"in g){let y=JSON.parse(JSON.stringify(g.error)),w=y.status,S=y.code,T=`got status: ${w}. ${JSON.stringify(g)}`;if(S>=400&&S<600)throw new sx({message:T,status:S})}}catch(g){if(g.name==="ApiError")throw g}o+=d;let f=-1,m=0;for(;;){f=-1,m=0;for(let w of c){let S=o.indexOf(w);S!==-1&&(f===-1||S<f)&&(f=S,m=w.length)}if(f===-1)break;let g=o.substring(0,f);o=o.substring(f+m);let y=g.trim();if(y.startsWith(a)){let w=y.substring(a.length).trim();try{let S=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield Hn(new Vu(S))}catch(S){throw new Error(`exception parsing stream chunk ${w}. ${S}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n,r,i,s,o){var a,c,l,u,d,f;let m=o??fetch,g=(a=r?.httpStatusCodes)!==null&&a!==void 0?a:zft,y=async()=>{let R=$ft(i,s),C;try{C=await m(e,Object.assign(Object.assign({},n),{signal:R.signal}))}catch(D){throw R.dispose(),D}if(!r||C.ok||!g.includes(C.status))return C;try{await _3(C)}finally{R.dispose()}return C};if(!r)return y();let w=Math.max(1,(c=r.attempts)!==null&&c!==void 0?c:Gft),S=Math.round(((l=r.initialDelay)!==null&&l!==void 0?l:Hft)*1e3),T=Math.max(S,Math.round(((u=r.maxDelay)!==null&&u!==void 0?u:jft)*1e3));return(0,Bbe.default)(y,{retries:w-1,factor:(d=r.expBase)!==null&&d!==void 0?d:Wft,minTimeout:S,maxTimeout:T,randomize:((f=r.jitter)!==null&&f!==void 0?f:Vft)>0,onFailedAttempt:R=>{var C;if(s?.aborted)throw(C=R.error)!==null&&C!==void 0?C:R}})}getDefaultHeaders(){let e={},n=Lft+" "+this.clientOptions.userAgentExtra;return e[Nft]=n,e[wV]=n,e[Oft]="application/json",e}async getHeadersInternal(e,n){let r=new Headers;if(e&&e.headers)for(let[i,s]of Object.entries(e.headers))r.append(i,s);return e?.timeout&&e.timeout>0&&r.append(Mft,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 s=this.clientOptions.uploader,o=await s.stat(e);i.sizeBytes=String(o.size);let a=(r=n?.mimeType)!==null&&r!==void 0?r:o.type;if(a===void 0||a==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=a;let c={file:i},l=this.getFileName(e),u=Ce("upload/v1beta/files",c._url),d=await this.fetchUploadUrl(u,i.sizeBytes,i.mimeType,l,c,n?.httpOptions);return s.upload(e,d,this)}async uploadFileToFileSearchStore(e,n,r){var i;let s=this.clientOptions.uploader,o=await s.stat(n),a=String(o.size),c=(i=r?.mimeType)!==null&&i!==void 0?i:o.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(n),d={};r!=null&&ETe(r,d);let f=await this.fetchUploadUrl(l,a,c,u,d,r?.httpOptions);return s.uploadToFileSearchStore(n,f,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,r,i,s,o){var a;let c={};o?c=o:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`},i?{"X-Goog-Upload-File-Name":i}:{})};let l=await this.request({path:e,body:JSON.stringify(s),httpMethod:"POST",httpOptions:c});if(!l||!l?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=(a=l?.headers)===null||a===void 0?void 0:a["x-goog-upload-url"];if(u===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}};Yft="mcp_used/unknown",wTe=!1;ox=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 s={},o=[];for(let u of this.mcpClients)try{for(var a=!0,c=(n=void 0,VS(Jft(u))),l;l=await c.next(),e=l.done,!e;a=!0){i=l.value,a=!1;let d=i;o.push(d);let f=d.name;if(s[f])throw new Error(`Duplicate function name ${f} found in MCP tools. Please ensure function names are unique.`);s[f]=u}}catch(d){n={error:d}}finally{try{!a&&!e&&(r=c.return)&&await r.call(c)}finally{if(n)throw n.error}}this.mcpTools=o,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),oct(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],s;this.config.timeout&&(s={timeout:this.config.timeout});let o=await i.callTool({name:r.name,arguments:r.args},void 0,s);n.push({functionResponse:{name:r.name,response:o.isError?{error:o}:o}})}return n}};xV=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(),s=this.apiClient.getApiVersion(),o=npt(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),c=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`,l=()=>{},u=new Promise(R=>{l=R}),d=e.callbacks,f=function(){l({})},m=this.apiClient,g={onopen:f,onmessage:R=>{ept(m,d.onmessage,R)},onerror:(n=d?.onerror)!==null&&n!==void 0?n:function(R){},onclose:(r=d?.onclose)!==null&&r!==void 0?r:function(R){}},y=this.webSocketFactory.create(c,tpt(o),g);y.connect(),await u;let T={setup:{model:Kt(this.apiClient,e.model)}};return y.send(JSON.stringify(T)),new bV(y,this.apiClient)}},bV=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=uut(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=lut(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(gm.PLAY)}pause(){this.sendPlaybackControl(gm.PAUSE)}stop(){this.sendPlaybackControl(gm.STOP)}resetContext(){this.sendPlaybackControl(gm.RESET_CONTEXT)}close(){this.conn.close()}};rpt="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";zO=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r,this.music=new xV(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,r,i,s,o,a;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let c=this.apiClient.getWebsocketBaseUrl(),l=this.apiClient.getApiVersion(),u,d=this.apiClient.getHeaders();e.config&&e.config.tools&&STe(e.config.tools)&&xTe(d);let f=apt(d);if(this.apiClient.isVertexAI()){let I=this.apiClient.getProject(),P=this.apiClient.getLocation(),F=this.apiClient.getApiKey(),X=!!I&&!!P||!!F;this.apiClient.getCustomBaseUrl()&&!X?u=c:(u=`${c}/ws/google.cloud.aiplatform.${l}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u))}else{let I=this.apiClient.getApiKey(),P="BidiGenerateContent",F="key";I?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),l!=="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."),P="BidiGenerateContentConstrained",F="access_token"),u=`${c}/ws/google.ai.generativelanguage.${l}.GenerativeService.${P}?${F}=${I}`}let m=()=>{},g=new Promise(I=>{m=I}),y=e.callbacks,w=function(){var I;(I=y?.onopen)===null||I===void 0||I.call(y),m({})},S=this.apiClient,T=!1,R=[],C=()=>{},D=new Promise(I=>{C=I}),$={onopen:w,onmessage:I=>{ipt(S,P=>{P.setupComplete&&!M.setupComplete&&(M.setupComplete=P.setupComplete,C({})),T?y.onmessage(P):R.push(P)},I)},onerror:(n=y?.onerror)!==null&&n!==void 0?n:function(I){},onclose:(r=y?.onclose)!==null&&r!==void 0?r:function(I){}},G=this.webSocketFactory.create(u,opt(f),$);G.connect(),await g;let V=Kt(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&V.startsWith("publishers/")){let I=this.apiClient.getProject(),P=this.apiClient.getLocation();I&&P&&(V=`projects/${I}/locations/${P}/`+V)}let L={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[zS.AUDIO]}:e.config.responseModalities=[zS.AUDIO]),!((s=e.config)===null||s===void 0)&&s.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let k=(a=(o=e.config)===null||o===void 0?void 0:o.tools)!==null&&a!==void 0?a:[],E=[];for(let I of k)if(this.isCallableTool(I)){let P=I;E.push(await P.tool())}else E.push(I);E.length>0&&(e.config.tools=E);let A={model:V,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?L=cut(this.apiClient,A):L=aut(this.apiClient,A),delete L.config;let M=new KO(G,this.apiClient);G.send(JSON.stringify(L)),await D,T=!0;for(let I of R)y.onmessage(I);return M}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},spt={turnComplete:!0},KO=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=gs(n.turns),e.isVertexAI()||(r=r.map(i=>lx(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 s of r){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(rpt)}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},spt),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:fut(e)}:n={realtimeInput:dut(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};_be=10;_m=class t extends ic{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=gs(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=gs(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let s=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:KS.EMBED_CONTENT});return await this.embedContentInternal(s)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:KS.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var r,i,s,o,a;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!cpt(n)||vbe(n.config))return await this.generateContentInternal(c);let l=Ebe(n);if(l.length>0){let y=l.map(w=>`tools[${w}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${y}.`)}let u,d,f=gs(c.contents),m=(s=(i=(r=c.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&s!==void 0?s:_be,g=0;for(;g<m&&(u=await this.generateContentInternal(c),!(!u.functionCalls||u.functionCalls.length===0));){let y=u.candidates[0].content,w=[];for(let S of(a=(o=n.config)===null||o===void 0?void 0:o.tools)!==null&&a!==void 0?a:[])if(hv(S)){let R=await S.callTool(u.functionCalls);w.push(...R)}g++,d={role:"user",parts:w},c.contents=gs(c.contents),c.contents.push(y),c.contents.push(d),wbe(c.config)&&(f.push(y),f.push(d))}return wbe(c.config)&&(u.automaticFunctionCallingHistory=f),u},this.generateContentStream=async n=>{var r,i,s,o,a;if(this.maybeMoveToResponseJsonSchema(n),vbe(n.config)){let d=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(d)}let c=Ebe(n);if(c.length>0){let d=c.map(f=>`tools[${f}]`).join(", ");throw new Error(`Incompatible tools found at ${d}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let l=(s=(i=(r=n?.config)===null||r===void 0?void 0:r.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,u=(a=(o=n?.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||a===void 0?void 0:a.disable;if(l&&!u)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 s,o=[];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"?s=c?.safetyAttributes:o.push(c);let a;return s?a={generatedImages:o,positivePromptSafetyAttributes:s,sdkHttpResponse:r.sdkHttpResponse}:a={generatedImages:o,sdkHttpResponse:r.sdkHttpResponse},a})),this.list=async n=>{var r;let o={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!o.config.queryBase){if(!((r=o.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.");o.config.filter="labels.tune-type:*"}return new hl(pl.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(o),o)},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,s,o,a,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}:!((o=(s=n.source)===null||s===void 0?void 0:s.video)===null||o===void 0)&&o.uri&&(!((c=(a=n.source)===null||a===void 0?void 0:a.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchema(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,r,i;let s=(n=e.config)===null||n===void 0?void 0:n.tools;if(!s)return e;let o=await Promise.all(s.map(async c=>hv(c)?await c.tool():c)),a={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:o})};if(a.config.tools=o,e.config&&e.config.tools&&STe(e.config.tools)){let c=(i=(r=e.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&i!==void 0?i:{},l=Object.assign({},c);Object.keys(l).length===0&&(l=this.apiClient.getDefaultHeaders()),xTe(l),a.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:l})}return a}async initAfcToolsMap(e){var n,r,i;let s=new Map;for(let o of(r=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&r!==void 0?r:[])if(hv(o)){let a=o,c=await a.tool();for(let l of(i=c.functionDeclarations)!==null&&i!==void 0?i:[]){if(!l.name)throw new Error("Function declaration name is required.");if(s.has(l.name))throw new Error(`Duplicate tool declaration name: ${l.name}`);s.set(l.name,a)}}return s}async processAfcStream(e){var n,r,i;let s=(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:_be,o=!1,a=0,c=await this.initAfcToolsMap(e);return(function(l,u,d){return pv(this,arguments,function*(){for(var f,m,g,y,w,S;a<s;){o&&(a++,o=!1);let D=yield Hn(l.processParamsMaybeAddMcpUsage(d)),$=yield Hn(l.generateContentStreamInternal(D)),G=[],V=[];try{for(var T=!0,R=(m=void 0,VS($)),C;C=yield Hn(R.next()),f=C.done,!f;T=!0){y=C.value,T=!1;let L=y;if(yield yield Hn(L),L.candidates&&(!((w=L.candidates[0])===null||w===void 0)&&w.content)){V.push(L.candidates[0].content);for(let k of(S=L.candidates[0].content.parts)!==null&&S!==void 0?S:[])if(a<s&&k.functionCall){if(!k.functionCall.name)throw new Error("Function call name was not returned by the model.");if(u.has(k.functionCall.name)){let E=yield Hn(u.get(k.functionCall.name).callTool([k.functionCall]));G.push(...E)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${u.keys()}, missing tool: ${k.functionCall.name}`)}}}}catch(L){m={error:L}}finally{try{!T&&!f&&(g=R.return)&&(yield Hn(g.call(R)))}finally{if(m)throw m.error}}if(G.length>0){o=!0;let L=new Bf;L.candidates=[{content:{role:"user",parts:G}}],yield yield Hn(L);let k=[];k.push(...V),k.push({role:"user",parts:G});let E=gs(d.contents).concat(k);d.contents=E}else break}})})(this,c,e)}async generateContentInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mbe(this.apiClient,e);return a=Ce("{model}:generateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=ybe(u),f=new Bf;return Object.assign(f,d),f})}else{let l=hbe(this.apiClient,e);return a=Ce("{model}:generateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=gbe(u),f=new Bf;return Object.assign(f,d),f})}}async generateContentStreamInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mbe(this.apiClient,e);return a=Ce("{model}:streamGenerateContent?alt=sse",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.requestStream({path:a,queryParams:c,body:JSON.stringify(l),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}),o.then(function(d){return pv(this,arguments,function*(){var f,m,g,y;try{for(var w=!0,S=VS(d),T;T=yield Hn(S.next()),f=T.done,!f;w=!0){y=T.value,w=!1;let R=y,C=ybe(yield Hn(R.json()),e);C.sdkHttpResponse={headers:R.headers};let D=new Bf;Object.assign(D,C),yield yield Hn(D)}}catch(R){m={error:R}}finally{try{!w&&!f&&(g=S.return)&&(yield Hn(g.call(S)))}finally{if(m)throw m.error}}})})}else{let l=hbe(this.apiClient,e);return a=Ce("{model}:streamGenerateContent?alt=sse",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.requestStream({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),o.then(function(d){return pv(this,arguments,function*(){var f,m,g,y;try{for(var w=!0,S=VS(d),T;T=yield Hn(S.next()),f=T.done,!f;w=!0){y=T.value,w=!1;let R=y,C=gbe(yield Hn(R.json()),e);C.sdkHttpResponse={headers:R.headers};let D=new Bf;Object.assign(D,C),yield yield Hn(D)}}catch(R){m={error:R}}finally{try{!w&&!f&&(g=S.return)&&(yield Hn(g.call(S)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Qut(this.apiClient,e,e),u=cct(e.model)?"{model}:embedContent":"{model}:predict";return a=Ce(u,l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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().then(f=>{let m=f;return m.sdkHttpResponse={headers:d.headers},m})),o.then(d=>{let f=edt(d,e),m=new YS;return Object.assign(m,f),m})}else{let l=Jut(this.apiClient,e);return a=Ce("{model}:batchEmbedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Zut(u),f=new YS;return Object.assign(f,d),f})}}async generateImagesInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=cdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=ldt(c),u=new bO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=zut(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Kut(c),u=new TO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=dft(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=fft(c),u=new AO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=Hdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=jdt(c),u=new CO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=Jdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Qdt(c),u=new RO;return Object.assign(u,l),u})}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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Tdt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>EV(u))}else{let l=bdt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>vV(u))}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Mdt(this.apiClient,e);return a=Ce("{models_url}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Ddt(u),f=new XS;return Object.assign(f,d),f})}else{let l=Odt(this.apiClient,e);return a=Ce("{models_url}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Ndt(u),f=new XS;return Object.assign(f,d),f})}}async update(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=lft(this.apiClient,e);return a=Ce("{model}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>EV(u))}else{let l=cft(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>vV(u))}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Hut(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Wut(u),f=new JS;return Object.assign(f,d),f})}else{let l=Gut(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=jut(u),f=new JS;return Object.assign(f,d),f})}}async countTokens(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=But(this.apiClient,e);return a=Ce("{model}:countTokens",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=$ut(u),f=new QS;return Object.assign(f,d),f})}else{let l=Fut(this.apiClient,e);return a=Ce("{model}:countTokens",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=qut(u),f=new QS;return Object.assign(f,d),f})}}async computeTokens(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=kut(this.apiClient,e);return s=Ce("{model}:computeTokens",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Put(c),u=new IO;return Object.assign(u,l),u})}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,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mdt(this.apiClient,e);return a=Ce("{model}:predictLongRunning",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>{let d=pdt(u),f=new ZS;return Object.assign(f,d),f})}else{let l=hdt(this.apiClient,e);return a=Ce("{model}:predictLongRunning",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>{let d=fdt(u),f=new ZS;return Object.assign(f,d),f})}}};_m.loggedGenerateImagesWarning=!1;_m.loggedEditImageWarning=!1;_m.loggedGenerateVideosWarning=!1;YO=class extends ic{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],s;r&&"httpOptions"in r&&(s=r.httpOptions);let o=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:o,_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],s;r&&"httpOptions"in r&&(s=r.httpOptions);let o=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:o,_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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Bat(e);return a=Ce("{operationName}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o}else{let l=Fat(e);return a=Ce("{operationName}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o}}async fetchPredictVideosOperationInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Pat(e);return s=Ce("{resourceName}:fetchPredictOperation",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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).")}};XO=class extends ic{constructor(e){super(),this.apiClient=e}async create(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let a=ppt(this.apiClient,e);s=Ce("auth_tokens",a._url),o=a._query,delete a.config,delete a._url,delete a._query;let c=Tpt(a,e.config);return i=this.apiClient.request({path:s,queryParams:o,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(l=>l.json()),i.then(l=>l)}}};TV=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async n=>new hl(pl.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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Rpt(e);return s=Ce("{name}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let o=Cpt(e);i=Ce("{name}",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(o),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=kpt(e);return s=Ce("{parent}/documents",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ppt(c),u=new OO;return Object.assign(u,l),u})}}};AV=class extends ic{constructor(e,n=new TV(e)){super(),this.apiClient=e,this.documents=n,this.list=async(r={})=>new hl(pl.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 s={};r.searchParams.forEach((c,l)=>{s[l]=c}),s.alt="media";let o=Object.assign({},n?.httpOptions),a=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:s,httpOptions:o});if(a instanceof Vu){let c=await a.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=vft(this.apiClient,e);return s=Ce("fileSearchStores",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Sft(e);return s=Ce("{name}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let o=wft(e);i=Ce("{name}",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(o),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Rft(e);return s=Ce("fileSearchStores",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ift(c),u=new MO;return Object.assign(u,l),u})}}async uploadToFileSearchStoreInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=kft(e);return s=Ce("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Pft(c),u=new NO;return Object.assign(u,l),u})}}async importFile(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Tft(e);return s=Ce("{file_search_store_name}:importFile",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=bft(c),u=new DO;return Object.assign(u,l),u})}}};CV=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return Upt(await this.options.getAuthHeaders(e))}},RV=class{beforeCreateRequest(e,n){return Object.assign(Object.assign({},n),{url:Npt(n.url)})}async beforeRequest(e,n){if(xbe(n.headers,Lpt(e.security_source)),Fpt(e,n.headers),qpt(n.headers))return n;let r=await Dpt(e.security_source,n.url);return xbe(n.headers,r?.default_headers),Bpt(n.headers,r),n}};Gf=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)}},JO=class extends Gf{constructor(){super(...arguments),this.name="UnexpectedClientError"}},dv=class extends Gf{constructor(){super(...arguments),this.name="InvalidRequestError"}},QO=class extends Gf{constructor(){super(...arguments),this.name="RequestAbortedError"}},ZO=class extends Gf{constructor(){super(...arguments),this.name="RequestTimeoutError"}},e1=class extends Gf{constructor(){super(...arguments),this.name="ConnectionError"}};na=class extends Error{constructor(e,n){var r,i,s,o;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=(s=n?.response)===null||s===void 0?void 0:s.headers,this.contentType=((o=n?.response)===null||o===void 0?void 0:o.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError"}};IV=class extends Error{},ys=class t extends IV{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=Tbe(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 s=n&&Wpt(n)&&typeof n.message=="string"?n.message:void 0,o=Tbe(n),a=(i=s??r)!==null&&i!==void 0?i:o||"An error occurred";return`${e?`${e} `:""}${a}`}static generate(e,n,r,i){return!e||!i?new mv({message:r,cause:n instanceof Error?n:void 0}):e===400?new OV(e,n,r,i):e===401?new MV(e,n,r,i):e===403?new NV(e,n,r,i):e===404?new DV(e,n,r,i):e===409?new LV(e,n,r,i):e===422?new UV(e,n,r,i):e===429?new FV(e,n,r,i):e>=500?new BV(e,n,r,i):new t(e,n,r,i)}},kV=class extends ys{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},mv=class extends ys{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},PV=class extends mv{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."})}},OV=class extends ys{},MV=class extends ys{},NV=class extends ys{},DV=class extends ys{},LV=class extends ys{},UV=class extends ys{},FV=class extends ys{},BV=class extends ys{};zpt=(t,e)=>e==null?fetch(t):fetch(t,e),t1=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||zpt}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}},Abe=/\s*;\s*/g;Kpt=new RegExp("^[0-9]xx$","i");n1=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);Jpt(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,s=r;for(let o of this.afterErrorHooks){let a=await o.afterError(e,i,s);i=a.response,s=a.error}return{response:i,error:s}}};eht=Object.prototype.hasOwnProperty;Rbe=["https://generativelanguage.googleapis.com"];nht={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};sht=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;kTe=oht(",");De=(t,e,n)=>{let r="",i=n?.explode?PTe(t,e):[[t,e]];if(i.every(([a,c])=>c==null))return;let s=a=>c1(a,n?.charEncoding),o=a=>s(OTe(a));return i.forEach(([a,c])=>{var l;let u="";if(c!=null){if(Array.isArray(c))u=(l=NTe(c,d=>`${o(d)}`))===null||l===void 0?void 0:l.join(",");else if(Hf(c)){let d=DTe(Object.entries(c),([f,m])=>`,${s(f)},${o(m)}`);u=d?.join("").slice(1)}else u=`${n?.explode&&Hf(e)?`${a}=`:""}${o(c)}`;r+=u?`,${u}`:""}}),r.slice(1)};cc=cht(kTe);Ibe={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},cx=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)}},jf=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};uht=new RegExp("^[0-9]xx$","i");yO=typeof globalThis>"u"?null:globalThis,hht=typeof yO=="object"&&yO!=null&&"importScripts"in yO&&typeof yO.importScripts=="function",mht=hht||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",sc=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof n1?this._hooks=n.hooks:this._hooks=new n1;let r=new t1;e.http_client=e.http_client||r,e=this._hooks.sdkInit(e);let i=tht(e);i&&(i.pathname=i.pathname.replace(/\/+$/,"")+"/"),this._baseURL=i,this._httpClient=e.http_client||r,this._options=Object.assign(Object.assign({},Mpt(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&ax().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,r){var i,s,o,a,c;let{method:l,path:u,query:d,headers:f,security:m}=n,g=(i=n.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!g)return ju(new dv("No base URL provided for operation"));let y=new URL(g),w;u?(y.pathname=y.pathname.replace(/\/+$/,"")+"/",w=new URL(u,y),!w.search&&y.search&&(w.search=y.search)):w=y,w.hash="";let S=(I,P)=>{if(!P)return I;let F=new Set(P.split("&").filter(N=>N!=="").map(N=>{var b;return(b=N.split("=")[0])!==null&&b!==void 0?b:""}));return[...I.split("&").filter(N=>{var b;return N!==""&&!F.has((b=N.split("=")[0])!==null&&b!==void 0?b:"")}),P].join("&")},T=I=>Object.entries(I).map(([P,F])=>{if(F==null)return;let X=Hf(F)?JSON.stringify(F):F;return kTe(P,X,{explode:Array.isArray(X),charEncoding:"percent"})}).filter(P=>typeof P<"u").join("&"),R=[d||"",T(r?.extra_query||{}),T(m?.queryParams||{})].reduce(S,w.search.slice(1));R&&(w.search=`?${R}`);let C=new Headers(f),D=m?.basic.username,$=m?.basic.password;if(D!=null||$!=null){let I=Zpt([D||"",$||""].join(":"));C.set("Authorization",`Basic ${I}`)}let G=new Headers(m?.headers||{});for(let[I,P]of G)C.set(I,P);let V=C.get("cookie")||"";for(let[I,P]of Object.entries(m?.cookies||{}))V+=`; ${I}=${P}`;V=V.startsWith("; ")?V.slice(2):V,C.set("cookie",V);let L=new Headers((s=r?.headers)!==null&&s!==void 0?s:(o=r?.fetch_options)===null||o===void 0?void 0:o.headers);for(let[I,P]of L)C.set(I,P);mht||C.set((a=n.uaHeader)!==null&&a!==void 0?a:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:nht.userAgent);let k=n.body,E=Object.fromEntries(Object.entries(r?.extra_body||{}).filter(([,I])=>typeof I<"u"));if(Object.keys(E).length>0){let I=new Headers(f).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(I)||typeof k!="string"&&k!=null)return ju(new dv("extra_body can only be merged into JSON object request bodies"));let F;try{F=k?JSON.parse(k):{}}catch(X){return ju(new dv("extra_body can only be merged into JSON object request bodies",{cause:X}))}if(!Hf(F))return ju(new dv("extra_body can only be merged into JSON object request bodies"));k=JSON.stringify(Object.assign(Object.assign({},F),E)),C.delete("content-length")}let A=Object.assign(Object.assign({},r?.fetch_options),r);!A?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign(A,{duplex:"half"});let M;try{M=this._hooks.beforeCreateRequest(e,{url:w,options:Object.assign(Object.assign({},A),{body:k??null,headers:C,method:l})})}catch(I){return ju(new JO("Create request hook failed to execute",{cause:I}))}return Cbe(new Request(M.url,M.options))}async _do(e,n){let{context:r,isErrorStatusCode:i}=n,s=r.timeout_ms;return lht(async()=>{var o;let a=e.clone(),c=a;if(s!=null&&s>0){let d=AbortSignal.timeout(s),f=(o=rht(a.signal,d))!==null&&o!==void 0?o:d;c=new Request(a,{signal:f})}let l=await this._hooks.beforeRequest(r,c);await ght(this._logger,l).catch(d=>{var f;return(f=this._logger)===null||f===void 0?void 0:f.log("Failed to log request:",d)});let u=await this._httpClient.request(l);try{if(i(u.status)){let d=await this._hooks.afterError(r,u,null);if(d.error)throw d.error;u=d.response||u}else u=await this._hooks.afterSuccess(r,u)}finally{await yht(this._logger,u,l).catch(d=>{var f;return(f=this._logger)===null||f===void 0?void 0:f.log("Failed to log response:",d)})}return u},{config:n.retryConfig,statusCodes:n.retryCodes}).then(o=>Cbe(o),o=>{switch(!0){case Xpt(o):return ju(new QO("Request aborted by client",{cause:o}));case RTe(o):return ju(new ZO("Request timed out",{cause:o}));case CTe(o):return ju(new e1("Unable to make request",{cause:o}));default:return ju(new JO("Unexpected HTTP client error",{cause:o}))}})}},FTe=/^(application|text)\/([^+]+\+)*json.*/,Pbe=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;r1=class extends na{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?`
529
- `:". ";let s=i;if(i.length>1e4){let o=i.substring(0,1e4),a=i.length-1e4;s=`${o}...and ${a} more chars`}e+=`Body: ${s}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError"}};qV=class extends ReadableStream{constructor(e,n,r){var i;let s=e.getReader(),o=new Uint8Array(4096),a=0,c=0,l={eventId:void 0},u=(i=r?.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(d){try{for(;;){let f=Eht(o,a,c);if(!f){c=Math.max(0,a-vht+1);let y=await s.read();if(y.done)return d.close();if(a+y.value.length>o.length){let w=new Uint8Array(Math.max(o.length*2,a+y.value.length));w.set(o.subarray(0,a)),o=w}o.set(y.value,a),a+=y.value.length;continue}let m=o.slice(0,f.index);if(o.copyWithin(0,f.index+f.length,a),a-=f.index+f.length,o.length>4096&&a<=o.length>>2){let y=new Uint8Array(Math.max(4096,a*2));y.set(o.subarray(0,a)),o=y}c=0;let g=wht(m,n,l,u);if(g&&!g.done)return d.enqueue(g.value);if(g?.done)return await s.cancel("done"),d.close()}}catch(f){d.error(f),await s.cancel(f)}},cancel:d=>s.cancel(d)})}[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 o=await r.read();return o.done?(r.releaseLock(),{done:!0,value:void 0}):{done:!1,value:o.value}},throw:async o=>(await r.cancel(o),r.releaseLock(),{done:!0,value:void 0}),return:async()=>(await r.cancel("done"),r.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},s=Symbol.asyncDispose;return s&&(i[s]=async()=>{var o;await((o=i.return)===null||o===void 0?void 0:o.call(i))}),i}values(e){return this[Symbol.asyncIterator](e)}},ea=13,ta=10,BTe=[[ea,ta,ea,ta],[ea,ta,ea],[ea,ta,ta],[ea,ea,ta],[ta,ea,ta],[ea,ea],[ta,ea],[ta,ta]],vht=BTe.reduce((t,e)=>Math.max(t,e.length),0);Sht={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};xht=/, */;Mbe={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},$V=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(Mbe.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(Mbe.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};At=class t{constructor(e,n){this[GTe]="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,s])=>[e(i),s]);return r.catch(()=>{}),new t(r,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};GTe=Symbol.toStringTag;GV=class extends sc{list(e,n){return qt(VTe(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(HTe(this,i,r,n))}delete(e,n,r){return qt(jTe(this,e,n?.api_version,r))}get(e,n,r){return qt(WTe(this,e,n?.api_version,r))}};HV=class extends sc{list(e,n){return qt(XTe(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(zTe(this,i,r,n))}delete(e,n,r){return qt(KTe(this,e,n?.api_version,r))}get(e,n,r){return qt(YTe(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i,update_mask:s}=n,o=Cr(n,["api_version","update_mask"]);return qt(JTe(this,e,o,i,s,r))}};jV=class extends sc{list(e,n,r,i){return qt(nAe(this,e,n,r?.api_version,r?.page_size,r?.page_token,r?.recursive,i))}};WV=class extends sc{startUpload(e,n,r,i){return qt(rAe(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))}};VV=class extends sc{get internal(){var e;return(e=this._internal)!==null&&e!==void 0?e:this._internal=new WV(this._options)}get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new jV(this._options)}listEnvironments(e,n){return qt(tAe(this,e?.api_version,e?.page_size,e?.page_token,n))}createEnvironment(e,n,r){return qt(QTe(this,e,n,r))}deleteEnvironment(e,n,r){return qt(ZTe(this,e,n?.api_version,r))}getEnvironment(e,n,r){return qt(eAe(this,e,n?.api_version,r))}};zV=class extends na{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"}},KV=class extends na{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"}};YV=class extends na{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"}},XV=class extends na{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"}};JV=class extends na{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"}},QV=class extends na{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"}};ZV=class extends na{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"}},ez=class extends na{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"}};tz=class extends sc{create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(sAe(this,i,r,n))}delete(e,n,r){return qt(jht(this,e,n?.api_version,r))}get(e,n,r){return qt(oAe(this,e,n?.api_version,n?.include_input,n?.last_event_id,n?.stream,r))}cancel(e,n,r){return qt(iAe(this,e,n?.api_version,r))}};nz=class extends sc{list(e,n){return qt(dAe(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(aAe(this,i,r,n))}delete(e,n,r){return qt(cAe(this,e,n?.api_version,r))}get(e,n,r){return qt(lAe(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i}=n,s=Cr(n,["api_version"]);return qt(pAe(this,e,s,i,r))}listExecutions(e,n,r){return qt(uAe(this,e,n?.api_version,n?.page_size,n?.page_token,r))}run(e,n,r){return qt(fAe(this,e,n?.api_version,r))}};rz=class extends sc{list(e,n){return qt(yAe(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(hAe(this,i,r,n))}delete(e,n,r){return qt(mAe(this,e,n?.api_version,r))}get(e,n,r){return qt(gAe(this,e,n?.api_version,r))}update(e,n,r){let i=n??{},{api_version:s,update_mask:o}=i,a=Cr(i,["api_version","update_mask"]),c=n===void 0||Object.keys(a).length===0?void 0:a;return qt(EAe(this,e,s,o,c,r))}ping(e,n,r,i){return qt(_Ae(this,e,n,r,i))}rotateSigningSecret(e,n,r,i){return qt(vAe(this,e,n,r,i))}};amt=class extends sc{get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new VV(this._options)}get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new GV(this._options)}get credentials(){var e;return(e=this._credentials)!==null&&e!==void 0?e:this._credentials=new HV(this._options)}get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new tz(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new nz(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new rz(this._options)}};cmt=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);iz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);if(i.stream===!0){let o=await v3(()=>this.getClient(r).interactions.create(Object.assign(Object.assign({},i),{stream:!0,api_version:r}),It(n,!0)));return Dbe(o)}let s=await en(sAe(this.getClient(r),i,r,It(n)));return E3(s)}async get(e,n={},r){let{api_version:i,stream:s=!1,last_event_id:o,include_input:a}=n??{};if(s===!0){let l=await v3(()=>this.getClient(i).interactions.get(e,{stream:s,last_event_id:o,include_input:a,api_version:i},It(r,!0)));return Dbe(l)}let c=await en(oAe(this.getClient(i),e,i,a,o,s,It(r)));return E3(c)}async delete(e,n={},r){return v3(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},It(r)))}async cancel(e,n={},r){return E3(await en(iAe(this.getClient(n?.api_version),e,n?.api_version,It(r))))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},sz=class{constructor(e){this.parentClient=e}async create(e={},n){let r=e??{},{api_version:i}=r,s=Cr(r,["api_version"]);return en(HTe(this.getClient(i),s,i,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s,parent:o}=e??{};return en(VTe(this.getClient(r),r,i,s,o,It(n)))}async get(e,n={},r){return en(WTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async delete(e,n={},r){return en(jTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},oz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(hAe(this.getClient(),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(yAe(this.getClient(),r,i,s,It(n)))}async get(e,n={},r){return en(gAe(this.getClient(),e,n?.api_version,It(r)))}async update(e,n={},r){let i=n??{},{api_version:s,update_mask:o}=i,a=Cr(i,["api_version","update_mask"]);return en(EAe(this.getClient(),e,s,o,a,It(r)))}async delete(e,n={},r){return en(mAe(this.getClient(),e,n?.api_version,It(r)))}async rotateSigningSecret(e,n={},r){let i=n??{},{api_version:s}=i,o=Cr(i,["api_version"]);return en(vAe(this.getClient(),e,s,o,It(r)))}async ping(e,n=void 0,r){let{api_version:i,body:s}=n??{};return en(_Ae(this.getClient(),e,i,s,It(r)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=ra(this.parentClient)),this.sdk}},az=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(aAe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,filter:i,page_size:s,page_token:o}=e??{};return en(dAe(this.getClient(r),r,i,s,o,It(n)))}async get(e,n={},r){return en(lAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async update(e,n,r){let{api_version:i}=n,s=Cr(n,["api_version"]);return en(pAe(this.getClient(i),e,s,i,It(r)))}async delete(e,n={},r){return en(cAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async run(e,n={},r){return en(fAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async listExecutions(e,n={},r){let{api_version:i,page_size:s,page_token:o}=n??{};return en(uAe(this.getClient(i),e,i,s,o,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}};cz=class{constructor(e,n){this.resolveClient=e,this.parentClient=n}async list(e,n){return en(nAe(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,It(n)))}async download(e,n){var r,i;let s=e.environment;if(!s)throw new Error("environment is required.");let o=s.startsWith("environments/")?s:`environments/${s}`,a=e.path.replace(/^\/+/,""),c=`${o}/files/${a}`,l=this.parentClient;if(!l||typeof l.request!="function")throw new Error("apiClient is required to download files.");let u=await l.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(u&&u.responseInternal&&typeof u.responseInternal.arrayBuffer=="function"){let d=await u.responseInternal.arrayBuffer();return new Uint8Array(d)}throw new Error("Unexpected response type from download")}async upload(e,n){var r,i,s,o,a,c,l,u;let d=e.environment;if(!d)throw new Error("environment is required.");d.startsWith("environments/")||`${d}`;let f=e.path.replace(/^\/+/,""),m=this.parentClient;if(!m||typeof m.request!="function")throw new Error("apiClient is required to upload files.");let g,y=0,w=e.mime_type;if(typeof e.file=="string"){let k;try{let E=globalThis.require;E&&(k=E("fs").readFileSync(e.file))}catch{}if(!k&&typeof globalThis.process<"u")try{let E=(i=(r=globalThis.process.mainModule)===null||r===void 0?void 0:r.require)!==null&&i!==void 0?i:globalThis.require;E&&(k=E("fs").readFileSync(e.file))}catch{}if(k)g=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),y=g.byteLength;else throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);w||(w=_mt(e.file))}else if(typeof Blob<"u"&&e.file instanceof Blob)g=e.file,y=e.file.size,!w&&e.file.type&&(w=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)g=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,y=g.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(e.file)){let k=e.file;g=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),y=g.byteLength}else throw new Error("Unsupported file type for upload.");w||(w="application/octet-stream");let S=d.startsWith("environments/")?d.replace(/^environments\//,""):d,[T,R]=await rAe(this.resolveClient(e.api_version),S,f,"start",y,w,"resumable",e.api_version,e.extract,e.overwrite,It(n)).$inspect();if(!T.ok)throw ym(T.error);let C=R.status==="complete"?(a=(o=(s=R.response)===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o.get("x-goog-upload-url"))!==null&&a!==void 0?a:(l=(c=R.response)===null||c===void 0?void 0:c.headers)===null||l===void 0?void 0:l.get("X-Goog-Upload-URL"):void 0;if(!C)throw new Error("Failed to get upload URL from upload handshake response.");let D=8*1024*1024,$=0,G,V=g instanceof Blob?g:new Blob([g]);for(;$<y||y===0&&$===0;){let k=Math.min($+D,y),E=V.slice($,k),A=k>=y,M=A?"upload, finalize":"upload";if(G=await m.request({path:"",body:E,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:"",baseUrl:C,headers:Object.assign(Object.assign({},((u=n?.httpOptions)===null||u===void 0?void 0:u.headers)||{}),{"X-Goog-Upload-Command":M,"X-Goog-Upload-Offset":`${$}`})})}),$=k,A)break}let L;if(G&&typeof G.json=="function"?L=await G.json():G&&G.responseInternal&&typeof G.responseInternal.json=="function"&&(L=await G.responseInternal.json()),L&&typeof L=="object"){if(Array.isArray(L.files))return L;if(L.name||L.path)return{files:[L]};if(L.file&&typeof L.file=="object")return{files:[L.file]}}return L}},lz=class{constructor(e){this.parentClient=e,this.files=new cz(n=>this.getClient(n),this.parentClient)}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(QTe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(tAe(this.getClient(r),r,i,s,It(n)))}async get(e,n={},r){return en(eAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async delete(e,n={},r){return en(ZTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},uz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(zTe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(XTe(this.getClient(r),r,i,s,It(n)))}async get(e,n={},r){return en(YTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async update(e,n,r){let{api_version:i,update_mask:s}=n,o=Cr(n,["api_version","update_mask"]);return en(JTe(this.getClient(i),e,o,i,s,It(r)))}async delete(e,n={},r){return en(KTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}};Ube="x-goog-api-key",WS="https://www.googleapis.com/auth/cloud-platform",dz=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=vmt(e.googleAuthOptions);this.googleAuth=new qbe.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(Ube)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(Ube,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,s]of r)e.get(i)===null&&e.append(i,s)}};fz=class{async download(e,n){if(e.downloadPath){let r=await Emt(e,n);if(r instanceof Vu){let i=(0,$be.createWriteStream)(e.downloadPath);Hbe.Readable.fromWeb(r.responseInternal.body).pipe(i),await(0,jbe.finished)(i)}else try{await(0,Gbe.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};pz=class{create(e,n,r){return new hz(e,n,r)}},hz=class{constructor(e,n,r){this.url=e,this.headers=n,this.callbacks=r}connect(){this.ws=new y3.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()}};yz=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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 s=Object.assign(Object.assign({},n),{preTunedModel:i});return s.baseModel=void 0,await this.tuneInternal(s)}else{let i=Object.assign({},n);return await this.tuneInternal(i)}else{let i=Object.assign({},n),s=await this.tuneMldevInternal(i),o="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?o=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(o=s.name.split("/operations/")[0]),{name:o,state:SO.JOB_STATE_QUEUED}}}}async getInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Mmt(e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>gz(u))}else{let l=Omt(e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Gmt(u))}}async listInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Dmt(e);return s=Ce("tuningJobs",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Lmt(c),u=new kO;return Object.assign(u,l),u})}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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Smt(e);return a=Ce("{name}:cancel",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=bmt(u),f=new ex;return Object.assign(f,d),f})}else{let l=wmt(e);return a=Ce("{name}:cancel",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=xmt(u),f=new ex;return Object.assign(f,d),f})}}async tuneInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Rmt(e,e);return s=Ce("tuningJobs",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>gz(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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Cmt(e);return s=Ce("tunedModels",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>Hmt(c))}}async validateReward(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=jmt(e);return s=Ce("{parent}/tuningJobs:validateReinforcementTuningReward",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Wmt(c),u=new PO;return Object.assign(u,l),u})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},SAe=1024*1024*8,xAe=3,bAe=1e3,TAe=2,qf="x-goog-upload-status";_z=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let r=await s1.stat(e);return n.size=r.size,n.type=this.inferMimeType(e),n}else return await Kmt(e)}async upload(e,n,r,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,r,i):Vmt(e,n,r,i)}async uploadToFileSearchStore(e,n,r,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,r,i):zmt(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 s;let o=await this.uploadFileFromPathInternal(e,n,r,i),a=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async uploadFileToFileSearchStoreFromPath(e,n,r,i){var s;let o=await this.uploadFileFromPathInternal(e,n,r,i),a=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=Sz(a),l=new ix;return Object.assign(l,c),l}async uploadFileFromPathInternal(e,n,r,i){var s,o,a;let c=n,l=i?.baseUrl||((s=r.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(l){let w=new URL(l),S=new URL(n);S.protocol=w.protocol,S.host=w.host,S.port=w.port,c=S.toString()}let u=0,d=0,f=new Vu(new Response),m="upload",g,y=Wbe.basename(e);try{if(g=await s1.open(e,"r"),!g)throw new Error("Failed to open file");for(u=(await g.stat()).size;d<u;){let w=Math.min(SAe,u-d);d+w>=u&&(m+=", finalize");let S=new Uint8Array(w),{bytesRead:T}=await g.read(S,0,w,d);if(T!==w)throw new Error(`Failed to read ${w} bytes from file at offset ${d}. bytes actually read: ${T}`);let R=new Blob([S]),C=0,D=bAe;for(;C<xAe;){let $=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(d),"X-Goog-Upload-File-Name":y});if(f=await r.request({path:"",body:R,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:c,headers:$})}),!((o=f?.headers)===null||o===void 0)&&o[qf])break;C++,await CAe(D),D=D*TAe}if(d+=T,((a=f?.headers)===null||a===void 0?void 0:a[qf])!=="active")break;if(u<=d)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return f}finally{g&&await g.close()}}};vz=class extends uTe{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||{},s=i.httpOptions||{},o=Object.assign({},s.headers||{});if(r)if(typeof r[Symbol.iterator]=="function")for(let[a,c]of r)o[a]=c;else for(let[a,c]of Object.entries(r))o[a]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},s),{headers:o})})})}};Ymt="gl-node/";Ez=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=ra(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 iz(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new oz(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 sz(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 az(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 lz(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 uz(this.apiClient),this._credentials)}constructor(e={}){var n,r,i,s;if(this.vertexai=Xmt(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let o=Jmt(),a=$f("GOOGLE_CLOUD_PROJECT"),c=$f("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:o,this.project=(r=e.project)!==null&&r!==void 0?r:a,this.location=(i=e.location)!==null&&i!==void 0?i:c,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((s=e.googleAuthOptions)===null||s===void 0)&&s.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!e.project&&!e.location&&(a||c)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&o?(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&&(a||c)&&o&&(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 l=Iat(e.httpOptions,this.vertexai,$f("GOOGLE_VERTEX_BASE_URL"),$f("GOOGLE_GEMINI_BASE_URL"));l&&(e.httpOptions?e.httpOptions.baseUrl=l:e.httpOptions={baseUrl:l}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let u=new dz({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new SV({auth:u,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:Ymt+process.version,uploader:new _z,downloader:new fz}),this.models=new _m(this.apiClient),this.live=new zO(this.apiClient,u,new pz),this.batches=new HO(this.apiClient),this.chats=new WO(this.models,this.apiClient),this.caches=new jO(this.apiClient),this.files=new vz(this.apiClient),this.operations=new YO(this.apiClient),this.authTokens=new XO(this.apiClient),this.tunings=new yz(this.apiClient),this.fileSearchStores=new AV(this.apiClient)}}});function LAe({provider:t,baseUrl:e,apiKey:n,model:r}={}){t&&Zmt.includes(t)&&(Nt.provider=t),e!==void 0&&(Nt.baseUrl=String(e||"").replace(/\/+$/,"")),n!==void 0&&(Nt.apiKey=String(n||"")),r&&(Nt.model=String(r))}function UAe(t={}){LAe(t),l1.info(`config \u2190 web: provider=${Nt.provider} baseUrl="${Nt.baseUrl}" model=${Nt.model} key=${Nt.apiKey?Nt.apiKey.slice(0,7)+"\u2026":"(none)"}`),u1.set(OAe,{...Nt}).catch(()=>{})}async function FAe(){if(kAe)return!0;kAe=!0;try{let t=await u1.get(OAe);t&&typeof t=="object"&&LAe(t),l1.info(`config \u2190 kv (restart restore): provider=${Nt.provider} baseUrl="${Nt.baseUrl}" model=${Nt.model} key=${Nt.apiKey?"kept":"(none)"}`)}catch{}return!0}function BAe(){return{...Nt,apiKey:void 0,ready:!!Nt.apiKey,busy:ux}}function ngt(t){if(!t||typeof t!="object")return null;if(t.role==="user"&&t.parts){let e=t.parts.filter(r=>typeof r?.text=="string"&&r.text).map(r=>r.text).join(""),n=t.parts.filter(r=>r?.functionResponse);return n.length?{role:"tool",results:n.map(r=>({name:r.functionResponse.name,output:r.functionResponse.response}))}:e?{role:"user",text:e}:null}if(t.role==="model"&&Array.isArray(t.parts)){let e=t.parts.filter(r=>typeof r?.text=="string"&&r.text).map(r=>r.text).join(""),n=t.parts.filter(r=>r?.functionCall).map((r,i)=>({id:`${r.functionCall.name}-${i}`,name:r.functionCall.name,args:r.functionCall.args||{}}));return{role:"assistant",text:e,calls:n}}return null}async function qAe(){if(ml)return ml;try{ml=await u1.get(PAe)||[]}catch{ml=[]}return Array.isArray(ml)||(ml=[]),ml=ml.map(t=>t&&!t.parts&&(t.role==="user"||t.role==="assistant"||t.role==="tool")?t:ngt(t)).filter(Boolean),ml}async function rgt(){try{await u1.set(PAe,ml.slice(-MAe))}catch{}}function kz(){return Kk().map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,parameters:n}))}function igt(t){return t.map(e=>e.role==="user"?{role:"user",parts:[{text:e.text}]}:e.role==="tool"?{role:"user",parts:e.results.map(n=>({functionResponse:{name:n.name,response:n.output}}))}:{role:"model",parts:[...e.text?[{text:e.text}]:[],...(e.calls||[]).map(n=>({functionCall:{name:n.name,args:n.args}}))]})}async function sgt(t){let{GoogleGenAI:e}=await Promise.resolve().then(()=>(IAe(),RAe)),i=(await new e({...Nt.baseUrl?{httpOptions:{baseUrl:Nt.baseUrl}}:{},apiKey:Nt.apiKey}).models.generateContent({model:Nt.model,contents:igt(t),config:{systemInstruction:Iz,tools:[{functionDeclarations:kz()}]}}))?.candidates?.[0]?.content?.parts||[];return{text:i.filter(s=>typeof s?.text=="string"&&s.text).map(s=>s.text).join(""),calls:i.filter(s=>s?.functionCall).map((s,o)=>({id:`${s.functionCall.name}-${o}`,name:s.functionCall.name,args:s.functionCall.args||{}}))}}function ogt(t){let e=[{role:"system",content:Iz}];for(let n of t)if(n.role==="user")e.push({role:"user",content:n.text});else if(n.role==="assistant")e.push({role:"assistant",content:n.text||null,...n.calls?.length?{tool_calls:n.calls.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.args||{})}}))}:{}});else if(n.role==="tool")for(let r of n.results)e.push({role:"tool",tool_call_id:r.callId||r.name,content:JSON.stringify(r.output)});return e}function agt(){let t="",e=[];return{push(n){typeof n?.content=="string"&&(t+=n.content);for(let r of n?.tool_calls||[]){let i=r.index??0;e[i]=e[i]||{id:"",name:"",args:""},r.id&&(e[i].id=r.id),r.function?.name&&(e[i].name+=r.function.name),typeof r.function?.arguments=="string"&&(e[i].args+=r.function.arguments)}},result(){return{text:t,calls:e.filter(Boolean).map(n=>({id:n.id,name:n.name,args:$Ae(n.args)}))}}}}async function cgt(t){let e=Nt.baseUrl||"https://openrouter.ai/api/v1",n=await fetch(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nt.apiKey}`},body:JSON.stringify({model:Nt.model,stream:!0,messages:ogt(t),tools:kz().map(c=>({type:"function",function:c}))}),signal:AbortSignal.timeout(DAe)});if(!n.ok){let c=await n.json().catch(()=>null);throw new Error(c?.error?.message||`HTTP ${n.status}`)}if(!(n.headers.get("content-type")||"").includes("text/event-stream")){let c=(await n.json())?.choices?.[0]?.message||{};return{text:typeof c.content=="string"?c.content:"",calls:(c.tool_calls||[]).map(l=>({id:l.id,name:l.function?.name||"",args:$Ae(l.function?.arguments)}))}}let i=agt(),s=n.body.getReader(),o=new TextDecoder,a="";for(;;){let{done:c,value:l}=await s.read();if(c)break;a+=o.decode(l,{stream:!0});let u;for(;(u=a.indexOf(`
528
+ `];for(;;){let{done:l,value:u}=yield Hn(i.read());if(l){if(o.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let d=s.decode(u,{stream:!0});try{let g=JSON.parse(d);if("error"in g){let y=JSON.parse(JSON.stringify(g.error)),w=y.status,S=y.code,T=`got status: ${w}. ${JSON.stringify(g)}`;if(S>=400&&S<600)throw new sx({message:T,status:S})}}catch(g){if(g.name==="ApiError")throw g}o+=d;let f=-1,m=0;for(;;){f=-1,m=0;for(let w of c){let S=o.indexOf(w);S!==-1&&(f===-1||S<f)&&(f=S,m=w.length)}if(f===-1)break;let g=o.substring(0,f);o=o.substring(f+m);let y=g.trim();if(y.startsWith(a)){let w=y.substring(a.length).trim();try{let S=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield Hn(new Vu(S))}catch(S){throw new Error(`exception parsing stream chunk ${w}. ${S}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n,r,i,s,o){var a,c,l,u,d,f;let m=o??fetch,g=(a=r?.httpStatusCodes)!==null&&a!==void 0?a:zft,y=async()=>{let R=$ft(i,s),C;try{C=await m(e,Object.assign(Object.assign({},n),{signal:R.signal}))}catch(D){throw R.dispose(),D}if(!r||C.ok||!g.includes(C.status))return C;try{await _W(C)}finally{R.dispose()}return C};if(!r)return y();let w=Math.max(1,(c=r.attempts)!==null&&c!==void 0?c:Gft),S=Math.round(((l=r.initialDelay)!==null&&l!==void 0?l:Hft)*1e3),T=Math.max(S,Math.round(((u=r.maxDelay)!==null&&u!==void 0?u:jft)*1e3));return(0,Bbe.default)(y,{retries:w-1,factor:(d=r.expBase)!==null&&d!==void 0?d:Wft,minTimeout:S,maxTimeout:T,randomize:((f=r.jitter)!==null&&f!==void 0?f:Vft)>0,onFailedAttempt:R=>{var C;if(s?.aborted)throw(C=R.error)!==null&&C!==void 0?C:R}})}getDefaultHeaders(){let e={},n=Lft+" "+this.clientOptions.userAgentExtra;return e[Nft]=n,e[wV]=n,e[Oft]="application/json",e}async getHeadersInternal(e,n){let r=new Headers;if(e&&e.headers)for(let[i,s]of Object.entries(e.headers))r.append(i,s);return e?.timeout&&e.timeout>0&&r.append(Mft,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 s=this.clientOptions.uploader,o=await s.stat(e);i.sizeBytes=String(o.size);let a=(r=n?.mimeType)!==null&&r!==void 0?r:o.type;if(a===void 0||a==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=a;let c={file:i},l=this.getFileName(e),u=Ce("upload/v1beta/files",c._url),d=await this.fetchUploadUrl(u,i.sizeBytes,i.mimeType,l,c,n?.httpOptions);return s.upload(e,d,this)}async uploadFileToFileSearchStore(e,n,r){var i;let s=this.clientOptions.uploader,o=await s.stat(n),a=String(o.size),c=(i=r?.mimeType)!==null&&i!==void 0?i:o.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(n),d={};r!=null&&ETe(r,d);let f=await this.fetchUploadUrl(l,a,c,u,d,r?.httpOptions);return s.uploadToFileSearchStore(n,f,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,r,i,s,o){var a;let c={};o?c=o:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`},i?{"X-Goog-Upload-File-Name":i}:{})};let l=await this.request({path:e,body:JSON.stringify(s),httpMethod:"POST",httpOptions:c});if(!l||!l?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=(a=l?.headers)===null||a===void 0?void 0:a["x-goog-upload-url"];if(u===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}};Yft="mcp_used/unknown",wTe=!1;ox=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 s={},o=[];for(let u of this.mcpClients)try{for(var a=!0,c=(n=void 0,VS(Jft(u))),l;l=await c.next(),e=l.done,!e;a=!0){i=l.value,a=!1;let d=i;o.push(d);let f=d.name;if(s[f])throw new Error(`Duplicate function name ${f} found in MCP tools. Please ensure function names are unique.`);s[f]=u}}catch(d){n={error:d}}finally{try{!a&&!e&&(r=c.return)&&await r.call(c)}finally{if(n)throw n.error}}this.mcpTools=o,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),oct(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],s;this.config.timeout&&(s={timeout:this.config.timeout});let o=await i.callTool({name:r.name,arguments:r.args},void 0,s);n.push({functionResponse:{name:r.name,response:o.isError?{error:o}:o}})}return n}};xV=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(),s=this.apiClient.getApiVersion(),o=npt(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),c=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`,l=()=>{},u=new Promise(R=>{l=R}),d=e.callbacks,f=function(){l({})},m=this.apiClient,g={onopen:f,onmessage:R=>{ept(m,d.onmessage,R)},onerror:(n=d?.onerror)!==null&&n!==void 0?n:function(R){},onclose:(r=d?.onclose)!==null&&r!==void 0?r:function(R){}},y=this.webSocketFactory.create(c,tpt(o),g);y.connect(),await u;let T={setup:{model:Kt(this.apiClient,e.model)}};return y.send(JSON.stringify(T)),new bV(y,this.apiClient)}},bV=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=uut(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=lut(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(gm.PLAY)}pause(){this.sendPlaybackControl(gm.PAUSE)}stop(){this.sendPlaybackControl(gm.STOP)}resetContext(){this.sendPlaybackControl(gm.RESET_CONTEXT)}close(){this.conn.close()}};rpt="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";zO=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r,this.music=new xV(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,r,i,s,o,a;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let c=this.apiClient.getWebsocketBaseUrl(),l=this.apiClient.getApiVersion(),u,d=this.apiClient.getHeaders();e.config&&e.config.tools&&STe(e.config.tools)&&xTe(d);let f=apt(d);if(this.apiClient.isVertexAI()){let I=this.apiClient.getProject(),P=this.apiClient.getLocation(),F=this.apiClient.getApiKey(),X=!!I&&!!P||!!F;this.apiClient.getCustomBaseUrl()&&!X?u=c:(u=`${c}/ws/google.cloud.aiplatform.${l}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u))}else{let I=this.apiClient.getApiKey(),P="BidiGenerateContent",F="key";I?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),l!=="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."),P="BidiGenerateContentConstrained",F="access_token"),u=`${c}/ws/google.ai.generativelanguage.${l}.GenerativeService.${P}?${F}=${I}`}let m=()=>{},g=new Promise(I=>{m=I}),y=e.callbacks,w=function(){var I;(I=y?.onopen)===null||I===void 0||I.call(y),m({})},S=this.apiClient,T=!1,R=[],C=()=>{},D=new Promise(I=>{C=I}),$={onopen:w,onmessage:I=>{ipt(S,P=>{P.setupComplete&&!M.setupComplete&&(M.setupComplete=P.setupComplete,C({})),T?y.onmessage(P):R.push(P)},I)},onerror:(n=y?.onerror)!==null&&n!==void 0?n:function(I){},onclose:(r=y?.onclose)!==null&&r!==void 0?r:function(I){}},G=this.webSocketFactory.create(u,opt(f),$);G.connect(),await g;let V=Kt(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&V.startsWith("publishers/")){let I=this.apiClient.getProject(),P=this.apiClient.getLocation();I&&P&&(V=`projects/${I}/locations/${P}/`+V)}let L={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[zS.AUDIO]}:e.config.responseModalities=[zS.AUDIO]),!((s=e.config)===null||s===void 0)&&s.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let k=(a=(o=e.config)===null||o===void 0?void 0:o.tools)!==null&&a!==void 0?a:[],E=[];for(let I of k)if(this.isCallableTool(I)){let P=I;E.push(await P.tool())}else E.push(I);E.length>0&&(e.config.tools=E);let A={model:V,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?L=cut(this.apiClient,A):L=aut(this.apiClient,A),delete L.config;let M=new KO(G,this.apiClient);G.send(JSON.stringify(L)),await D,T=!0;for(let I of R)y.onmessage(I);return M}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},spt={turnComplete:!0},KO=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=gs(n.turns),e.isVertexAI()||(r=r.map(i=>lx(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 s of r){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(rpt)}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},spt),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:fut(e)}:n={realtimeInput:dut(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};_be=10;_m=class t extends ic{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=gs(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=gs(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let s=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:KS.EMBED_CONTENT});return await this.embedContentInternal(s)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:KS.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var r,i,s,o,a;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!cpt(n)||vbe(n.config))return await this.generateContentInternal(c);let l=Ebe(n);if(l.length>0){let y=l.map(w=>`tools[${w}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${y}.`)}let u,d,f=gs(c.contents),m=(s=(i=(r=c.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&s!==void 0?s:_be,g=0;for(;g<m&&(u=await this.generateContentInternal(c),!(!u.functionCalls||u.functionCalls.length===0));){let y=u.candidates[0].content,w=[];for(let S of(a=(o=n.config)===null||o===void 0?void 0:o.tools)!==null&&a!==void 0?a:[])if(hv(S)){let R=await S.callTool(u.functionCalls);w.push(...R)}g++,d={role:"user",parts:w},c.contents=gs(c.contents),c.contents.push(y),c.contents.push(d),wbe(c.config)&&(f.push(y),f.push(d))}return wbe(c.config)&&(u.automaticFunctionCallingHistory=f),u},this.generateContentStream=async n=>{var r,i,s,o,a;if(this.maybeMoveToResponseJsonSchema(n),vbe(n.config)){let d=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(d)}let c=Ebe(n);if(c.length>0){let d=c.map(f=>`tools[${f}]`).join(", ");throw new Error(`Incompatible tools found at ${d}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let l=(s=(i=(r=n?.config)===null||r===void 0?void 0:r.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,u=(a=(o=n?.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||a===void 0?void 0:a.disable;if(l&&!u)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 s,o=[];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"?s=c?.safetyAttributes:o.push(c);let a;return s?a={generatedImages:o,positivePromptSafetyAttributes:s,sdkHttpResponse:r.sdkHttpResponse}:a={generatedImages:o,sdkHttpResponse:r.sdkHttpResponse},a})),this.list=async n=>{var r;let o={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!o.config.queryBase){if(!((r=o.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.");o.config.filter="labels.tune-type:*"}return new hl(pl.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(o),o)},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,s,o,a,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}:!((o=(s=n.source)===null||s===void 0?void 0:s.video)===null||o===void 0)&&o.uri&&(!((c=(a=n.source)===null||a===void 0?void 0:a.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchema(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,r,i;let s=(n=e.config)===null||n===void 0?void 0:n.tools;if(!s)return e;let o=await Promise.all(s.map(async c=>hv(c)?await c.tool():c)),a={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:o})};if(a.config.tools=o,e.config&&e.config.tools&&STe(e.config.tools)){let c=(i=(r=e.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&i!==void 0?i:{},l=Object.assign({},c);Object.keys(l).length===0&&(l=this.apiClient.getDefaultHeaders()),xTe(l),a.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:l})}return a}async initAfcToolsMap(e){var n,r,i;let s=new Map;for(let o of(r=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&r!==void 0?r:[])if(hv(o)){let a=o,c=await a.tool();for(let l of(i=c.functionDeclarations)!==null&&i!==void 0?i:[]){if(!l.name)throw new Error("Function declaration name is required.");if(s.has(l.name))throw new Error(`Duplicate tool declaration name: ${l.name}`);s.set(l.name,a)}}return s}async processAfcStream(e){var n,r,i;let s=(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:_be,o=!1,a=0,c=await this.initAfcToolsMap(e);return(function(l,u,d){return pv(this,arguments,function*(){for(var f,m,g,y,w,S;a<s;){o&&(a++,o=!1);let D=yield Hn(l.processParamsMaybeAddMcpUsage(d)),$=yield Hn(l.generateContentStreamInternal(D)),G=[],V=[];try{for(var T=!0,R=(m=void 0,VS($)),C;C=yield Hn(R.next()),f=C.done,!f;T=!0){y=C.value,T=!1;let L=y;if(yield yield Hn(L),L.candidates&&(!((w=L.candidates[0])===null||w===void 0)&&w.content)){V.push(L.candidates[0].content);for(let k of(S=L.candidates[0].content.parts)!==null&&S!==void 0?S:[])if(a<s&&k.functionCall){if(!k.functionCall.name)throw new Error("Function call name was not returned by the model.");if(u.has(k.functionCall.name)){let E=yield Hn(u.get(k.functionCall.name).callTool([k.functionCall]));G.push(...E)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${u.keys()}, missing tool: ${k.functionCall.name}`)}}}}catch(L){m={error:L}}finally{try{!T&&!f&&(g=R.return)&&(yield Hn(g.call(R)))}finally{if(m)throw m.error}}if(G.length>0){o=!0;let L=new Bf;L.candidates=[{content:{role:"user",parts:G}}],yield yield Hn(L);let k=[];k.push(...V),k.push({role:"user",parts:G});let E=gs(d.contents).concat(k);d.contents=E}else break}})})(this,c,e)}async generateContentInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mbe(this.apiClient,e);return a=Ce("{model}:generateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=ybe(u),f=new Bf;return Object.assign(f,d),f})}else{let l=hbe(this.apiClient,e);return a=Ce("{model}:generateContent",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=gbe(u),f=new Bf;return Object.assign(f,d),f})}}async generateContentStreamInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mbe(this.apiClient,e);return a=Ce("{model}:streamGenerateContent?alt=sse",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.requestStream({path:a,queryParams:c,body:JSON.stringify(l),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}),o.then(function(d){return pv(this,arguments,function*(){var f,m,g,y;try{for(var w=!0,S=VS(d),T;T=yield Hn(S.next()),f=T.done,!f;w=!0){y=T.value,w=!1;let R=y,C=ybe(yield Hn(R.json()),e);C.sdkHttpResponse={headers:R.headers};let D=new Bf;Object.assign(D,C),yield yield Hn(D)}}catch(R){m={error:R}}finally{try{!w&&!f&&(g=S.return)&&(yield Hn(g.call(S)))}finally{if(m)throw m.error}}})})}else{let l=hbe(this.apiClient,e);return a=Ce("{model}:streamGenerateContent?alt=sse",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.requestStream({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),o.then(function(d){return pv(this,arguments,function*(){var f,m,g,y;try{for(var w=!0,S=VS(d),T;T=yield Hn(S.next()),f=T.done,!f;w=!0){y=T.value,w=!1;let R=y,C=gbe(yield Hn(R.json()),e);C.sdkHttpResponse={headers:R.headers};let D=new Bf;Object.assign(D,C),yield yield Hn(D)}}catch(R){m={error:R}}finally{try{!w&&!f&&(g=S.return)&&(yield Hn(g.call(S)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Qut(this.apiClient,e,e),u=cct(e.model)?"{model}:embedContent":"{model}:predict";return a=Ce(u,l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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().then(f=>{let m=f;return m.sdkHttpResponse={headers:d.headers},m})),o.then(d=>{let f=edt(d,e),m=new YS;return Object.assign(m,f),m})}else{let l=Jut(this.apiClient,e);return a=Ce("{model}:batchEmbedContents",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Zut(u),f=new YS;return Object.assign(f,d),f})}}async generateImagesInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=cdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=ldt(c),u=new bO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=zut(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Kut(c),u=new TO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=dft(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=fft(c),u=new AO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=Hdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=jdt(c),u=new CO;return Object.assign(u,l),u})}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,s="",o={};if(this.apiClient.isVertexAI()){let a=Jdt(this.apiClient,e);return s=Ce("{model}:predict",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Qdt(c),u=new RO;return Object.assign(u,l),u})}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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Tdt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>EV(u))}else{let l=bdt(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>vV(u))}}async listInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Mdt(this.apiClient,e);return a=Ce("{models_url}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Ddt(u),f=new XS;return Object.assign(f,d),f})}else{let l=Odt(this.apiClient,e);return a=Ce("{models_url}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Ndt(u),f=new XS;return Object.assign(f,d),f})}}async update(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=lft(this.apiClient,e);return a=Ce("{model}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>EV(u))}else{let l=cft(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>vV(u))}}async delete(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Hut(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=Wut(u),f=new JS;return Object.assign(f,d),f})}else{let l=Gut(this.apiClient,e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=jut(u),f=new JS;return Object.assign(f,d),f})}}async countTokens(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=But(this.apiClient,e);return a=Ce("{model}:countTokens",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=$ut(u),f=new QS;return Object.assign(f,d),f})}else{let l=Fut(this.apiClient,e);return a=Ce("{model}:countTokens",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=qut(u),f=new QS;return Object.assign(f,d),f})}}async computeTokens(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=kut(this.apiClient,e);return s=Ce("{model}:computeTokens",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Put(c),u=new IO;return Object.assign(u,l),u})}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,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=mdt(this.apiClient,e);return a=Ce("{model}:predictLongRunning",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o.then(u=>{let d=pdt(u),f=new ZS;return Object.assign(f,d),f})}else{let l=hdt(this.apiClient,e);return a=Ce("{model}:predictLongRunning",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o.then(u=>{let d=fdt(u),f=new ZS;return Object.assign(f,d),f})}}};_m.loggedGenerateImagesWarning=!1;_m.loggedEditImageWarning=!1;_m.loggedGenerateVideosWarning=!1;YO=class extends ic{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],s;r&&"httpOptions"in r&&(s=r.httpOptions);let o=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:o,_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],s;r&&"httpOptions"in r&&(s=r.httpOptions);let o=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:o,_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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Bat(e);return a=Ce("{operationName}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json()),o}else{let l=Fat(e);return a=Ce("{operationName}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json()),o}}async fetchPredictVideosOperationInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Pat(e);return s=Ce("{resourceName}:fetchPredictOperation",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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).")}};XO=class extends ic{constructor(e){super(),this.apiClient=e}async create(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let a=ppt(this.apiClient,e);s=Ce("auth_tokens",a._url),o=a._query,delete a.config,delete a._url,delete a._query;let c=Tpt(a,e.config);return i=this.apiClient.request({path:s,queryParams:o,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(l=>l.json()),i.then(l=>l)}}};TV=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async n=>new hl(pl.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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Rpt(e);return s=Ce("{name}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let o=Cpt(e);i=Ce("{name}",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(o),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=kpt(e);return s=Ce("{parent}/documents",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ppt(c),u=new OO;return Object.assign(u,l),u})}}};AV=class extends ic{constructor(e,n=new TV(e)){super(),this.apiClient=e,this.documents=n,this.list=async(r={})=>new hl(pl.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 s={};r.searchParams.forEach((c,l)=>{s[l]=c}),s.alt="media";let o=Object.assign({},n?.httpOptions),a=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:s,httpOptions:o});if(a instanceof Vu){let c=await a.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=vft(this.apiClient,e);return s=Ce("fileSearchStores",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Sft(e);return s=Ce("{name}",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let o=wft(e);i=Ce("{name}",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(o),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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Rft(e);return s=Ce("fileSearchStores",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Ift(c),u=new MO;return Object.assign(u,l),u})}}async uploadToFileSearchStoreInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=kft(e);return s=Ce("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=Pft(c),u=new NO;return Object.assign(u,l),u})}}async importFile(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Tft(e);return s=Ce("{file_search_store_name}:importFile",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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 l=bft(c),u=new DO;return Object.assign(u,l),u})}}};CV=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return Upt(await this.options.getAuthHeaders(e))}},RV=class{beforeCreateRequest(e,n){return Object.assign(Object.assign({},n),{url:Npt(n.url)})}async beforeRequest(e,n){if(xbe(n.headers,Lpt(e.security_source)),Fpt(e,n.headers),qpt(n.headers))return n;let r=await Dpt(e.security_source,n.url);return xbe(n.headers,r?.default_headers),Bpt(n.headers,r),n}};Gf=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)}},JO=class extends Gf{constructor(){super(...arguments),this.name="UnexpectedClientError"}},dv=class extends Gf{constructor(){super(...arguments),this.name="InvalidRequestError"}},QO=class extends Gf{constructor(){super(...arguments),this.name="RequestAbortedError"}},ZO=class extends Gf{constructor(){super(...arguments),this.name="RequestTimeoutError"}},e1=class extends Gf{constructor(){super(...arguments),this.name="ConnectionError"}};na=class extends Error{constructor(e,n){var r,i,s,o;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=(s=n?.response)===null||s===void 0?void 0:s.headers,this.contentType=((o=n?.response)===null||o===void 0?void 0:o.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError"}};IV=class extends Error{},ys=class t extends IV{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=Tbe(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 s=n&&Wpt(n)&&typeof n.message=="string"?n.message:void 0,o=Tbe(n),a=(i=s??r)!==null&&i!==void 0?i:o||"An error occurred";return`${e?`${e} `:""}${a}`}static generate(e,n,r,i){return!e||!i?new mv({message:r,cause:n instanceof Error?n:void 0}):e===400?new OV(e,n,r,i):e===401?new MV(e,n,r,i):e===403?new NV(e,n,r,i):e===404?new DV(e,n,r,i):e===409?new LV(e,n,r,i):e===422?new UV(e,n,r,i):e===429?new FV(e,n,r,i):e>=500?new BV(e,n,r,i):new t(e,n,r,i)}},kV=class extends ys{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},mv=class extends ys{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},PV=class extends mv{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."})}},OV=class extends ys{},MV=class extends ys{},NV=class extends ys{},DV=class extends ys{},LV=class extends ys{},UV=class extends ys{},FV=class extends ys{},BV=class extends ys{};zpt=(t,e)=>e==null?fetch(t):fetch(t,e),t1=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||zpt}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}},Abe=/\s*;\s*/g;Kpt=new RegExp("^[0-9]xx$","i");n1=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);Jpt(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,s=r;for(let o of this.afterErrorHooks){let a=await o.afterError(e,i,s);i=a.response,s=a.error}return{response:i,error:s}}};eht=Object.prototype.hasOwnProperty;Rbe=["https://generativelanguage.googleapis.com"];nht={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};sht=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;kTe=oht(",");De=(t,e,n)=>{let r="",i=n?.explode?PTe(t,e):[[t,e]];if(i.every(([a,c])=>c==null))return;let s=a=>c1(a,n?.charEncoding),o=a=>s(OTe(a));return i.forEach(([a,c])=>{var l;let u="";if(c!=null){if(Array.isArray(c))u=(l=NTe(c,d=>`${o(d)}`))===null||l===void 0?void 0:l.join(",");else if(Hf(c)){let d=DTe(Object.entries(c),([f,m])=>`,${s(f)},${o(m)}`);u=d?.join("").slice(1)}else u=`${n?.explode&&Hf(e)?`${a}=`:""}${o(c)}`;r+=u?`,${u}`:""}}),r.slice(1)};cc=cht(kTe);Ibe={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},cx=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)}},jf=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};uht=new RegExp("^[0-9]xx$","i");yO=typeof globalThis>"u"?null:globalThis,hht=typeof yO=="object"&&yO!=null&&"importScripts"in yO&&typeof yO.importScripts=="function",mht=hht||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",sc=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof n1?this._hooks=n.hooks:this._hooks=new n1;let r=new t1;e.http_client=e.http_client||r,e=this._hooks.sdkInit(e);let i=tht(e);i&&(i.pathname=i.pathname.replace(/\/+$/,"")+"/"),this._baseURL=i,this._httpClient=e.http_client||r,this._options=Object.assign(Object.assign({},Mpt(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&ax().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,r){var i,s,o,a,c;let{method:l,path:u,query:d,headers:f,security:m}=n,g=(i=n.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!g)return ju(new dv("No base URL provided for operation"));let y=new URL(g),w;u?(y.pathname=y.pathname.replace(/\/+$/,"")+"/",w=new URL(u,y),!w.search&&y.search&&(w.search=y.search)):w=y,w.hash="";let S=(I,P)=>{if(!P)return I;let F=new Set(P.split("&").filter(N=>N!=="").map(N=>{var b;return(b=N.split("=")[0])!==null&&b!==void 0?b:""}));return[...I.split("&").filter(N=>{var b;return N!==""&&!F.has((b=N.split("=")[0])!==null&&b!==void 0?b:"")}),P].join("&")},T=I=>Object.entries(I).map(([P,F])=>{if(F==null)return;let X=Hf(F)?JSON.stringify(F):F;return kTe(P,X,{explode:Array.isArray(X),charEncoding:"percent"})}).filter(P=>typeof P<"u").join("&"),R=[d||"",T(r?.extra_query||{}),T(m?.queryParams||{})].reduce(S,w.search.slice(1));R&&(w.search=`?${R}`);let C=new Headers(f),D=m?.basic.username,$=m?.basic.password;if(D!=null||$!=null){let I=Zpt([D||"",$||""].join(":"));C.set("Authorization",`Basic ${I}`)}let G=new Headers(m?.headers||{});for(let[I,P]of G)C.set(I,P);let V=C.get("cookie")||"";for(let[I,P]of Object.entries(m?.cookies||{}))V+=`; ${I}=${P}`;V=V.startsWith("; ")?V.slice(2):V,C.set("cookie",V);let L=new Headers((s=r?.headers)!==null&&s!==void 0?s:(o=r?.fetch_options)===null||o===void 0?void 0:o.headers);for(let[I,P]of L)C.set(I,P);mht||C.set((a=n.uaHeader)!==null&&a!==void 0?a:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:nht.userAgent);let k=n.body,E=Object.fromEntries(Object.entries(r?.extra_body||{}).filter(([,I])=>typeof I<"u"));if(Object.keys(E).length>0){let I=new Headers(f).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(I)||typeof k!="string"&&k!=null)return ju(new dv("extra_body can only be merged into JSON object request bodies"));let F;try{F=k?JSON.parse(k):{}}catch(X){return ju(new dv("extra_body can only be merged into JSON object request bodies",{cause:X}))}if(!Hf(F))return ju(new dv("extra_body can only be merged into JSON object request bodies"));k=JSON.stringify(Object.assign(Object.assign({},F),E)),C.delete("content-length")}let A=Object.assign(Object.assign({},r?.fetch_options),r);!A?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign(A,{duplex:"half"});let M;try{M=this._hooks.beforeCreateRequest(e,{url:w,options:Object.assign(Object.assign({},A),{body:k??null,headers:C,method:l})})}catch(I){return ju(new JO("Create request hook failed to execute",{cause:I}))}return Cbe(new Request(M.url,M.options))}async _do(e,n){let{context:r,isErrorStatusCode:i}=n,s=r.timeout_ms;return lht(async()=>{var o;let a=e.clone(),c=a;if(s!=null&&s>0){let d=AbortSignal.timeout(s),f=(o=rht(a.signal,d))!==null&&o!==void 0?o:d;c=new Request(a,{signal:f})}let l=await this._hooks.beforeRequest(r,c);await ght(this._logger,l).catch(d=>{var f;return(f=this._logger)===null||f===void 0?void 0:f.log("Failed to log request:",d)});let u=await this._httpClient.request(l);try{if(i(u.status)){let d=await this._hooks.afterError(r,u,null);if(d.error)throw d.error;u=d.response||u}else u=await this._hooks.afterSuccess(r,u)}finally{await yht(this._logger,u,l).catch(d=>{var f;return(f=this._logger)===null||f===void 0?void 0:f.log("Failed to log response:",d)})}return u},{config:n.retryConfig,statusCodes:n.retryCodes}).then(o=>Cbe(o),o=>{switch(!0){case Xpt(o):return ju(new QO("Request aborted by client",{cause:o}));case RTe(o):return ju(new ZO("Request timed out",{cause:o}));case CTe(o):return ju(new e1("Unable to make request",{cause:o}));default:return ju(new JO("Unexpected HTTP client error",{cause:o}))}})}},FTe=/^(application|text)\/([^+]+\+)*json.*/,Pbe=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;r1=class extends na{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?`
529
+ `:". ";let s=i;if(i.length>1e4){let o=i.substring(0,1e4),a=i.length-1e4;s=`${o}...and ${a} more chars`}e+=`Body: ${s}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError"}};qV=class extends ReadableStream{constructor(e,n,r){var i;let s=e.getReader(),o=new Uint8Array(4096),a=0,c=0,l={eventId:void 0},u=(i=r?.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(d){try{for(;;){let f=Eht(o,a,c);if(!f){c=Math.max(0,a-vht+1);let y=await s.read();if(y.done)return d.close();if(a+y.value.length>o.length){let w=new Uint8Array(Math.max(o.length*2,a+y.value.length));w.set(o.subarray(0,a)),o=w}o.set(y.value,a),a+=y.value.length;continue}let m=o.slice(0,f.index);if(o.copyWithin(0,f.index+f.length,a),a-=f.index+f.length,o.length>4096&&a<=o.length>>2){let y=new Uint8Array(Math.max(4096,a*2));y.set(o.subarray(0,a)),o=y}c=0;let g=wht(m,n,l,u);if(g&&!g.done)return d.enqueue(g.value);if(g?.done)return await s.cancel("done"),d.close()}}catch(f){d.error(f),await s.cancel(f)}},cancel:d=>s.cancel(d)})}[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 o=await r.read();return o.done?(r.releaseLock(),{done:!0,value:void 0}):{done:!1,value:o.value}},throw:async o=>(await r.cancel(o),r.releaseLock(),{done:!0,value:void 0}),return:async()=>(await r.cancel("done"),r.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},s=Symbol.asyncDispose;return s&&(i[s]=async()=>{var o;await((o=i.return)===null||o===void 0?void 0:o.call(i))}),i}values(e){return this[Symbol.asyncIterator](e)}},ea=13,ta=10,BTe=[[ea,ta,ea,ta],[ea,ta,ea],[ea,ta,ta],[ea,ea,ta],[ta,ea,ta],[ea,ea],[ta,ea],[ta,ta]],vht=BTe.reduce((t,e)=>Math.max(t,e.length),0);Sht={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};xht=/, */;Mbe={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},$V=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(Mbe.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(Mbe.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};At=class t{constructor(e,n){this[GTe]="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,s])=>[e(i),s]);return r.catch(()=>{}),new t(r,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};GTe=Symbol.toStringTag;GV=class extends sc{list(e,n){return qt(VTe(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(HTe(this,i,r,n))}delete(e,n,r){return qt(jTe(this,e,n?.api_version,r))}get(e,n,r){return qt(WTe(this,e,n?.api_version,r))}};HV=class extends sc{list(e,n){return qt(XTe(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(zTe(this,i,r,n))}delete(e,n,r){return qt(KTe(this,e,n?.api_version,r))}get(e,n,r){return qt(YTe(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i,update_mask:s}=n,o=Cr(n,["api_version","update_mask"]);return qt(JTe(this,e,o,i,s,r))}};jV=class extends sc{list(e,n,r,i){return qt(nAe(this,e,n,r?.api_version,r?.page_size,r?.page_token,r?.recursive,i))}};WV=class extends sc{startUpload(e,n,r,i){return qt(rAe(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))}};VV=class extends sc{get internal(){var e;return(e=this._internal)!==null&&e!==void 0?e:this._internal=new WV(this._options)}get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new jV(this._options)}listEnvironments(e,n){return qt(tAe(this,e?.api_version,e?.page_size,e?.page_token,n))}createEnvironment(e,n,r){return qt(QTe(this,e,n,r))}deleteEnvironment(e,n,r){return qt(ZTe(this,e,n?.api_version,r))}getEnvironment(e,n,r){return qt(eAe(this,e,n?.api_version,r))}};zV=class extends na{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"}},KV=class extends na{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"}};YV=class extends na{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"}},XV=class extends na{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"}};JV=class extends na{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"}},QV=class extends na{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"}};ZV=class extends na{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"}},ez=class extends na{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"}};tz=class extends sc{create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(sAe(this,i,r,n))}delete(e,n,r){return qt(jht(this,e,n?.api_version,r))}get(e,n,r){return qt(oAe(this,e,n?.api_version,n?.include_input,n?.last_event_id,n?.stream,r))}cancel(e,n,r){return qt(iAe(this,e,n?.api_version,r))}};nz=class extends sc{list(e,n){return qt(dAe(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(aAe(this,i,r,n))}delete(e,n,r){return qt(cAe(this,e,n?.api_version,r))}get(e,n,r){return qt(lAe(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i}=n,s=Cr(n,["api_version"]);return qt(pAe(this,e,s,i,r))}listExecutions(e,n,r){return qt(uAe(this,e,n?.api_version,n?.page_size,n?.page_token,r))}run(e,n,r){return qt(fAe(this,e,n?.api_version,r))}};rz=class extends sc{list(e,n){return qt(yAe(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return qt(hAe(this,i,r,n))}delete(e,n,r){return qt(mAe(this,e,n?.api_version,r))}get(e,n,r){return qt(gAe(this,e,n?.api_version,r))}update(e,n,r){let i=n??{},{api_version:s,update_mask:o}=i,a=Cr(i,["api_version","update_mask"]),c=n===void 0||Object.keys(a).length===0?void 0:a;return qt(EAe(this,e,s,o,c,r))}ping(e,n,r,i){return qt(_Ae(this,e,n,r,i))}rotateSigningSecret(e,n,r,i){return qt(vAe(this,e,n,r,i))}};amt=class extends sc{get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new VV(this._options)}get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new GV(this._options)}get credentials(){var e;return(e=this._credentials)!==null&&e!==void 0?e:this._credentials=new HV(this._options)}get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new tz(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new nz(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new rz(this._options)}};cmt=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);iz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);if(i.stream===!0){let o=await vW(()=>this.getClient(r).interactions.create(Object.assign(Object.assign({},i),{stream:!0,api_version:r}),It(n,!0)));return Dbe(o)}let s=await en(sAe(this.getClient(r),i,r,It(n)));return EW(s)}async get(e,n={},r){let{api_version:i,stream:s=!1,last_event_id:o,include_input:a}=n??{};if(s===!0){let l=await vW(()=>this.getClient(i).interactions.get(e,{stream:s,last_event_id:o,include_input:a,api_version:i},It(r,!0)));return Dbe(l)}let c=await en(oAe(this.getClient(i),e,i,a,o,s,It(r)));return EW(c)}async delete(e,n={},r){return vW(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},It(r)))}async cancel(e,n={},r){return EW(await en(iAe(this.getClient(n?.api_version),e,n?.api_version,It(r))))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},sz=class{constructor(e){this.parentClient=e}async create(e={},n){let r=e??{},{api_version:i}=r,s=Cr(r,["api_version"]);return en(HTe(this.getClient(i),s,i,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s,parent:o}=e??{};return en(VTe(this.getClient(r),r,i,s,o,It(n)))}async get(e,n={},r){return en(WTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async delete(e,n={},r){return en(jTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},oz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(hAe(this.getClient(),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(yAe(this.getClient(),r,i,s,It(n)))}async get(e,n={},r){return en(gAe(this.getClient(),e,n?.api_version,It(r)))}async update(e,n={},r){let i=n??{},{api_version:s,update_mask:o}=i,a=Cr(i,["api_version","update_mask"]);return en(EAe(this.getClient(),e,s,o,a,It(r)))}async delete(e,n={},r){return en(mAe(this.getClient(),e,n?.api_version,It(r)))}async rotateSigningSecret(e,n={},r){let i=n??{},{api_version:s}=i,o=Cr(i,["api_version"]);return en(vAe(this.getClient(),e,s,o,It(r)))}async ping(e,n=void 0,r){let{api_version:i,body:s}=n??{};return en(_Ae(this.getClient(),e,i,s,It(r)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=ra(this.parentClient)),this.sdk}},az=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(aAe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,filter:i,page_size:s,page_token:o}=e??{};return en(dAe(this.getClient(r),r,i,s,o,It(n)))}async get(e,n={},r){return en(lAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async update(e,n,r){let{api_version:i}=n,s=Cr(n,["api_version"]);return en(pAe(this.getClient(i),e,s,i,It(r)))}async delete(e,n={},r){return en(cAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async run(e,n={},r){return en(fAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async listExecutions(e,n={},r){let{api_version:i,page_size:s,page_token:o}=n??{};return en(uAe(this.getClient(i),e,i,s,o,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}};cz=class{constructor(e,n){this.resolveClient=e,this.parentClient=n}async list(e,n){return en(nAe(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,It(n)))}async download(e,n){var r,i;let s=e.environment;if(!s)throw new Error("environment is required.");let o=s.startsWith("environments/")?s:`environments/${s}`,a=e.path.replace(/^\/+/,""),c=`${o}/files/${a}`,l=this.parentClient;if(!l||typeof l.request!="function")throw new Error("apiClient is required to download files.");let u=await l.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(u&&u.responseInternal&&typeof u.responseInternal.arrayBuffer=="function"){let d=await u.responseInternal.arrayBuffer();return new Uint8Array(d)}throw new Error("Unexpected response type from download")}async upload(e,n){var r,i,s,o,a,c,l,u;let d=e.environment;if(!d)throw new Error("environment is required.");d.startsWith("environments/")||`${d}`;let f=e.path.replace(/^\/+/,""),m=this.parentClient;if(!m||typeof m.request!="function")throw new Error("apiClient is required to upload files.");let g,y=0,w=e.mime_type;if(typeof e.file=="string"){let k;try{let E=globalThis.require;E&&(k=E("fs").readFileSync(e.file))}catch{}if(!k&&typeof globalThis.process<"u")try{let E=(i=(r=globalThis.process.mainModule)===null||r===void 0?void 0:r.require)!==null&&i!==void 0?i:globalThis.require;E&&(k=E("fs").readFileSync(e.file))}catch{}if(k)g=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),y=g.byteLength;else throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);w||(w=_mt(e.file))}else if(typeof Blob<"u"&&e.file instanceof Blob)g=e.file,y=e.file.size,!w&&e.file.type&&(w=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)g=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,y=g.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(e.file)){let k=e.file;g=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),y=g.byteLength}else throw new Error("Unsupported file type for upload.");w||(w="application/octet-stream");let S=d.startsWith("environments/")?d.replace(/^environments\//,""):d,[T,R]=await rAe(this.resolveClient(e.api_version),S,f,"start",y,w,"resumable",e.api_version,e.extract,e.overwrite,It(n)).$inspect();if(!T.ok)throw ym(T.error);let C=R.status==="complete"?(a=(o=(s=R.response)===null||s===void 0?void 0:s.headers)===null||o===void 0?void 0:o.get("x-goog-upload-url"))!==null&&a!==void 0?a:(l=(c=R.response)===null||c===void 0?void 0:c.headers)===null||l===void 0?void 0:l.get("X-Goog-Upload-URL"):void 0;if(!C)throw new Error("Failed to get upload URL from upload handshake response.");let D=8*1024*1024,$=0,G,V=g instanceof Blob?g:new Blob([g]);for(;$<y||y===0&&$===0;){let k=Math.min($+D,y),E=V.slice($,k),A=k>=y,M=A?"upload, finalize":"upload";if(G=await m.request({path:"",body:E,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:"",baseUrl:C,headers:Object.assign(Object.assign({},((u=n?.httpOptions)===null||u===void 0?void 0:u.headers)||{}),{"X-Goog-Upload-Command":M,"X-Goog-Upload-Offset":`${$}`})})}),$=k,A)break}let L;if(G&&typeof G.json=="function"?L=await G.json():G&&G.responseInternal&&typeof G.responseInternal.json=="function"&&(L=await G.responseInternal.json()),L&&typeof L=="object"){if(Array.isArray(L.files))return L;if(L.name||L.path)return{files:[L]};if(L.file&&typeof L.file=="object")return{files:[L.file]}}return L}},lz=class{constructor(e){this.parentClient=e,this.files=new cz(n=>this.getClient(n),this.parentClient)}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(QTe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(tAe(this.getClient(r),r,i,s,It(n)))}async get(e,n={},r){return en(eAe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async delete(e,n={},r){return en(ZTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}},uz=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Cr(e,["api_version"]);return en(zTe(this.getClient(r),i,r,It(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:s}=e??{};return en(XTe(this.getClient(r),r,i,s,It(n)))}async get(e,n={},r){return en(YTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}async update(e,n,r){let{api_version:i,update_mask:s}=n,o=Cr(n,["api_version","update_mask"]);return en(JTe(this.getClient(i),e,o,i,s,It(r)))}async delete(e,n={},r){return en(KTe(this.getClient(n?.api_version),e,n?.api_version,It(r)))}getClient(e){var n;return e?ra(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ra(this.parentClient)),this.sdk)}};Ube="x-goog-api-key",WS="https://www.googleapis.com/auth/cloud-platform",dz=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=vmt(e.googleAuthOptions);this.googleAuth=new qbe.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(Ube)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(Ube,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,s]of r)e.get(i)===null&&e.append(i,s)}};fz=class{async download(e,n){if(e.downloadPath){let r=await Emt(e,n);if(r instanceof Vu){let i=(0,$be.createWriteStream)(e.downloadPath);Hbe.Readable.fromWeb(r.responseInternal.body).pipe(i),await(0,jbe.finished)(i)}else try{await(0,Gbe.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};pz=class{create(e,n,r){return new hz(e,n,r)}},hz=class{constructor(e,n,r){this.url=e,this.headers=n,this.callbacks=r}connect(){this.ws=new yW.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()}};yz=class extends ic{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hl(pl.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 s=Object.assign(Object.assign({},n),{preTunedModel:i});return s.baseModel=void 0,await this.tuneInternal(s)}else{let i=Object.assign({},n);return await this.tuneInternal(i)}else{let i=Object.assign({},n),s=await this.tuneMldevInternal(i),o="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?o=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(o=s.name.split("/operations/")[0]),{name:o,state:SO.JOB_STATE_QUEUED}}}}async getInternal(e){var n,r,i,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Mmt(e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>gz(u))}else{let l=Omt(e);return a=Ce("{name}",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>Gmt(u))}}async listInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Dmt(e);return s=Ce("tuningJobs",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Lmt(c),u=new kO;return Object.assign(u,l),u})}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,s;let o,a="",c={};if(this.apiClient.isVertexAI()){let l=Smt(e);return a=Ce("{name}:cancel",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),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(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=bmt(u),f=new ex;return Object.assign(f,d),f})}else{let l=wmt(e);return a=Ce("{name}:cancel",l._url),c=l._query,delete l._url,delete l._query,o=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(u=>u.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:u.headers},f})),o.then(u=>{let d=xmt(u),f=new ex;return Object.assign(f,d),f})}}async tuneInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=Rmt(e,e);return s=Ce("tuningJobs",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>gz(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,s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Cmt(e);return s=Ce("tunedModels",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>Hmt(c))}}async validateReward(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let a=jmt(e);return s=Ce("{parent}/tuningJobs:validateReinforcementTuningReward",a._url),o=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),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(l=>{let u=l;return u.sdkHttpResponse={headers:c.headers},u})),i.then(c=>{let l=Wmt(c),u=new PO;return Object.assign(u,l),u})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},SAe=1024*1024*8,xAe=3,bAe=1e3,TAe=2,qf="x-goog-upload-status";_z=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let r=await s1.stat(e);return n.size=r.size,n.type=this.inferMimeType(e),n}else return await Kmt(e)}async upload(e,n,r,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,r,i):Vmt(e,n,r,i)}async uploadToFileSearchStore(e,n,r,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,r,i):zmt(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 s;let o=await this.uploadFileFromPathInternal(e,n,r,i),a=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async uploadFileToFileSearchStoreFromPath(e,n,r,i){var s;let o=await this.uploadFileFromPathInternal(e,n,r,i),a=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[qf])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=Sz(a),l=new ix;return Object.assign(l,c),l}async uploadFileFromPathInternal(e,n,r,i){var s,o,a;let c=n,l=i?.baseUrl||((s=r.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(l){let w=new URL(l),S=new URL(n);S.protocol=w.protocol,S.host=w.host,S.port=w.port,c=S.toString()}let u=0,d=0,f=new Vu(new Response),m="upload",g,y=Wbe.basename(e);try{if(g=await s1.open(e,"r"),!g)throw new Error("Failed to open file");for(u=(await g.stat()).size;d<u;){let w=Math.min(SAe,u-d);d+w>=u&&(m+=", finalize");let S=new Uint8Array(w),{bytesRead:T}=await g.read(S,0,w,d);if(T!==w)throw new Error(`Failed to read ${w} bytes from file at offset ${d}. bytes actually read: ${T}`);let R=new Blob([S]),C=0,D=bAe;for(;C<xAe;){let $=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(d),"X-Goog-Upload-File-Name":y});if(f=await r.request({path:"",body:R,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:c,headers:$})}),!((o=f?.headers)===null||o===void 0)&&o[qf])break;C++,await CAe(D),D=D*TAe}if(d+=T,((a=f?.headers)===null||a===void 0?void 0:a[qf])!=="active")break;if(u<=d)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return f}finally{g&&await g.close()}}};vz=class extends uTe{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||{},s=i.httpOptions||{},o=Object.assign({},s.headers||{});if(r)if(typeof r[Symbol.iterator]=="function")for(let[a,c]of r)o[a]=c;else for(let[a,c]of Object.entries(r))o[a]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},s),{headers:o})})})}};Ymt="gl-node/";Ez=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=ra(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 iz(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new oz(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 sz(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 az(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 lz(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 uz(this.apiClient),this._credentials)}constructor(e={}){var n,r,i,s;if(this.vertexai=Xmt(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let o=Jmt(),a=$f("GOOGLE_CLOUD_PROJECT"),c=$f("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:o,this.project=(r=e.project)!==null&&r!==void 0?r:a,this.location=(i=e.location)!==null&&i!==void 0?i:c,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((s=e.googleAuthOptions)===null||s===void 0)&&s.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!e.project&&!e.location&&(a||c)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&o?(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&&(a||c)&&o&&(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 l=Iat(e.httpOptions,this.vertexai,$f("GOOGLE_VERTEX_BASE_URL"),$f("GOOGLE_GEMINI_BASE_URL"));l&&(e.httpOptions?e.httpOptions.baseUrl=l:e.httpOptions={baseUrl:l}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let u=new dz({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new SV({auth:u,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:Ymt+process.version,uploader:new _z,downloader:new fz}),this.models=new _m(this.apiClient),this.live=new zO(this.apiClient,u,new pz),this.batches=new HO(this.apiClient),this.chats=new WO(this.models,this.apiClient),this.caches=new jO(this.apiClient),this.files=new vz(this.apiClient),this.operations=new YO(this.apiClient),this.authTokens=new XO(this.apiClient),this.tunings=new yz(this.apiClient),this.fileSearchStores=new AV(this.apiClient)}}});function LAe({provider:t,baseUrl:e,apiKey:n,model:r}={}){t&&Zmt.includes(t)&&(Nt.provider=t),e!==void 0&&(Nt.baseUrl=String(e||"").replace(/\/+$/,"")),n!==void 0&&(Nt.apiKey=String(n||"")),r&&(Nt.model=String(r))}function UAe(t={}){LAe(t),l1.info(`config \u2190 web: provider=${Nt.provider} baseUrl="${Nt.baseUrl}" model=${Nt.model} key=${Nt.apiKey?Nt.apiKey.slice(0,7)+"\u2026":"(none)"}`),u1.set(OAe,{...Nt}).catch(()=>{})}async function FAe(){if(kAe)return!0;kAe=!0;try{let t=await u1.get(OAe);t&&typeof t=="object"&&LAe(t),l1.info(`config \u2190 kv (restart restore): provider=${Nt.provider} baseUrl="${Nt.baseUrl}" model=${Nt.model} key=${Nt.apiKey?"kept":"(none)"}`)}catch{}return!0}function BAe(){return{...Nt,apiKey:void 0,ready:!!Nt.apiKey,busy:ux}}function ngt(t){if(!t||typeof t!="object")return null;if(t.role==="user"&&t.parts){let e=t.parts.filter(r=>typeof r?.text=="string"&&r.text).map(r=>r.text).join(""),n=t.parts.filter(r=>r?.functionResponse);return n.length?{role:"tool",results:n.map(r=>({name:r.functionResponse.name,output:r.functionResponse.response}))}:e?{role:"user",text:e}:null}if(t.role==="model"&&Array.isArray(t.parts)){let e=t.parts.filter(r=>typeof r?.text=="string"&&r.text).map(r=>r.text).join(""),n=t.parts.filter(r=>r?.functionCall).map((r,i)=>({id:`${r.functionCall.name}-${i}`,name:r.functionCall.name,args:r.functionCall.args||{}}));return{role:"assistant",text:e,calls:n}}return null}async function qAe(){if(ml)return ml;try{ml=await u1.get(PAe)||[]}catch{ml=[]}return Array.isArray(ml)||(ml=[]),ml=ml.map(t=>t&&!t.parts&&(t.role==="user"||t.role==="assistant"||t.role==="tool")?t:ngt(t)).filter(Boolean),ml}async function rgt(){try{await u1.set(PAe,ml.slice(-MAe))}catch{}}function kz(){return Kk().map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,parameters:n}))}function igt(t){return t.map(e=>e.role==="user"?{role:"user",parts:[{text:e.text}]}:e.role==="tool"?{role:"user",parts:e.results.map(n=>({functionResponse:{name:n.name,response:n.output}}))}:{role:"model",parts:[...e.text?[{text:e.text}]:[],...(e.calls||[]).map(n=>({functionCall:{name:n.name,args:n.args}}))]})}async function sgt(t){let{GoogleGenAI:e}=await Promise.resolve().then(()=>(IAe(),RAe)),i=(await new e({...Nt.baseUrl?{httpOptions:{baseUrl:Nt.baseUrl}}:{},apiKey:Nt.apiKey}).models.generateContent({model:Nt.model,contents:igt(t),config:{systemInstruction:Iz,tools:[{functionDeclarations:kz()}]}}))?.candidates?.[0]?.content?.parts||[];return{text:i.filter(s=>typeof s?.text=="string"&&s.text).map(s=>s.text).join(""),calls:i.filter(s=>s?.functionCall).map((s,o)=>({id:`${s.functionCall.name}-${o}`,name:s.functionCall.name,args:s.functionCall.args||{}}))}}function ogt(t){let e=[{role:"system",content:Iz}];for(let n of t)if(n.role==="user")e.push({role:"user",content:n.text});else if(n.role==="assistant")e.push({role:"assistant",content:n.text||null,...n.calls?.length?{tool_calls:n.calls.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.args||{})}}))}:{}});else if(n.role==="tool")for(let r of n.results)e.push({role:"tool",tool_call_id:r.callId||r.name,content:JSON.stringify(r.output)});return e}function agt(){let t="",e=[];return{push(n){typeof n?.content=="string"&&(t+=n.content);for(let r of n?.tool_calls||[]){let i=r.index??0;e[i]=e[i]||{id:"",name:"",args:""},r.id&&(e[i].id=r.id),r.function?.name&&(e[i].name+=r.function.name),typeof r.function?.arguments=="string"&&(e[i].args+=r.function.arguments)}},result(){return{text:t,calls:e.filter(Boolean).map(n=>({id:n.id,name:n.name,args:$Ae(n.args)}))}}}}async function cgt(t){let e=Nt.baseUrl||"https://openrouter.ai/api/v1",n=await fetch(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nt.apiKey}`},body:JSON.stringify({model:Nt.model,stream:!0,messages:ogt(t),tools:kz().map(c=>({type:"function",function:c}))}),signal:AbortSignal.timeout(DAe)});if(!n.ok){let c=await n.json().catch(()=>null);throw new Error(c?.error?.message||`HTTP ${n.status}`)}if(!(n.headers.get("content-type")||"").includes("text/event-stream")){let c=(await n.json())?.choices?.[0]?.message||{};return{text:typeof c.content=="string"?c.content:"",calls:(c.tool_calls||[]).map(l=>({id:l.id,name:l.function?.name||"",args:$Ae(l.function?.arguments)}))}}let i=agt(),s=n.body.getReader(),o=new TextDecoder,a="";for(;;){let{done:c,value:l}=await s.read();if(c)break;a+=o.decode(l,{stream:!0});let u;for(;(u=a.indexOf(`
530
530
  `))>=0;){let d=a.slice(0,u).trim();if(a=a.slice(u+1),!d.startsWith("data:"))continue;let f=d.slice(5).trim();if(f==="[DONE]")return i.result();let m;try{m=JSON.parse(f)}catch{continue}if(m.error)throw new Error(m.error?.message||"stream error");i.push(m.choices?.[0]?.delta)}}return i.result()}function lgt(t){let e=[];for(let n of t)n.role==="user"?e.push({role:"user",content:n.text}):n.role==="assistant"?e.push({role:"assistant",content:[...n.text?[{type:"text",text:n.text}]:[],...(n.calls||[]).map(r=>({type:"tool_use",id:r.id,name:r.name,input:r.args}))]}):n.role==="tool"&&e.push({role:"user",content:n.results.map(r=>({type:"tool_result",tool_use_id:r.callId||r.name,content:JSON.stringify(r.output)}))});return e}async function ugt(t){let e=Nt.baseUrl||"https://api.anthropic.com",n=await fetch(`${e}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":Nt.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:Nt.model,max_tokens:4096,system:Iz,messages:lgt(t),tools:kz()}),signal:AbortSignal.timeout(DAe)}),r=await n.json();if(!n.ok)throw new Error(r?.error?.message||`HTTP ${n.status}`);let i=r?.content||[];return{text:i.filter(s=>s.type==="text").map(s=>s.text).join(""),calls:i.filter(s=>s.type==="tool_use").map(s=>({id:s.id,name:s.name,args:s.input||{}}))}}function $Ae(t){if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{return{}}}async function dgt(t,e){let n=Cf.find(r=>r.name===t);if(!n)return{error:`unknown tool: ${t}`};try{let r=await n.run(e||{},{sessionId:"jarvis-agent"});return r?.error?{error:r.error}:typeof r=="string"?{result:r.slice(0,NAe)}:r}catch(r){return{error:r.message}}}async function Pz(t,e){if(ux)return{error:"a turn is already running \u2014 wait for it to finish"};if(!Nt.apiKey)return{error:"no API key \u2014 add one in Settings \u2192 Jarvis"};ux=!0;try{let n=e||(()=>{}),r=await qAe();r.push({role:"user",text:String(t||"")});let i=tgt||(Nt.provider==="openai"?cgt:Nt.provider==="anthropic"?ugt:sgt);l1.info(`turn: provider=${Nt.provider} baseUrl="${Nt.baseUrl}" model=${Nt.model} history=${r.length}`);let s="";for(let o=0;o<Qmt;o++){let{text:a,calls:c}=await i(r);if(r.push({role:"assistant",text:a,calls:c}),!c.length){s=a||"(no answer)";break}let l=[];for(let u of c){n("tool",{name:u.name,args:u.args||{}});let d=await dgt(u.name,u.args),f=JSON.stringify(d).slice(0,NAe);n("toolResult",{name:u.name,result:f}),l.push({callId:u.id,name:u.name,output:d})}r.push({role:"tool",results:l})}return s||(s="tool-call loop limit reached \u2014 stopped for safety, ask me again to continue"),n("assistant",{text:s}),await rgt(),{text:s}}catch(n){return l1.error(`agent turn failed: ${n.message}`),{error:`${Nt.provider} error: ${n.message}`}}finally{ux=!1}}async function GAe(t){return!Nt.apiKey||ux?{skipped:!0}:await Pz(t,()=>{})}async function HAe(){return(await qAe()).slice(-MAe)}var l1,u1,PAe,OAe,MAe,Qmt,NAe,DAe,Iz,Zmt,egt,Nt,ux,ml,tgt,kAe,Oz=ae(()=>{_i();Yk();tt();l1=Se("jarvis"),u1={get:qp,set:Bp},PAe="jarvis:chat",OAe="jarvis:agentConfig",MAe=60,Qmt=8,NAe=4e3,DAe=12e4,Iz="You are Jarvis \u2014 the conductor coordinating worker sessions (AI CLIs and terminals) on this machine. The user chats to delegate work and ask about status. Convention: when the user asks to 'create a task/job in workspace X', OPEN a worker session in that workspace (create_session with the workspace taken from list_fleet's workspacePath, default engine claude), delegate via dispatch_prompt, and record a manage_kanban card for that workspace. When woken because a worker finished or awaits approval: check with list_fleet, update the board, report only what matters. When a worker is done and no longer needed, close_session to free its resources. Reply briefly, in the user's language.",Zmt=["gemini","openai","anthropic"],egt={provider:"gemini",baseUrl:"",model:"gemini-3.8-flash"},Nt={...egt,apiKey:""},ux=!1,ml=null,tgt=null,kAe=!1});function pgt({wake:t=GAe,refreshBoard:e=async()=>{await zk(await U_())},debounceMs:n=fgt,enabled:r=!0}={}){let i=r,s=[],o=null;return{setWakeEnabled(a){i=!!a},onWorkerDone(a){!i||!a||(s.includes(a)||s.push(a),e(),o&&clearTimeout(o),o=setTimeout(()=>{o=null,this._flush()},n))},async _flush(){let a=s;if(s=[],!a.length)return;let c=a.length===1?`Worker ${a[0]}`:`Workers ${a.join(", ")}`;try{await t(`[9remote] ${c} changed state (finished or awaiting approval) \u2014 check with list_fleet, update the kanban board if needed, and only report back briefly when something matters.`)}catch{}}}}function VAe(t){WAe.setWakeEnabled(t)}function Mz(t){WAe.onWorkerDone(t)}function zAe(){jAe||(jAe=!0,Sr.onEvent((t,e)=>{e==="turn_complete"&&Mz(t)}))}var fgt,WAe,jAe,Nz=ae(()=>{Xd();jk();hS();Oz();fgt=3e3;WAe=pgt({enabled:!1}),jAe=!1});function YAe(t){hgt&&(zAe(),FAe(),t.on("jarvis:getState",async(e,n)=>{try{let r=await U_(),i=await zk(r);n?.({ok:!0,board:i,fleet:r})}catch(r){Dz.error(`getState failed: ${r.message}`),n?.({ok:!1,error:r.message})}}),t.on("jarvis:kanban",async({action:e}={},n)=>{try{let r=await F_(e,"web");n?.(r.error?{ok:!1,error:r.error}:{ok:!0,board:r.board})}catch(r){Dz.error(`kanban action failed: ${r.message}`),n?.({ok:!1,error:r.message})}}),t.on("jarvis:tools",(e,n)=>n?.({ok:!0,tools:Kk()})),t.on("jarvis:tool",async({name:e,args:n}={},r)=>{let i=Cf.find(s=>s.name===e);if(!i)return r?.({ok:!1,error:`unknown tool: ${e}`});try{let s=await i.run(n||{},{sessionId:"jarvis-live"});r?.(s?.error?{ok:!1,error:s.error}:{ok:!0,result:typeof s=="string"?s:JSON.stringify(s)})}catch(s){Dz.error(`live tool ${e} failed: ${s.message}`),r?.({ok:!1,error:s.message})}}),t.on("jarvis:agentConfig",({apiKey:e,model:n,wake:r}={},i)=>{UAe({apiKey:e,model:n}),r!==void 0&&VAe(!!r),i?.({ok:!0,...BAe()})}),t.on("jarvis:chatHistory",async(e,n)=>{try{n?.({ok:!0,history:await HAe()})}catch(r){n?.({ok:!1,error:r.message})}}),t.on("jarvis:chat",async({text:e}={},n)=>{if(!e||typeof e!="string")return n?.({ok:!1,error:"text is required"});KAe("jarvis:chat:event",{type:"user",text:e.slice(0,2e3)});let r=await Pz(e,(i,s)=>KAe("jarvis:chat:event",{type:i,...s}));n?.(r.error?{ok:!1,error:r.error}:{ok:!0,text:r.text})}))}var Dz,hgt,KAe,XAe=ae(()=>{jk();hS();Nz();Oz();Yk();nu();es();tt();Dz=Se("jarvis"),hgt=!1,KAe=(t,e)=>{let n=Ya();n&&nt(n,t,e)}});function eCe(){let t="";for(let e=0;e<mgt;e++)t+=JAe[Lz.default.randomInt(JAe.length)];return t}function Uz(){let t=A7(ZAe,null);return!t||Date.now()>t.expiresAt?null:t}function tCe(t){try{xn(ZAe,t)}catch(e){d1.error(`persist pairing state: ${e.message}`)}}function nCe(t,e,n,r=null){tCe({tempKey:t,tail:e,expiresAt:n,workerUrl:r})}function ggt(){tCe({tempKey:null,tail:null,expiresAt:0,workerUrl:null})}async function ygt(t,e){if(!(!t||!e))try{await mc(`${e}/api/temp-key/remove`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempKey:t})}),d1.info(`one-time code revoked at the Worker: ${t}`)}catch(n){d1.warn(`could not revoke the code at the Worker: ${n.message}`)}}function dx(){let t=Uz();return t?{tempKey:t.tempKey,tail:t.tail,expiresAt:t.expiresAt}:null}function f1(t){let e=Uz();if(!e?.tail||!t)return!1;let n=Buffer.from(String(t).toUpperCase(),"utf8"),r=Buffer.from(String(e.tail).toUpperCase(),"utf8");return n.length===r.length&&Lz.default.timingSafeEqual(n,r)}function Fz(t,e=null){let n=Uz();return!n||!t?{match:!1,burned:!1}:f1(t)?{match:!0,burned:!1}:!e||String(e).trim().toUpperCase()===String(n.tempKey).trim().toUpperCase()?(ggt(),d1.warn("pairing tail mismatch \u2014 code killed here and at the Worker"),ygt(n.tempKey,n.workerUrl),{match:!1,burned:!0}):{match:!1,burned:!1}}var Lz,QAe,d1,ZAe,JAe,mgt,Bz=ae(()=>{Lz=ce(require("crypto"),1),QAe=require("path");Lt();tt();So();Lt();d1=Se("pairing"),ZAe=(0,QAe.join)(Oe.STATE,"pairing.json"),JAe="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789",mgt=2});function iCe(){let t="";for(let e=0;e<_gt;e++)t+=rCe[qz.default.randomInt(rCe.length)];return t}function sCe(t){return`sk-${(t||"").slice(0,8).toLowerCase()}-${iCe()}-${iCe()}`}function oCe(t){return/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(t||"")}function Dn(t){if(!oCe(t))return t||null;let e=t.split("-");return`${e[0]}-${e[1]}-${e[2]}`}function p1(t){return oCe(t)?t.split("-")[3]:null}function h1(t,e){if(typeof t!="string"||!t||typeof e!="string"||!e)return!1;let n=Buffer.from(Dn(t)||"","utf8"),r=Buffer.from(Dn(e)||"","utf8");return n.length>0&&n.length===r.length&&qz.default.timingSafeEqual(n,r)}var qz,rCe,_gt,Vf=ae(()=>{qz=ce(require("crypto"),1),rCe="abcdefghijklmnpqrstuvwxyz123456789",_gt=8});var dCe={};yr(dCe,{PROOF_DEADLINE:()=>zz,admissionGate:()=>Kz,clearProofWaiters:()=>Vz,finishTailRejection:()=>y1,handleTailProof:()=>Yz,isProvingExpired:()=>bgt,isTailProofEnabled:()=>Ev,noteTailFailure:()=>px,onTailProven:()=>g1,presentedTailOf:()=>hx,submitTailProof:()=>m1,verdictStateOf:()=>fx,verifyKeyTail:()=>wv,verifyPresentedTail:()=>Agt});function uCe(){return p1(Zi()?.key||"")}function Ev(){return!!uCe()}function Wz(t,e){let n=t?Hz.get(t):null;return!n||n.keyHead!==e?null:n}function cCe(t,e,n,r=null){if(!t)return;let i=Hz.get(t);Hz.set(t,{keyHead:e,state:n,reason:r,since:Date.now()}),n!==i?.state&&(n===wo.proven&&Tgt(t),n===wo.rejected&&Ku.delete(t))}function m1(t,e,{pairing:n=!1,tempKey:r=null}={}){let i=Dn(Zi()?.key||"");if(!t||!Ev()&&!n)return!1;if((n?Fz(e,r):{match:wv(e)}).match)return cCe(t,i,wo.proven),yQ(t,i),Gz.info(`[seal] proof accepted: device=${t.slice(0,8)}`),!0;let o=e===null?ti.sealUnreadable:ti.mismatch;return cCe(t,i,wo.rejected,o),Gz.warn(`[seal] proof rejected (${o}): device=${t.slice(0,8)}`),!1}function bgt(t){let e=Wz(t,Dn(Zi()?.key||""));return!!e&&e.state===wo.proving&&Date.now()-e.since>jz}function fx(t){return Wz(t,Dn(Zi()?.key||""))?.state||null}function g1(t,e,n){if(!t||!Ev()||fx(t)===wo.proven)return e();Ku.has(t)||Ku.set(t,new Set),Ku.get(t).add(e),n&&setTimeout(()=>{let r=Ku.get(t);r?.delete(e)&&(r.size||Ku.delete(t),n())},jz)}function Tgt(t){let e=Ku.get(t);if(e){Ku.delete(t);for(let n of e)try{n()}catch{}}}function Vz(t){Ku.delete(t)}function px(t){let e=Date.now(),n=(aCe.get(t)||[]).filter(i=>e-i<Sgt);n.push(e),aCe.set(t,n);let r=n.length-vgt;return r<=0?0:Math.min(Egt*2**(r-1),wgt)}function Agt({tail:t,tempKey:e}={}){let n=!!e;if(!n&&!Ev())return{ok:!0};if(!t)return{ok:!1,reason:ti.mismatch,penaltyMs:0};let r=n?Fz(t,e):{match:wv(t)};return r.match?{ok:!0}:{ok:!1,reason:ti.mismatch,burned:!!r.burned,penaltyMs:px(Dn(Zi()?.key||""))}}function Kz(t,e,{provenSocket:n=!1,tempKey:r=null}={}){let i=Dn(Zi()?.key||""),s=O0(t);if(s===Xi.rejected)return{step:"authz",decision:Ir.reject,reason:"device-rejected"};let o=!!r&&!eA(t);if(o){let a=dx();Gz.info(`[pair] device=${t?.slice(0,8)} presented=${e===void 0?"none":String(e).length+"ch"} liveCode=${a?"yes":"no"} liveTail=${a?.tail?String(a.tail).length+"ch":"none"} match=${e===void 0?"n/a":f1(String(e))}`)}if(Ev()||o){let a=Wz(t,i);if(a?.state===wo.rejected&&e===void 0)return{step:"auth",decision:Ir.reject,reason:a.reason};let c=u=>o?f1(u):wv(u);if(!(n||a?.state===wo.proven||e!==void 0&&c(e)))return e!==void 0?{step:"auth",decision:Ir.reject,reason:e===null?ti.sealUnreadable:ti.mismatch}:{step:"auth",decision:Ir.hold,reason:"awaiting-proof"}}return s===Xi.approved||s===Xi.auto?{step:"authz",decision:Ir.admit}:{step:"authz",decision:Ir.hold,reason:"host-decides"}}function wv(t){let e=uCe();if(!e||!t)return!1;let n=Buffer.from(String(t),"utf8"),r=Buffer.from(e,"utf8");return n.length===r.length&&lCe.default.timingSafeEqual(n,r)}function hx(t,e){let n=t?.keyTailSealed;return n!==void 0?!n||typeof n!="object"||Array.isArray(n)?null:e(n)??null:t?.keyTail}function Yz(t,e){let n=t?.data?.auth?.deviceId||t.handshake?.auth?.deviceId||t.deviceId||null,r=t.handshake?.auth?.tempKey||e?.tempKey||null,i=!!r&&!!dx();if(!n||!Ev()&&!i)return!0;let s=hx(e,v0);return s===void 0||m1(n,s,{pairing:i,tempKey:r})?!0:(t.data.tailReject={reason:s===null?ti.sealUnreadable:ti.mismatch,penaltyMs:px(Dn(Zi()?.key||""))},!1)}function y1(t,e){if(t.data?.tailRejectFinished)return;t.data.tailRejectFinished=!0;let{reason:n,penaltyMs:r=0}=t.data?.tailReject||{},i=$z>=xgt,s=i?0:r;i||$z++,setTimeout(()=>{i||$z--;try{t.emit("device:tailRejected",{reason:n}),t.disconnect()}catch{}e?.()},s)}var lCe,Gz,vgt,Egt,wgt,Sgt,xgt,aCe,$z,Hz,jz,Ku,zz,Xz=ae(()=>{lCe=ce(require("crypto"),1);tt();N0();Bz();Ji();Vf();Ic();E0();Gz=Se("deviceAuth");vgt=5,Egt=1e3,wgt=60*1e3,Sgt=3600*1e3,xgt=20,aCe=new Map,$z=0,Hz=new Map,jz=2e4;Ku=new Map;zz=jz});var Zr,_1,mx=ae(()=>{Zr={authenticating:"authenticating",awaitingHost:"awaitingHost",active:"active",closed:"closed"},_1=new Set(["device:tailProof","device:clientReady","disconnect"])});var fCe,v1,pCe=ae(()=>{fCe=require("events");mx();v1=class extends fCe.EventEmitter{constructor({deviceId:e,peerId:n=null,apiKey:r=null}){super(),this.setMaxListeners(0),this.deviceId=e,this.peerId=n||e,this.apiKey=r,this.createdAt=Date.now(),this.data={},this._state=Zr.authenticating,this._carriers=new Map}get state(){return this._state}get active(){return this._state===Zr.active}get closed(){return this._state===Zr.closed}get carrierIds(){return[...this._carriers.keys()]}get connected(){for(let e of this._carriers.values())if(e?.ready)return!0;return!1}attach(e,n){if(this.closed)return!1;let r=this._carriers.get(e);return r&&r!==n&&this._detachOne(e,r),this._carriers.set(e,n),this.emit("carrierAttached",e,n),!0}detach(e){let n=this._carriers.get(e);return n?(this._detachOne(e,n),!0):!1}_detachOne(e,n){this._carriers.delete(e),this.emit("carrierDetached",e,n)}hasCarrier(e){return this._carriers.has(e)}carrier(e){return this._carriers.get(e)||null}allows(e){return this.active?!0:this.closed?!1:_1.has(e)}keyProven(){return this._state!==Zr.authenticating?!1:this._transition(Zr.awaitingHost,"key-proven")}hostAllowed(){return this._state!==Zr.awaitingHost?!1:this._transition(Zr.active,"host-allowed")}close(e="closed"){if(this.closed)return!1;for(let[n,r]of[...this._carriers])this._detachOne(n,r);return this._transition(Zr.closed,e)}_transition(e,n){let r=this._state;return this._state=e,this.emit("state",{from:r,to:e,reason:n,deviceId:this.deviceId}),!0}toJSON(){return{deviceId:this.deviceId,peerId:this.peerId,state:this._state,carriers:this.carrierIds,createdAt:this.createdAt}}}});var E1,hCe=ae(()=>{pCe();mx();E1=class{constructor(){this._byPeer=new Map,this._byDevice=new Map}open({deviceId:e,peerId:n,apiKey:r}){let i=n||e,s=this._byPeer.get(i);if(s&&!s.closed)return s;let o=new v1({deviceId:e,peerId:i,apiKey:r});return this._byPeer.set(i,o),this._byDevice.has(e)||this._byDevice.set(e,new Set),this._byDevice.get(e).add(i),o.on("state",a=>{a.to===Zr.closed&&this.delete(i)}),o}get(e){let n=this._byPeer.get(e);return n&&!n.closed?n:null}forDevice(e){let n=this._byDevice.get(e);if(!n)return[];let r=[];for(let i of n){let s=this._byPeer.get(i);s&&!s.closed&&r.push(s)}return r}closeDevice(e,n){let r=this.forDevice(e);for(let i of r)i.close(n);return r.length}delete(e){let n=this._byPeer.get(e);if(!n)return!1;this._byPeer.delete(e);let r=this._byDevice.get(n.deviceId);return r&&(r.delete(e),r.size||this._byDevice.delete(n.deviceId)),!0}get size(){return this._byPeer.size}all(){return[...this._byPeer.values()]}}});function mCe(t,e){return!t||t.closed?{effects:[]}:e.decision===Ir.reject?{effects:["refuse"],reason:e.reason||ti.mismatch}:e.decision===Ir.hold&&e.step==="auth"?t.state===Zr.authenticating?{effects:["open-auth-channel"],reason:e.reason}:{effects:[],reason:e.reason}:(t.state===Zr.authenticating&&t.keyProven(),e.decision===Ir.hold?{effects:["ask-host"],reason:e.reason}:(t.state===Zr.awaitingHost&&t.hostAllowed(),{effects:t.active?["start-session"]:[]}))}var gCe=ae(()=>{mx();Ji()});function ia(){try{let t=(0,vCe.join)(Oe.ROOT,"keys.json");return JSON.parse((0,_Ce.readFileSync)(t,"utf8")).key||null}catch{return null}}function Ya(){return vs}function yx(t){return t.carrier||{id:"ws",ip:t.handshake?.headers?.["x-forwarded-for"]||t.handshake?.address||"unknown",pendingId:t.id}}function Qn(t){return t?.data?.auth||t?.handshake?.auth||null}function Qz(t,e){let n=t?hx(Qn(t),v0):void 0,r=Kz(e,n,{provenSocket:t?.data?.provenDevice===!0,tempKey:Qn(t)?.tempKey||null});Dr.info(`gate: device=${e?.slice(0,8)??"none"} step=${r.step} decision=${r.decision}${r.reason?` reason=${r.reason}`:""} carrier=${t?yx(t).id:"signaling"}`);let i=!!Qn(t)?.tempKey,s=r.step==="authz"&&!i;return t&&n!==void 0&&(s||r.step==="auth")&&m1(e,n,{pairing:i,tempKey:Qn(t)?.tempKey||null}),t&&r.decision===Ir.reject&&r.step==="auth"&&(t.data.tailReject=t.data.tailReject||{reason:r.reason,penaltyMs:px(Dn(ia()||""))}),r}function Rgt(t){t.data.authHandlersReady||(t.data.authHandlersReady=!0,t.on("device:tailProof",e=>{let n=Qn(t)?.deviceId;e?.tempKey&&t.data&&(t.data.auth||(t.data.auth={}),t.data.auth.tempKey=e.tempKey);try{let r=Yz(t,e);Dr.info(`tailProof: device=${n?.slice(0,8)} carrier=${yx(t).id} accepted=${r}`),r||xv(t,n)}catch(r){Dr.warn(`tailProof handler failed: ${r.message}`)}}))}async function _x(t){if(Qn(t)?.tempKey&&(Dr.info("one-time key used \u2014 clearing from UI"),KT()),await Pgt(t),Rgt(t),!t.data.localUi){let e=Qn(t)?.deviceId||null,n=Ogt(t);if(!n)return;let{id:r}=yx(t);n.attach(r,t.data.protocol?._adapters?.get(r)||null);let i=Qz(t,e),{effects:s,reason:o}=mCe(n,i);if(Dr.info(`flow: device=${e?.slice(0,8)} state=${n.state} effects=[${s.join(",")}]${o?` reason=${o}`:""}`),Xt(`[auth] ${e?.slice(0,8)}: ${n.state} \u2192 ${s.join(",")||"wait"}`),s.includes("refuse")){xv(t,e,o);return}if(s.includes("open-auth-channel")){t.data.awaitingProof||(t.data.awaitingProof=!0,g1(e,()=>{t.data.awaitingProof=!1,t.connected&&_x(t).catch(()=>{})},()=>xv(t,e,ti.timeout)));return}if(s.includes("ask-host")){let a=yx(t);r8(e,{socketId:a.pendingId,ip:a.ip,peerId:t.peerId,notify:()=>Em(t,"device:pendingApproval")});return}if(!s.includes("start-session"))return;O0(e)===Xi.auto&&(tA(e),jg(e),kn("deviceApproval",{action:"refresh"}))}await kgt(t)}function Igt(t){if(!Qn(t)?.tempKey)return;let e=p1(ia()||"");e&&n8(t,()=>{Em(t,"device:keyIssued",{tail:e}),Dr.info(`key issued to paired device=${Qn(t)?.deviceId?.slice(0,8)}`)})}function ECe(t){if(!t.connected||!t.data?.conn?.active&&!t.data?.localUi||!t.data?.clientReady)return;w1(t),Igt(t);let e=nf._buildServerInfo?.();e&&t.emit("serverInfo",e),t.emit("srvCaps",{env2:1,fragCtl:1}),t.emit("tunnel:updated",zT())}async function kgt(t){t.data.sessionReady||(t.data.sessionReady=!0,t.data.approved=!0,z_e(t),Y_e(t),Mve(t),Bve(t),v0e(t,vs),YAe(t),await y2(t,vs,ia()),ECe(t),t.emit("terminal:ready"))}async function Pgt(t){if(t.data.protocol)return;let{webrtc:e,streaming:n}=Te,r=new rA(t,{enableWebRTC:e.enableWebRTC,enableTurn:e.enableTurn??!1,apiKey:Dn(ia()),turnApiUrl:e.turnApiUrl||null,turnRefreshInterval:e.turnRefreshInterval,dcMaxMessageSize:e.dcMaxMessageSize,dcChunkSize:e.dcChunkSize,dcMaxTilesPerFrame:e.dcMaxTilesPerFrame,answerTimeout:e.answerTimeout,maxControlBuffer:e.maxControlBuffer,wsChunkSize:n.chunkSize,signaling:{deviceId:t.peerId||Qn(t)?.peerId||Qn(t)?.deviceId||null,doUrl:e.signalingDoUrl,apiKey:ia()}});t.data.protocol=r,t.defersWsAdapter&&(r._onDead=()=>{Dr.debug(`[diag] _onDead fired peer=${(t.peerId||"").slice(0,12)} \u2014 rtc never returned in grace`),yi(`RTC session closed: ${Qn(t)?.deviceId?.slice(0,8)}...`);try{r.close()}catch{}Td(r),t.disconnect()}),Y7(r),r.attachAsBus(t);try{await r.init()}catch(i){console.error("[transport] pm init failed:",i.message)}}function Ogt(t){let e=Qn(t)?.deviceId||null;if(!e)return null;let n=t.peerId||Qn(t)?.peerId||e,r=t.data.conn;if(r&&!r.closed)return r;let i=Zz.open({deviceId:e,peerId:n,apiKey:ia()});return t.data.conn=i,i}function jL(){return e8}function aQ(t){if(e8=t,!t){lL();return}J7();for(let e of[..._s.keys()])bv(e),yi(`RTC test-disabled: killed session ${e?.slice(0,8)}`)}function n8(t,e){t.data.clientReady?e():t.once("device:clientReady",e)}function wCe(t){t.data.clientReady=!1,t.on("device:clientReady",()=>{t.data.clientReady=!0,ECe(t)})}function Mgt(t){if(!t)return;if(!Sv()){gx(t,{type:"error",message:"remote-disabled"});return}if(e8){gx(t,{type:"error",message:"rtc-disabled"});return}let e=t.split(":")[0],n=_s.get(t);if(n){if(!n.data.protocol?._closed)return;yi(`Stale RTC session ${e.slice(0,8)} \u2014 rebuilding`),bv(t)}let r=Ngt(t),i=Qz(null,e);if(i.decision===Ir.hold&&i.step==="auth")return r?void 0:(Dr.info(`rtc-offer: building session so the TAIL proof has a road device=${e.slice(0,8)}`),void Jz(t,e));switch(i.decision){case Ir.admit:return r?void 0:void Jz(t,e);case Ir.reject:JL(e,yCe(t),"rtc"),gx(t,{type:"error",message:xg.rejected}),d0(t),Xt(`Rejected device via RTC: ${e.slice(0,8)} \u2014 waiting in Clients list`),kn("deviceApproval",{action:"refresh"});return;default:r8(e,{socketId:yCe(t),ip:"rtc",peerId:t,notify:()=>gx(t,{type:"error",message:xg.pending})})}}function r8(t,{socketId:e,ip:n,peerId:r,notify:i}){if(i(),vQ(t)){Xt(`[auth] already pending, not asking twice: ${t?.slice(0,8)}`);return}KL(e,{deviceId:t,ip:n,...r?{peerId:r}:{}}),Dr.info(`asking host: device=${t?.slice(0,8)} via=${r?"rtc":"ws"}`),Xt(`[auth] ASKING HOST: ${t?.slice(0,8)} via=${r?"rtc":"ws"} socketId=${e}`),Xt(`Device needs approval: ${t?.slice(0,8)||"no-id"}`),kn("deviceApproval",{socketId:e,deviceId:t,ip:n,action:"pending"})}function Ngt(t){for(let e of vs?.sockets.sockets.values()||[])if(e.connected&&Qn(e)?.peerId===t)return!0;return!1}function Em(t,e,...n){let r=t.data?.protocol;r&&!r._closed&&r.emitEverywhere(e,...n)||t.emit(e,...n)}function w1(t){let e=()=>{t.connected&&n8(t,()=>Em(t,"device:approved"))};if(t.data.localUi)return e();let n=t.data.conn;if(n?.active)return e();if(n)return void n.on("state",function r(i){i.to===Zr.closed&&n.off("state",r),i.to===Zr.active&&(n.off("state",r),e())})}function SCe(t){return t.data.approved||t.data.unlocking?Promise.resolve():(t.data.unlocking=!0,w1(t),_x(t).catch(n=>Xt(`Feature setup failed: ${n.message}`)).finally(()=>{t.data.unlocking=!1}))}async function xCe(t){if(!t)return;let e=M0(t);e&&Dp(e);let n=[];for(let r of vs?.sockets.sockets.values()||[])Qn(r)?.deviceId!==t||r.data.approved||n.push(SCe(r));for(let r of _s.values())Qn(r)?.deviceId!==t||r.data.approved||n.push(_x(r).catch(i=>Xt(`Connection resume failed: ${i.message}`)));await Promise.allSettled(n);for(let r of NJ(t))Jz(r,t)}function xv(t,e,n){Dr.debug(`[diag] rejectDeviceTail device=${e?.slice(0,8)} reason=${n}`),t.data.tailReject=t.data.tailReject||{reason:n,penaltyMs:0};let r=t.data.tailReject.reason;Dr.warn(`tail rejected (${r}): device=${e?.slice(0,8)??"none"} carrier=${yx(t).id}`),Xt(`Device refused (${r}): ${e?.slice(0,8)}`),Qn(t)?.tempKey&&r===ti.mismatch&&(Dr.warn("one-time key burned (wrong TAIL) \u2014 clearing from UI"),KT()),y1(t,()=>{t.defersWsAdapter&&bv(t.peerId),bCe(e,r)})}function bCe(t,e){if(Dr.debug(`[diag] revokeDevice device=${t?.slice(0,8)} reason=${e}`),!!t){Vz(t),Dp(M0(t)||""),Zz.closeDevice(t,e);for(let n of vs?.sockets.sockets.values()||[])Qn(n)?.deviceId===t&&(n.data.tailReject=n.data.tailReject||{reason:e,penaltyMs:0},y1(n));for(let[n,r]of _s)Qn(r)?.deviceId===t&&(r.data?.tailReject||bv(n))}}function TCe(t){let e=YL(t);if(e)return{key:t,...e};let n=t8(t)?.split(":")[0]||Qn(vs?.sockets.sockets.get(t)||null)?.deviceId||null,r=n?M0(n):null,i=r?YL(r):null;return i?{key:r,...i}:null}function bv(t){let e=t?_s.get(t):null;if(!e)return;let n=e.data?.protocol;_s.delete(t);try{e.disconnect()}catch{}if(n){try{n.close()}catch{}Td(n)}}function Jz(t,e){Dgt(t,e).catch(n=>{bv(t),Xt(`RTC session failed: ${n.message}`)})}async function Dgt(t,e){if(_s.has(t))return;let n=new ET({deviceId:e,peerId:t,apiKey:ia()});n.data.approved=!1,n.data.rtcSession=!0,n.data.conn=Zz.open({deviceId:e,peerId:t,apiKey:ia()}),wCe(n);let r;n.data.ready=new Promise(i=>{r=i}),_s.set(t,n),QT(n.id,"rtc",e,"rtc"),n.on("disconnect",()=>{Dr.debug(`[diag] AgentBus disconnect peer=${(t||"").slice(0,12)} \u2192 untrack + conn.close`),_s.get(t)===n&&_s.delete(t),ZT(n.id),n.data.conn?.close("carrier-gone"),r()}),yi(`RTC session: ${e.slice(0,8)}...`);try{await _x(n)}finally{r()}setTimeout(()=>{_s.get(t)===n&&fx(e)!==wo.proven&&(Xt(`Device never proved its TAIL: ${e.slice(0,8)} \u2014 dropping session`),xv(n,e,ti.timeout))},zz+1e3),w1(n)}function ACe(t){if(!vs)return!1;let e=TCe(t);return e?fx(e.deviceId)===wo.rejected?(Dr.warn(`approve refused \u2014 TAIL was rejected: device=${e.deviceId.slice(0,8)}`),Xt(`Cannot approve ${e.deviceId.slice(0,8)} \u2014 wrong access key`),Dp(e.key),bCe(e.deviceId,ti.mismatch),kn("deviceApproval",{action:"refresh"}),!1):(tA(e.deviceId),jg(e.deviceId),Xt(`Device approved: ${e.deviceId.slice(0,8)}...`),xCe(e.deviceId),kn("deviceApproval",{action:"refresh"}),!0):!1}function CCe(t){return!vs||!t?!1:(tA(t),jg(t),Xt(`Device approved from pending: ${t.slice(0,8)}...`),xCe(t),kn("deviceApproval",{action:"refresh"}),!0)}function S1(t){Dr.debug(`[diag] disconnectDeviceSockets device=${t?.slice(0,8)} \u2014 stack hint: ${new Error().stack.split(`
531
531
  `)[2]?.trim()?.slice(0,90)}`);let e=vs;if(!e||!t)return 0;let n=0;for(let r of e.sockets.sockets.values())Qn(r)?.deviceId===t&&(r.disconnect(!0),n++);for(let r of BT())r._closed||r._deviceId?.split(":")[0]===t&&(Lg(r),n++);for(let[r,i]of _s)if(r.split(":")[0]===t){try{i.data.protocol?.close()}catch{}Td(i.data.protocol),d0(r),i.disconnect(),n++}return n&&yi(`Disconnected ${n} socket(s) for device ${t.slice(0,8)}...`),n}function RCe(t){if(!vs)return!1;let e=TCe(t),n=vs.sockets.sockets.get(t);Dp(e?.key||t),e?.deviceId&&wQ(e.deviceId,{ip:e.ip,socketId:t}),n&&(Em(n,"device:rejected"),n.disconnect(!0));let r=e?.peerId||t8(t);return r&&(gx(r,{type:"error",message:xg.rejected}),d0(r)),kn("deviceApproval",{action:"refresh"}),Xt(`Device rejected: ${e?.deviceId?.slice(0,8)||"unknown"}...`),!0}function Sv(){return Pp().remoteEnabled!==!1}function ICe(t){let e=t.handshake?.address||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}function kCe(t){return t.handshake?.headers?.["cf-connecting-ip"]?!1:ICe(t)}function PCe(t){if(t){Sg(Dn(ia())),lL();return}TD();for(let r of BT())if(!r._closed){try{r._offGlobalSig?.()}catch{}r._offGlobalSig=null}let e=vs,n=new Set;if(e)for(let r of e.sockets.sockets.values()){if(r.data.localUi||kCe(r)){r.data.protocol&&n.add(r.data.protocol);continue}r.disconnect(!0)}for(let r of BT())r._closed||n.has(r)||Lg(r);for(let[r,i]of _s){try{i.data.protocol?.close()}catch{}Td(i.data.protocol),d0(r),i.disconnect()}}async function OCe(t){fQ(),xQ(),Sv()&&Sg(Dn(ia())),setInterval(()=>{if(!Sv())return;let r=Dn(ia());r&&Sg(r)},Cgt),OJ(Mgt),gT(()=>Fg());let e=new CJ(t,{cors:{origin:"*",methods:["GET","POST"],credentials:!0,allowedHeaders:["*"]},allowRequest:(r,i)=>i(null,!Yx(r.headers.host)),transports:["websocket","polling"],allowEIO3:!0,allowUpgrades:!0,pingTimeout:3e4,pingInterval:12e3,maxHttpBufferSize:1e8,perMessageDeflate:{threshold:1024}}),n=await WZ();return wL(n),e.on("connection",r=>{_T("client-connected");let i=r.handshake.headers["x-forwarded-for"]||r.handshake.address||"unknown",s=Qn(r)?.deviceId||null;wCe(r),r.data.approved=!1,r.use((d,f)=>{if(r.data.localUi)return f();let m=r.data.conn;return m?m.allows(d[0])?f():f(new Error("Device not approved")):_1.has(d[0])?f():f(new Error("Device not approved"))});let o=ICe(r),a=!!r.handshake.headers["cf-connecting-ip"],c=r.handshake.headers.origin,l=!c||dp.includes(c);if(!a&&o&&l&&qJ(r.handshake.auth?.localToken)){r.data.approved=!0,r.data.localUi=!0,yi("Local UI connected \u2014 trusted (token)"),_x(r).catch(d=>Xt(`Feature setup failed: ${d.message}`));return}if(s===up){Xt(`Rejected untrusted local-ui socket from ${i}`),r.disconnect(!0);return}if(!Sv()&&!kCe(r)){yi(`Rejected ${s?.slice(0,8)||"unknown"} from ${i} \u2014 remote access is off`),r.disconnect(!0);return}if(!a&&o&&l&&s&&!eA(s)){let d=hx(Qn(r),v0);d&&wv(d)&&O0(s)===Xi.unknown&&(hQ(s),Dr.info(`loopback workspace device admitted for this session (key TAIL verified): ${s.slice(0,8)}`),yi(`Loopback workspace admitted (session): ${s.slice(0,8)} (key TAIL verified)`))}QT(r.id,i,s),yi(`Client connected: ${i} (device: ${s?.slice(0,8)||"none"})`),r.on("disconnect",d=>{ZT(r.id),Dp(r.id);let f=r.data?.conn;f&&(f.detach("ws"),f.connected||f.close("carrier-gone"));let m=r.data?.protocol;yi(`Client disconnected: ${i} (${d}) pm=${m?._deviceId?.slice(0,12)||"none"} remoteAttached=${!!r.data?.remoteAttached}`),m&&!r.data?.remoteAttached&&Lg(m)});let u=()=>{if(!r.connected)return;let d=r.handshake.auth?.peerId||null,f=()=>{if(r.data.approved)return;let w=M0(s);if(w&&!t8(w)){yi(`Device ${s?.slice(0,8)} already pending, ignoring duplicate`),r.disconnect(!0);return}let S=!!w;w&&Dp(w),n8(r,()=>{if(!(r.data.approved||!r.connected)){if(S){KL(r.id,{deviceId:s,ip:i}),Em(r,"device:pendingApproval");return}r8(s,{socketId:r.id,ip:i,notify:()=>Em(r,"device:pendingApproval")})}})},m=w=>{let S=w.data.conn;r.data.conn=S,r.data.approved=!!S?.active,r.data.rtcHost=w,Promise.resolve(w.data.ready).then(()=>w.data.protocol?.attachSocket(r)).then(()=>S?.attach("ws",w.data.protocol?._adapters?.get("ws")||null)).then(()=>{S?.active&&r.emit("terminal:ready")}).catch(T=>Xt(`RTC session attachSocket failed: ${T.message}`)),yi(`Tunnel attached to RTC session: ${s.slice(0,8)}...`),w1(r)},g=d?_s.get(d):null;if(!g&&d&&!r.data._rtcWaited&&LJ(d)){r.data._rtcWaited=!0,yi(`WS first, RTC offer pending \u2192 grace 500ms (device ${s.slice(0,8)})`),setTimeout(u,500);return}let y=Qz(r,s);if(y.decision===Ir.hold&&y.step==="auth"){Dr.info(`route: awaiting TAIL proof device=${s?.slice(0,8)||"no-id"}`),g1(s,()=>u(),()=>{xv(r,s,ti.timeout)});return}switch(y.decision){case Ir.admit:if(g)return void m(g);yi(`Device admitted: ${s?.slice(0,8)}...`),SCe(r);return;case Ir.reject:{if(r.data?.tailReject)return void xv(r,s);JL(s,r.id,i),Xt(`Rejected device reconnected: ${s.slice(0,8)} \u2014 waiting in Clients list`),Em(r,"device:rejected"),kn("deviceApproval",{action:"refresh"});return}default:Dr.info(`route: hold for approval device=${s?.slice(0,8)||"no-id"}`),Xt(`Device needs approval: ${s?.slice(0,8)||"no-id"}`),f()}};u()}),nf(e,ia()),vs=e,e}var _Ce,vCe,Dr,Cgt,vs,_s,Zz,e8,yCe,t8,gx,nu=ae(()=>{RJ();_Ce=require("fs"),vCe=require("path");f0();UJ();Lt();wT();aM();TQ();Ji();es();Gr();Ic();Ha();xA();K_e();X_e();Nve();qve();E0e();XAe();ns();N0();Xz();E0();Ji();Vf();tt();hCe();gCe();mx();Dr=Se("transport");Cgt=5e3,vs=null;_s=new Map,Zz=new E1;e8=!1;yCe=t=>`rtc-${t}`,t8=t=>t.startsWith("rtc-")?t.slice(4):null,gx=(t,e)=>yT({...e,to:t});Q7(bv)});var BCe=B((vx,i8)=>{(function(t,e){typeof vx=="object"&&typeof i8=="object"?i8.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof vx=="object"?vx["electron-machine-id"]=e(require("child_process"),require("crypto")):t["electron-machine-id"]=e(t.child_process,t.crypto)})(vx,function(t,e){return(function(n){function r(s){if(i[s])return i[s].exports;var o=i[s]={exports:{},id:s,loaded:!1};return n[s].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var i={};return r.m=n,r.c=i,r.p="",r(0)})([function(n,r,i){n.exports=i(34)},function(n,r,i){var s=i(29)("wks"),o=i(33),a=i(2).Symbol,c=typeof a=="function",l=n.exports=function(u){return s[u]||(s[u]=c&&a[u]||(c?a:o)("Symbol."+u))};l.store=s},function(n,r){var i=n.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(n,r,i){var s=i(9);n.exports=function(o){if(!s(o))throw TypeError(o+" is not an object!");return o}},function(n,r,i){n.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(n,r,i){var s=i(12),o=i(17);n.exports=i(4)?function(a,c,l){return s.f(a,c,o(1,l))}:function(a,c,l){return a[c]=l,a}},function(n,r){var i=n.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(n,r,i){var s=i(14);n.exports=function(o,a,c){if(s(o),a===void 0)return o;switch(c){case 1:return function(l){return o.call(a,l)};case 2:return function(l,u){return o.call(a,l,u)};case 3:return function(l,u,d){return o.call(a,l,u,d)}}return function(){return o.apply(a,arguments)}}},function(n,r){var i={}.hasOwnProperty;n.exports=function(s,o){return i.call(s,o)}},function(n,r){n.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(n,r){n.exports={}},function(n,r){var i={}.toString;n.exports=function(s){return i.call(s).slice(8,-1)}},function(n,r,i){var s=i(3),o=i(26),a=i(32),c=Object.defineProperty;r.f=i(4)?Object.defineProperty:function(l,u,d){if(s(l),u=a(u,!0),s(d),o)try{return c(l,u,d)}catch{}if("get"in d||"set"in d)throw TypeError("Accessors not supported!");return"value"in d&&(l[u]=d.value),l}},function(n,r,i){var s=i(42),o=i(15);n.exports=function(a){return s(o(a))}},function(n,r){n.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(n,r){n.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(n,r,i){var s=i(9),o=i(2).document,a=s(o)&&s(o.createElement);n.exports=function(c){return a?o.createElement(c):{}}},function(n,r){n.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(n,r,i){var s=i(12).f,o=i(8),a=i(1)("toStringTag");n.exports=function(c,l,u){c&&!o(c=u?c:c.prototype,a)&&s(c,a,{configurable:!0,value:l})}},function(n,r,i){var s=i(29)("keys"),o=i(33);n.exports=function(a){return s[a]||(s[a]=o(a))}},function(n,r){var i=Math.ceil,s=Math.floor;n.exports=function(o){return isNaN(o=+o)?0:(o>0?s:i)(o)}},function(n,r,i){var s=i(11),o=i(1)("toStringTag"),a=s((function(){return arguments})())=="Arguments",c=function(l,u){try{return l[u]}catch{}};n.exports=function(l){var u,d,f;return l===void 0?"Undefined":l===null?"Null":typeof(d=c(u=Object(l),o))=="string"?d:a?s(u):(f=s(u))=="Object"&&typeof u.callee=="function"?"Arguments":f}},function(n,r){n.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(n,r,i){var s=i(2),o=i(6),a=i(7),c=i(5),l="prototype",u=function(d,f,m){var g,y,w,S=d&u.F,T=d&u.G,R=d&u.S,C=d&u.P,D=d&u.B,$=d&u.W,G=T?o:o[f]||(o[f]={}),V=G[l],L=T?s:R?s[f]:(s[f]||{})[l];T&&(m=f);for(g in m)y=!S&&L&&L[g]!==void 0,y&&g in G||(w=y?L[g]:m[g],G[g]=T&&typeof L[g]!="function"?m[g]:D&&y?a(w,s):$&&L[g]==w?(function(k){var E=function(A,M,I){if(this instanceof k){switch(arguments.length){case 0:return new k;case 1:return new k(A);case 2:return new k(A,M)}return new k(A,M,I)}return k.apply(this,arguments)};return E[l]=k[l],E})(w):C&&typeof w=="function"?a(Function.call,w):w,C&&((G.virtual||(G.virtual={}))[g]=w,d&u.R&&V&&!V[g]&&c(V,g,w)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,n.exports=u},function(n,r){n.exports=function(i){try{return!!i()}catch{return!0}}},function(n,r,i){n.exports=i(2).document&&document.documentElement},function(n,r,i){n.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(n,r,i){"use strict";var s=i(28),o=i(23),a=i(57),c=i(5),l=i(8),u=i(10),d=i(45),f=i(18),m=i(52),g=i(1)("iterator"),y=!([].keys&&"next"in[].keys()),w="@@iterator",S="keys",T="values",R=function(){return this};n.exports=function(C,D,$,G,V,L,k){d($,D,G);var E,A,M,I=function(J){if(!y&&J in N)return N[J];switch(J){case S:return function(){return new $(this,J)};case T:return function(){return new $(this,J)}}return function(){return new $(this,J)}},P=D+" Iterator",F=V==T,X=!1,N=C.prototype,b=N[g]||N[w]||V&&N[V],q=b||I(V),pe=V?F?I("entries"):q:void 0,oe=D=="Array"&&N.entries||b;if(oe&&(M=m(oe.call(new C)),M!==Object.prototype&&(f(M,P,!0),s||l(M,g)||c(M,g,R))),F&&b&&b.name!==T&&(X=!0,q=function(){return b.call(this)}),s&&!k||!y&&!X&&N[g]||c(N,g,q),u[D]=q,u[P]=R,V)if(E={values:F?q:I(T),keys:L?q:I(S),entries:pe},k)for(A in E)A in N||a(N,A,E[A]);else o(o.P+o.F*(y||X),D,E);return E}},function(n,r){n.exports=!0},function(n,r,i){var s=i(2),o="__core-js_shared__",a=s[o]||(s[o]={});n.exports=function(c){return a[c]||(a[c]={})}},function(n,r,i){var s,o,a,c=i(7),l=i(41),u=i(25),d=i(16),f=i(2),m=f.process,g=f.setImmediate,y=f.clearImmediate,w=f.MessageChannel,S=0,T={},R="onreadystatechange",C=function(){var $=+this;if(T.hasOwnProperty($)){var G=T[$];delete T[$],G()}},D=function($){C.call($.data)};g&&y||(g=function($){for(var G=[],V=1;arguments.length>V;)G.push(arguments[V++]);return T[++S]=function(){l(typeof $=="function"?$:Function($),G)},s(S),S},y=function($){delete T[$]},i(11)(m)=="process"?s=function($){m.nextTick(c(C,$,1))}:w?(o=new w,a=o.port2,o.port1.onmessage=D,s=c(a.postMessage,a,1)):f.addEventListener&&typeof postMessage=="function"&&!f.importScripts?(s=function($){f.postMessage($+"","*")},f.addEventListener("message",D,!1)):s=R in d("script")?function($){u.appendChild(d("script"))[R]=function(){u.removeChild(this),C.call($)}}:function($){setTimeout(c(C,$,1),0)}),n.exports={set:g,clear:y}},function(n,r,i){var s=i(20),o=Math.min;n.exports=function(a){return a>0?o(s(a),9007199254740991):0}},function(n,r,i){var s=i(9);n.exports=function(o,a){if(!s(o))return o;var c,l;if(a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o))||typeof(c=o.valueOf)=="function"&&!s(l=c.call(o))||!a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o)))return l;throw TypeError("Can't convert object to primitive value")}},function(n,r){var i=0,s=Math.random();n.exports=function(o){return"Symbol(".concat(o===void 0?"":o,")_",(++i+s).toString(36))}},function(n,r,i){"use strict";function s(R){return R&&R.__esModule?R:{default:R}}function o(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function a(R){return(0,g.createHash)("sha256").update(R).digest("hex")}function c(R){switch(w){case"darwin":return R.split("IOPlatformUUID")[1].split(`
532
- `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return R.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(R){var C=c((0,m.execSync)(T[w]).toString());return R?C:a(C)}function u(R){return new f.default(function(C,D){return(0,m.exec)(T[w],{},function($,G,V){if($)return D(new Error("Error while obtaining machine id: "+$.stack));var L=c(G.toString());return C(R?L:a(L))})})}Object.defineProperty(r,"__esModule",{value:!0});var d=i(35),f=s(d);r.machineIdSync=l,r.machineId=u;var m=i(70),g=i(71),y=process,w=y.platform,S={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},T={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:S[o()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(n,r,i){n.exports={default:i(36),__esModule:!0}},function(n,r,i){i(66),i(68),i(69),i(67),n.exports=i(6).Promise},function(n,r){n.exports=function(){}},function(n,r){n.exports=function(i,s,o,a){if(!(i instanceof s)||a!==void 0&&a in i)throw TypeError(o+": incorrect invocation!");return i}},function(n,r,i){var s=i(13),o=i(31),a=i(62);n.exports=function(c){return function(l,u,d){var f,m=s(l),g=o(m.length),y=a(d,g);if(c&&u!=u){for(;g>y;)if(f=m[y++],f!=f)return!0}else for(;g>y;y++)if((c||y in m)&&m[y]===u)return c||y||0;return!c&&-1}}},function(n,m,i){var s=i(7),o=i(44),a=i(43),c=i(3),l=i(31),u=i(64),d={},f={},m=n.exports=function(g,y,w,S,T){var R,C,D,$,G=T?function(){return g}:u(g),V=s(w,S,y?2:1),L=0;if(typeof G!="function")throw TypeError(g+" is not iterable!");if(a(G)){for(R=l(g.length);R>L;L++)if($=y?V(c(C=g[L])[0],C[1]):V(g[L]),$===d||$===f)return $}else for(D=G.call(g);!(C=D.next()).done;)if($=o(D,V,C.value,y),$===d||$===f)return $};m.BREAK=d,m.RETURN=f},function(n,r){n.exports=function(i,s,o){var a=o===void 0;switch(s.length){case 0:return a?i():i.call(o);case 1:return a?i(s[0]):i.call(o,s[0]);case 2:return a?i(s[0],s[1]):i.call(o,s[0],s[1]);case 3:return a?i(s[0],s[1],s[2]):i.call(o,s[0],s[1],s[2]);case 4:return a?i(s[0],s[1],s[2],s[3]):i.call(o,s[0],s[1],s[2],s[3])}return i.apply(o,s)}},function(n,r,i){var s=i(11);n.exports=Object("z").propertyIsEnumerable(0)?Object:function(o){return s(o)=="String"?o.split(""):Object(o)}},function(n,r,i){var s=i(10),o=i(1)("iterator"),a=Array.prototype;n.exports=function(c){return c!==void 0&&(s.Array===c||a[o]===c)}},function(n,r,i){var s=i(3);n.exports=function(o,a,c,l){try{return l?a(s(c)[0],c[1]):a(c)}catch(d){var u=o.return;throw u!==void 0&&s(u.call(o)),d}}},function(n,r,i){"use strict";var s=i(49),o=i(17),a=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),n.exports=function(l,u,d){l.prototype=s(c,{next:o(1,d)}),a(l,u+" Iterator")}},function(n,r,i){var s=i(1)("iterator"),o=!1;try{var a=[7][s]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch{}n.exports=function(c,l){if(!l&&!o)return!1;var u=!1;try{var d=[7],f=d[s]();f.next=function(){return{done:u=!0}},d[s]=function(){return f},c(d)}catch{}return u}},function(n,r){n.exports=function(i,s){return{value:s,done:!!i}}},function(n,r,i){var s=i(2),o=i(30).set,a=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,u=i(11)(c)=="process";n.exports=function(){var d,f,m,g=function(){var T,R;for(u&&(T=c.domain)&&T.exit();d;){R=d.fn,d=d.next;try{R()}catch(C){throw d?m():f=void 0,C}}f=void 0,T&&T.enter()};if(u)m=function(){c.nextTick(g)};else if(a){var y=!0,w=document.createTextNode("");new a(g).observe(w,{characterData:!0}),m=function(){w.data=y=!y}}else if(l&&l.resolve){var S=l.resolve();m=function(){S.then(g)}}else m=function(){o.call(s,g)};return function(T){var R={fn:T,next:void 0};f&&(f.next=R),d||(d=R,m()),f=R}}},function(n,r,i){var s=i(3),o=i(50),a=i(22),c=i(19)("IE_PROTO"),l=function(){},u="prototype",d=function(){var f,m=i(16)("iframe"),g=a.length,y=">";for(m.style.display="none",i(25).appendChild(m),m.src="javascript:",f=m.contentWindow.document,f.open(),f.write("<script>document.F=Object</script"+y),f.close(),d=f.F;g--;)delete d[u][a[g]];return d()};n.exports=Object.create||function(f,m){var g;return f!==null?(l[u]=s(f),g=new l,l[u]=null,g[c]=f):g=d(),m===void 0?g:o(g,m)}},function(n,r,i){var s=i(12),o=i(3),a=i(54);n.exports=i(4)?Object.defineProperties:function(c,l){o(c);for(var u,d=a(l),f=d.length,m=0;f>m;)s.f(c,u=d[m++],l[u]);return c}},function(n,r,i){var s=i(55),o=i(17),a=i(13),c=i(32),l=i(8),u=i(26),d=Object.getOwnPropertyDescriptor;r.f=i(4)?d:function(f,m){if(f=a(f),m=c(m,!0),u)try{return d(f,m)}catch{}if(l(f,m))return o(!s.f.call(f,m),f[m])}},function(n,r,i){var s=i(8),o=i(63),a=i(19)("IE_PROTO"),c=Object.prototype;n.exports=Object.getPrototypeOf||function(l){return l=o(l),s(l,a)?l[a]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(n,r,i){var s=i(8),o=i(13),a=i(39)(!1),c=i(19)("IE_PROTO");n.exports=function(l,u){var d,f=o(l),m=0,g=[];for(d in f)d!=c&&s(f,d)&&g.push(d);for(;u.length>m;)s(f,d=u[m++])&&(~a(g,d)||g.push(d));return g}},function(n,r,i){var s=i(53),o=i(22);n.exports=Object.keys||function(a){return s(a,o)}},function(n,r){r.f={}.propertyIsEnumerable},function(n,r,i){var s=i(5);n.exports=function(o,a,c){for(var l in a)c&&o[l]?o[l]=a[l]:s(o,l,a[l]);return o}},function(n,r,i){n.exports=i(5)},function(n,r,i){var s=i(9),o=i(3),a=function(c,l){if(o(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};n.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,u){try{u=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),u(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(d,f){return a(d,f),l?d.__proto__=f:u(d,f),d}})({},!1):void 0),check:a}},function(n,r,i){"use strict";var s=i(2),o=i(6),a=i(12),c=i(4),l=i(1)("species");n.exports=function(u){var d=typeof o[u]=="function"?o[u]:s[u];c&&d&&!d[l]&&a.f(d,l,{configurable:!0,get:function(){return this}})}},function(n,r,i){var s=i(3),o=i(14),a=i(1)("species");n.exports=function(c,l){var u,d=s(c).constructor;return d===void 0||(u=s(d)[a])==null?l:o(u)}},function(n,r,i){var s=i(20),o=i(15);n.exports=function(a){return function(c,l){var u,d,f=String(o(c)),m=s(l),g=f.length;return m<0||m>=g?a?"":void 0:(u=f.charCodeAt(m),u<55296||u>56319||m+1===g||(d=f.charCodeAt(m+1))<56320||d>57343?a?f.charAt(m):u:a?f.slice(m,m+2):(u-55296<<10)+(d-56320)+65536)}}},function(n,r,i){var s=i(20),o=Math.max,a=Math.min;n.exports=function(c,l){return c=s(c),c<0?o(c+l,0):a(c,l)}},function(n,r,i){var s=i(15);n.exports=function(o){return Object(s(o))}},function(n,r,i){var s=i(21),o=i(1)("iterator"),a=i(10);n.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[o]||c["@@iterator"]||a[s(c)]}},function(n,r,i){"use strict";var s=i(37),o=i(47),a=i(10),c=i(13);n.exports=i(27)(Array,"Array",function(l,u){this._t=c(l),this._i=0,this._k=u},function(){var l=this._t,u=this._k,d=this._i++;return!l||d>=l.length?(this._t=void 0,o(1)):u=="keys"?o(0,d):u=="values"?o(0,l[d]):o(0,[d,l[d]])},"values"),a.Arguments=a.Array,s("keys"),s("values"),s("entries")},function(n,r){},function(n,r,i){"use strict";var s,o,a,c=i(28),l=i(2),u=i(7),d=i(21),f=i(23),m=i(9),g=(i(3),i(14)),y=i(38),w=i(40),S=(i(58).set,i(60)),T=i(30).set,R=i(48)(),C="Promise",D=l.TypeError,G=l.process,$=l[C],G=l.process,V=d(G)=="process",L=function(){},k=!!(function(){try{var oe=$.resolve(1),J=(oe.constructor={})[i(1)("species")]=function(ve){ve(L,L)};return(V||typeof PromiseRejectionEvent=="function")&&oe.then(L)instanceof J}catch{}})(),E=function(oe,J){return oe===J||oe===$&&J===a},A=function(oe){var J;return!(!m(oe)||typeof(J=oe.then)!="function")&&J},M=function(oe){return E($,oe)?new I(oe):new o(oe)},I=o=function(oe){var J,ve;this.promise=new oe(function(we,xe){if(J!==void 0||ve!==void 0)throw D("Bad Promise constructor");J=we,ve=xe}),this.resolve=g(J),this.reject=g(ve)},P=function(oe){try{oe()}catch(J){return{error:J}}},F=function(oe,J){if(!oe._n){oe._n=!0;var ve=oe._c;R(function(){for(var we=oe._v,xe=oe._s==1,lt=0,Ue=function(U){var K,j,Q=xe?U.ok:U.fail,Z=U.resolve,ee=U.reject,ie=U.domain;try{Q?(xe||(oe._h==2&&b(oe),oe._h=1),Q===!0?K=we:(ie&&ie.enter(),K=Q(we),ie&&ie.exit()),K===U.promise?ee(D("Promise-chain cycle")):(j=A(K))?j.call(K,Z,ee):Z(K)):ee(we)}catch(ne){ee(ne)}};ve.length>lt;)Ue(ve[lt++]);oe._c=[],oe._n=!1,J&&!oe._h&&X(oe)})}},X=function(oe){T.call(l,function(){var J,ve,we,xe=oe._v;if(N(oe)&&(J=P(function(){V?G.emit("unhandledRejection",xe,oe):(ve=l.onunhandledrejection)?ve({promise:oe,reason:xe}):(we=l.console)&&we.error&&we.error("Unhandled promise rejection",xe)}),oe._h=V||N(oe)?2:1),oe._a=void 0,J)throw J.error})},N=function(oe){if(oe._h==1)return!1;for(var J,ve=oe._a||oe._c,we=0;ve.length>we;)if(J=ve[we++],J.fail||!N(J.promise))return!1;return!0},b=function(oe){T.call(l,function(){var J;V?G.emit("rejectionHandled",oe):(J=l.onrejectionhandled)&&J({promise:oe,reason:oe._v})})},q=function(oe){var J=this;J._d||(J._d=!0,J=J._w||J,J._v=oe,J._s=2,J._a||(J._a=J._c.slice()),F(J,!0))},pe=function(oe){var J,ve=this;if(!ve._d){ve._d=!0,ve=ve._w||ve;try{if(ve===oe)throw D("Promise can't be resolved itself");(J=A(oe))?R(function(){var we={_w:ve,_d:!1};try{J.call(oe,u(pe,we,1),u(q,we,1))}catch(xe){q.call(we,xe)}}):(ve._v=oe,ve._s=1,F(ve,!1))}catch(we){q.call({_w:ve,_d:!1},we)}}};k||($=function(oe){y(this,$,C,"_h"),g(oe),s.call(this);try{oe(u(pe,this,1),u(q,this,1))}catch(J){q.call(this,J)}},s=function(oe){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)($.prototype,{then:function(oe,J){var ve=M(S(this,$));return ve.ok=typeof oe!="function"||oe,ve.fail=typeof J=="function"&&J,ve.domain=V?G.domain:void 0,this._c.push(ve),this._a&&this._a.push(ve),this._s&&F(this,!1),ve.promise},catch:function(oe){return this.then(void 0,oe)}}),I=function(){var oe=new s;this.promise=oe,this.resolve=u(pe,oe,1),this.reject=u(q,oe,1)}),f(f.G+f.W+f.F*!k,{Promise:$}),i(18)($,C),i(59)(C),a=i(6)[C],f(f.S+f.F*!k,C,{reject:function(oe){var J=M(this),ve=J.reject;return ve(oe),J.promise}}),f(f.S+f.F*(c||!k),C,{resolve:function(oe){if(oe instanceof $&&E(oe.constructor,this))return oe;var J=M(this),ve=J.resolve;return ve(oe),J.promise}}),f(f.S+f.F*!(k&&i(46)(function(oe){$.all(oe).catch(L)})),C,{all:function(oe){var J=this,ve=M(J),we=ve.resolve,xe=ve.reject,lt=P(function(){var Ue=[],U=0,K=1;w(oe,!1,function(j){var Q=U++,Z=!1;Ue.push(void 0),K++,J.resolve(j).then(function(ee){Z||(Z=!0,Ue[Q]=ee,--K||we(Ue))},xe)}),--K||we(Ue)});return lt&&xe(lt.error),ve.promise},race:function(oe){var J=this,ve=M(J),we=ve.reject,xe=P(function(){w(oe,!1,function(lt){J.resolve(lt).then(ve.resolve,we)})});return xe&&we(xe.error),ve.promise}})},function(n,r,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(o){this._t=String(o),this._i=0},function(){var o,a=this._t,c=this._i;return c>=a.length?{value:void 0,done:!0}:(o=s(a,c),this._i+=o.length,{value:o,done:!1})})},function(n,r,i){i(65);for(var s=i(2),o=i(5),a=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],u=0;u<5;u++){var d=l[u],f=s[d],m=f&&f.prototype;m&&!m[c]&&o(m,c,d),a[d]=a.Array}},function(n,r){n.exports=require("child_process")},function(n,r){n.exports=require("crypto")}])})});var fyt={};yr(fyt,{startServer:()=>GRe});module.exports=UIe(fyt);var A1=require("http"),wm=require("child_process"),ji=require("fs"),nn=require("path"),C1=require("url");Rr();aM();Lt();tt();nu();n2();gj();Ha();Lq();Vf();Ic();async function MCe(t,e){let n=t.headers.authorization;if(!n||!n.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let r=n.slice(7);if(!h1(r,Zi()?.key)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await TR();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}Vf();wT();var LCe=require("url");var x1=ce(require("path"),1),UCe=ce(require("os"),1);Lt();var NCe=ce(require("path"),1),DCe=ce(require("os"),1);var BDt=NCe.default.join(DCe.default.homedir(),".9remote","pids");aL();Rp();tt();var YDt=Se("update"),XDt=x1.default.dirname((0,LCe.fileURLToPath)(__importMetaUrl));var JDt=x1.default.join(UCe.default.homedir(),".9remote","cloudflared.pid");function FCe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}var QDt=x1.default.join(Oe.STATE,l0.lockFile);ns();Ha();Rp();Rr();Ic();Vf();var qCe=ce(BCe(),1),s8=ce(require("crypto"),1),{machineIdSync:Lgt}=qCe.default;async function $Ce(t=null){let e=t||process.env.MACHINE_ID_SALT||"9remote-salt";try{let n=Lgt();return s8.default.createHash("sha256").update(n+e).digest("hex").substring(0,16)}catch(n){return console.error("Error getting machine ID:",n),s8.default.randomUUID().replace(/-/g,"").substring(0,16)}}ns();Lt();tt();E0();Vf();Bz();var o8=Se("session"),Ugt=10;async function GCe(t,e){let n=async()=>{let r=await mc(`${e}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{let i={apiKey:Dn(t),expiryMinutes:Ugt};return{...i,...kT(i)}})())});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error||`HTTP ${r.status}`)}return r.json()};try{let r;try{r=await n()}catch(s){if(o8.warn(`Temp key creation failed (${s.message}) \u2014 re-registering session`),!await a8(t,e))throw s;r=await n()}let i=eCe();return nCe(r.tempKey,i,r.expiresAt,e),{...r,oneTimeKey:`${r.tempKey}${i}`}}catch(r){return o8.error(`Temp key creation failed: ${r?.message||r}`),null}}function HCe(t,e){return e?.tempKey?`${t}/login?k=${e.tempKey}#${e.oneTimeKey}`:`${t}/login`}async function a8(t,e,n,r){try{let i=await mc(`${e}/api/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(t),hostPublicKey:RT(),hostX25519Key:IT(),tempKey:dx()?.tempKey||void 0})});if(!i.ok)throw new Error(`HTTP ${i.status}`);return n&&await mc(`${e}/api/session/update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(t),tunnelUrl:n,...kT({apiKey:Dn(t),tunnelUrl:n})})}).catch(()=>{}),r&&Dn(r)!==Dn(t)&&await mc(`${e}/api/session/delete`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(r),...kT({apiKey:Dn(r)})})}).catch(()=>{}),!0}catch(i){return o8.error(`Session registration failed: ${i?.message||i}`),!1}}f0();Vf();Rp();function c8(t){return Pp().remoteEnabled!==!1?!1:(Ze(t,409,"Remote access is off"),!0)}async function jCe(t,e){if(c8(e))return;let n=VT(),r=n.workerUrl||wc;if(!n.permanentKey){Ze(e,400,"No permanent key set");return}let i=await GCe(n.permanentKey,r);if(!i){Ze(e,500,"Temp key creation failed");return}let s=HCe(r,i);kc({oneTimeKey:i.oneTimeKey,oneTimeKeyExpiresAt:i.expiresAt,qrUrl:s}),Me(e,{oneTimeKey:i.oneTimeKey,expiresAt:i.expiresAt,qrUrl:s})}async function WCe(t,e){c8(e)||(_T("session-registered"),Me(e,vT()))}async function VCe(t,e){if(!c8(e))try{let n=VT(),r=n.workerUrl||wc,i=await $Ce(),s=sCe(i),o=Zi();if(!await a8(s,r,n.tunnelUrl,o?.key)){Ze(e,502,"Could not register the new key with the server");return}D7(i,s,o?.name||"Default"),Sg(Dn(s)),kc({permanentKey:s,oneTimeKey:"",oneTimeKeyExpiresAt:null,qrUrl:"",pairingUsed:!0}),Me(e,{ok:!0,permanentKey:s})}catch(n){Ze(e,500,n.message)}}Rr();nu();N0();async function zCe(t,e){let n=await _r(t,e);if(!n)return;let r=ACe(n.socketId);Me(e,{ok:r})}async function KCe(t,e){let n=await _r(t,e);if(!n)return;let r=RCe(n.socketId);Me(e,{ok:r})}function YCe(t,e){Me(e,{pending:EQ()})}function XCe(t,e){Me(e,{devices:_Q()})}function JCe(t,e){Me(e,{rejected:SQ()})}async function QCe(t,e){let n=await _r(t,e);if(!n)return;let r=CCe(n.deviceId);Me(e,{ok:r})}async function ZCe(t,e){let n=await _r(t,e);n&&(S1(n.deviceId),jg(n.deviceId),Me(e))}async function eRe(t,e){let n=await _r(t,e);n&&(S1(n.deviceId),mQ(n.deviceId),Me(e))}async function tRe(t,e){let n=await _r(t,e);if(!n)return;pQ(n.deviceId);let r=S1(n.deviceId);Me(e,{disconnected:r})}function nRe(t,e){Me(e,{enabled:QL()})}async function rRe(t,e){let n=await _r(t,e);if(!n)return;let r=gQ(n.deviceId,n.label);Me(e,{ok:r})}async function iRe(t,e){let n=await _r(t,e);if(!n)return;let r=bQ(!!n.enabled);Me(e,{enabled:r})}Rr();nu();es();xR();Fs();Fc();d2();Nz();var sRe={},Fgt=1e4;function Bgt(t,e){if(e?.csid&&qd.test(e.csid))return e.csid;let{sessionId:n,...r}=e||{};return lne(t,r)}function aRe(t,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"",csid:e.csid||"",...e};let n=JSON.parse(t||"{}");return{type:n.type||"stop",sessionId:n.sessionId||"",tool:n.tool||"",csid:n.csid||"",...n}}async function cRe(t,e){let n="";await new Promise(r=>{t.on("data",i=>n+=i),t.on("end",r)});try{uRe(aRe(n,null)),Me(e,{success:!0})}catch{Ze(e,400,"Invalid JSON")}}function lRe(t,e,{query:n}){uRe(aRe(null,n)),Me(e,{success:!0})}function oRe(t,e,n){let{type:r,sessionId:i,tool:s}=t,o={type:r,sessionId:i,tool:s,timestamp:n},c=nh({type:r,sessionId:i,tool:s})?.state||Jt.IDLE,l=ss(i);if(nt(e,"statusChange",{sessionId:i,state:c,tool:s,since:n,...l?{conversationId:l.id}:{}}),bF(i,o),nt(e,"chatNotification",o),(c===Jt.DONE||c===Jt.BLOCKED)&&KA(i),(c===Jt.DONE||c===Jt.BLOCKED)&&Mz(i),c!==Jt.DONE&&c!==Jt.BLOCKED)return;let u=`${i}:${c}`;n-(sRe[u]||0)<Fgt||(sRe[u]=n,ace({...o,state:c}))}function uRe(t){let{type:e,sessionId:n,tool:r}=t,i=Date.now(),s=Ya();if(!s||!n)return;let o=Bgt(r,t);if(o&&Da(n,r,o,"hook"),VA[e]===Jt.DONE){XA(n,()=>oRe(t,s,Date.now()));return}oRe(t,s,i)}Rr();s2();UR();Lt();var l8=ce(require("fs"),1),b1=ce(require("path"),1);nu();es();yh();Ha();var qgt=process.platform==="darwin"||process.platform==="win32",dRe=t=>qgt?t.toLowerCase():t,fRe=(t,e)=>{let n=dRe(t),r=dRe(e);return n===r||n.startsWith(r+b1.default.sep)},pRe=t=>[t.cwd,t.workspacePath].filter(Boolean);function $gt(t,e,n){if(e&&n.some(s=>s.id===e))return e;let r=null,i=-1;for(let s of n)for(let o of pRe(s))fRe(t,o)&&o.length>i&&(r=s.id,i=o.length);return r}function hRe({path:t,title:e},n=null){if(!t||typeof t!="string")return{error:"path is required"};let r=b1.default.resolve(t);try{r=l8.default.realpathSync(r)}catch{return{error:"File not found"}}if(wt(r))return{error:"Access denied"};if(!l8.default.statSync(r).isFile())return{error:"Not a file"};let i=_u(),s=i.filter(c=>pRe(c).some(l=>fRe(r,l)));if(n&&i.some(c=>c.id===n)&&!s.some(c=>c.id===n))return{error:"File is outside this terminal's workspace"};if(!s.length)return{error:"File is outside every open terminal's workspace"};let o=Ya();if(!o)return{error:"Server not ready"};let a=$gt(r,n,s);return nt(o,"artifactOpen",{path:r,title:e||b1.default.basename(r),sessionId:a}),{path:r}}var Ggt={name:"openArtifact",description:"Show a file you just created or edited in the 9Remote app, sliding it in beside the terminal. Use it for files worth looking at \u2014 html, markdown, svg, images, pdf, csv, diagrams, code. Skip files with nothing to see. The user closes it themselves.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the file."},title:{type:"string",description:"Optional label for the panel header."}},required:["path"]},run({path:t,title:e},n){let r=hRe({path:t,title:e},n?.sessionId);return r.error?r:`Opened ${r.path}`}},mRe=Ggt;hS();Fj();var Hgt=500;function jgt(t={applyAction:F_}){return{name:"report_task",description:"Report what you just finished, in one or two sentences. It lands on this session's card on the kanban board the user watches, so progress is visible without reading your terminal. Call it when a chunk of work completes, and again with status when your own state changes (todo | in_progress | needs_input | done). While a turn of yours is actually running, the live state wins \u2014 the self-report takes effect when you go idle.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"1-2 sentences of what was done or what changed"},status:{type:"string",enum:Uj,description:"Optional self-reported status; live turn state still wins while running"}},required:["summary"]},async run({summary:e,status:n}={},r={}){let i=String(e||"").trim().slice(0,Hgt);if(!i)return{error:"summary is required"};let s=r?.sessionId;if(!s)return{error:"no session identity; cannot tell which card is yours"};let{error:o}=await t.applyAction({type:"report",sessionId:s,summary:i,...n?{status:n}:{}});return o?{error:o}:"reported"}}}var gRe=jgt();Yk();var yRe=[mRe],_Re=new Map([...yRe,...Cf,gRe].map(t=>[t.name,t])),vRe=()=>yRe.map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,inputSchema:n}));var T1=(t,e=!1)=>({content:[{type:"text",text:t}],isError:e});async function Wgt(t,e,n){let r=_Re.get(t);if(!r)return T1(`Unknown tool: ${t}`,!0);try{let i=await r.run(e||{},n||{});return i?.error?T1(i.error,!0):T1(typeof i=="string"?i:JSON.stringify(i))}catch(i){return T1(i.message,!0)}}async function ERe(t,e){let{id:n,method:r,params:i}=t||{},s=o=>({jsonrpc:"2.0",id:n,result:o});return r==="initialize"?s({protocolVersion:i?.protocolVersion||Pl.PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:{name:Pl.SERVER_NAME,version:"3.0.24"}}):r==="tools/list"?s({tools:vRe()}):r==="tools/call"?s(await Wgt(i?.name,i?.arguments,e)):r==="ping"?s({}):n==null?null:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${r}`}}}var d8=ce(require("fs"),1),SRe=require("child_process");tt();r2();var Vgt=Se("artifact"),wRe=/(?:^|[\s\0])NINE_REMOTE_SESSION_ID=([^\s\0]+)/,u8=new WeakMap,f8=(t,e)=>(0,SRe.execFileSync)(t,e,{encoding:"utf8",timeout:Wy.PROBE_TIMEOUT_MS,stdio:["ignore","pipe","ignore"]});function zgt(t,e){let n=f8("lsof",["-nP",`-iTCP:${t}`,"-Fpn"]),r=null;for(let i of n.split(`
533
- `))if(i[0]==="p")r=parseInt(i.slice(1),10);else if(i[0]==="n"&&r&&r!==e){let s=i.match(/^n(?:\[[^\]]+\]|[^:]+):(\d+)->/);if(s&&Number(s[1])===t)return r}return null}function Kgt(t){try{return process.platform==="linux"?d8.default.readFileSync(`/proc/${t}/environ`,"utf8").match(wRe)?.[1]||null:f8("ps",["-Eww","-o","command=","-p",String(t)]).match(wRe)?.[1]||null}catch{return null}}function Ygt(t){try{if(process.platform==="linux"){let e=d8.default.readFileSync(`/proc/${t}/stat`,"utf8");return parseInt(e.slice(e.lastIndexOf(")")+2).split(" ")[1],10)||null}return parseInt(f8("ps",["-o","ppid=","-p",String(t)]).trim(),10)||null}catch{return null}}function Xgt(t){for(let e=0;t>1&&t!==process.pid&&e<Wy.MAX_PARENT_HOPS;e++){let n=Kgt(t);if(n)return n;if(t=Ygt(t),!t)return null}return null}function xRe(t){let e=t?.headers?.[Wy.HEADER];if(e&&!/[${}]/.test(e))return e;let n=t?.socket;if(!n)return null;if(u8.has(n))return u8.get(n);let r=null;try{let i=zgt(n.remotePort,process.pid);i&&(r=Xgt(i))}catch(i){Vgt.warn(`caller probe failed: ${i.message}`)}return u8.set(n,r),r}async function bRe(t,e){if(!ale(t.headers.authorization))return Ze(e,401,"Unauthorized");if(!tw())return Ze(e,403,"MCP is turned off in 9Remote settings");let n=await _r(t,e);if(n===null&&!e.writableEnded)return Ze(e,400,"Invalid request");if(e.writableEnded)return;let r;try{r=await ERe(n,{sessionId:xRe(t)})}catch(i){r={jsonrpc:"2.0",id:n?.id??null,error:{code:-32603,message:i.message}}}if(!r)return e.writeHead(202),e.end();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(r))}Rr();GT();Ic();Gr();ns();function TRe(){return{mode:mL(),active:hL(),presets:Object.keys(Te.sleepInhibit?.presets||{})}}function ARe(t,e){Me(e,TRe())}async function CRe(t,e){let n=await _r(t,e);if(!n)return;let r=I0(n.mode);MT({sleepInhibitMode:r});let i=TRe();kn("sleepInhibit",i),Me(e,i)}Rr();Ic();nu();ns();function RRe(t){return{enabled:t}}function IRe(t,e){Me(e,RRe(Sv()))}async function kRe(t,e){let n=await _r(t,e);if(!n)return;if(typeof n.enabled!="boolean")return Ze(e,400,"enabled must be a boolean");MT({remoteEnabled:n.enabled}),PCe(n.enabled),Aa(n.enabled?"start-tunnel":"stop-tunnel");let r=RRe(n.enabled);kn("remote",r),Me(e,r)}Rr();mU();async function PRe(t,e){let n=await dA();Me(e,n)}async function ORe(t,e){let n=await rZ(),r=await dA();Me(e,{...n,...r})}async function MRe(t,e){let n=await _r(t,e);if(!n)return;if(typeof n.text!="string"||!n.text){Ze(e,400,"Missing text");return}let r=await $0(n.text);Me(e,{ok:r.ok,reason:r.reason||null})}async function NRe(t,e){let n=await nZ(),r=await dA();Me(e,{...n,...r})}_i();Rr();async function DRe(t,e){try{let n=await Rd();Me(e,{sessions:n})}catch(n){Ze(e,500,n.message)}}async function LRe(t,e){let n=await _r(t,e);if(n){if(!n.sessionId)return Ze(e,400,"sessionId required");try{await Id(n.sessionId),Me(e)}catch(r){Ze(e,500,r.message)}}}var Yu=ce(require("os"),1);Gr();xA();Rr();function Jgt(){let t=VZ();if(!t?.activeClients)return{total:0,streaming:0};let e=0;for(let n of t.activeClients.values())n.isStreaming&&e++;return{total:t.activeClients.size,streaming:e}}function Qgt(){let t=process.memoryUsage(),e=Yu.default.cpus();return{agent:{pid:process.pid,version:"3.0.24",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(t.heapUsed/1048576*10)/10,heapTotalMB:Math.round(t.heapTotal/1048576*10)/10,rssMB:Math.round(t.rss/1048576*10)/10,externalMB:Math.round(t.external/1048576*10)/10}},os:{hostname:Yu.default.hostname(),platform:Yu.default.platform(),arch:Yu.default.arch(),uptimeSec:Math.round(Yu.default.uptime()),loadAvg:Yu.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(Yu.default.totalmem()/1048576),freeMemMB:Math.round(Yu.default.freemem()/1048576)},remote:{available:SA(),...Jgt(),memoryWarningThresholdMB:Te.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function URe(t,e){try{Me(e,Qgt())}catch(n){Ze(e,500,"stats error",n.message)}}GT();Ic();Gr();sK();SK();var so=Se("server"),sa=(0,C1.fileURLToPath)(new URL(".",__importMetaUrl)),qRe=process.env.NODE_ENV==="development",Zgt=5173,p8=[(0,nn.join)(sa,"dist","ui"),(0,nn.join)(sa,"ui","dist"),(0,nn.join)(sa,"ui")].find(t=>(0,ji.existsSync)(t))||(0,nn.join)(sa,"dist","ui"),lc=[(0,nn.join)(sa,"dist","web"),(0,nn.join)(sa,"web"),(0,nn.join)(sa,"..","web","out")].find(t=>(0,ji.existsSync)(t))||p8,eyt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".txt":"text/x-component; charset=utf-8",".webmanifest":"application/manifest+json"};function tyt(t,e,n){let r=(0,A1.request)({hostname:"localhost",port:Zgt,path:t.url,method:t.method,headers:t.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});r.on("error",()=>n?n():void(e.writeHead(502),e.end("Vite dev server not ready"))),t.pipe(r)}function nyt(t,e){let n;try{n=(0,C1.parse)(t.url).pathname}catch{Ze(e,400,"Bad request");return}let r=vK(n,t.headers.host);if(!r){Ze(e,404,"Not found");return}for(let[i,s]of Object.entries(r.headers))e.setHeader(i,s);Es(e,(0,nn.join)(lc,r.path),{frameable:!0})||Ze(e,404,"Not found")}function Es(t,e,{frameable:n=!1}={}){if(!(0,ji.existsSync)(e))return!1;try{if((0,ji.statSync)(e).isDirectory()){let a=(0,nn.join)(e,"index.html");return(0,ji.existsSync)(a)?Es(t,a,{frameable:n}):!1}let i=(0,nn.extname)(e),s=eyt[i]||"application/octet-stream";t.setHeader("Content-Type",s),i===".html"&&!n&&t.setHeader("X-Frame-Options","SAMEORIGIN");let o=e.includes(`${nn.sep}_next${nn.sep}static${nn.sep}`);return t.hasHeader("Cache-Control")||t.setHeader("Cache-Control",o?"public, max-age=31536000, immutable":"no-cache"),t.writeHead(200),t.end((0,ji.readFileSync)(e)),!0}catch{return!1}}async function h8(t){try{let e=await mc(iM);if(!e.ok)return;let{version:n}=await e.json();if(n&&FCe(t,n)){YT({version:n}),kn("updateAvailable",{version:n}),WR();return}k0()&&(YT(null),WR())}catch{}}var FRe=0;function ryt(t){let e=Date.now();e-FRe<l0.connectCheckDebounceMs||(FRe=e,h8(t))}function iyt(t,e){if(process.env.CODESPACES!=="true"){Ze(e,400,"Not running on Codespaces");return}let n=process.env.CODESPACE_NAME;if(!n){Ze(e,400,"Codespace name not found");return}let r=Ya();r&&r.emit("codespace:stopping"),Me(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,wm.execFile)("gh",["codespace","stop","-c",n],{windowsHide:!0}),500)}async function syt(t,e){let{parseJsonBody:n}=await Promise.resolve().then(()=>(Rr(),ud)),r=await n(t,e);if(!r)return;let{verifyPresentedTail:i}=await Promise.resolve().then(()=>(Xz(),dCe)),s=i({tail:r.tail,tempKey:r.tempKey});if(s.ok){Me(e,{ok:!0});return}let o=t.headers["x-forwarded-for"]||t.socket?.remoteAddress||"unknown";if(r.tempKey&&r.tail)if(s.burned){so.warn(`wrong one-time code TAIL (${o}) \u2014 code burned, clearing from UI`);let{clearOneTimeKey:a}=await Promise.resolve().then(()=>(ns(),HL));a()}else so.warn(`stale one-time code TAIL (${o}) \u2014 code still live`);else r.tempKey?so.warn(`wrong one-time code TAIL (${o}) \u2014 no TAIL presented, code still live`):so.warn(`wrong API-key TAIL (${o}) \u2014 rejected`);setTimeout(()=>Me(e,{ok:!1,reason:s.reason}),s.penaltyMs||0)}var $Re;async function BRe(t,e,{pathname:n}){let r=t.headers.authorization;if(!r||!r.startsWith("Bearer ")||!h1(r.slice(7),Zi()?.key)){Ze(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Rr(),ud)),s=await i(t,e);if(!s)return;if(!s.port){Ze(e,400,"Port required");return}if(!n.endsWith("start")){PR(s.port),Me(e,{success:!0});return}let o=kR(s.port);if(!o){Ze(e,400,"Invalid port");return}Me(e,{success:!0,sessionId:o})}function oyt(t,e,{pathname:n,search:r}){let i=n.match(/^\/proxy\/([0-9a-f-]{36})(\/.*)?$/);i?ile($Re,t,e,i[1],i[2]||"/",r):Ze(e,404,"Not found")}function ayt(t,e,n){W_e(t,e,n)}var cyt=[{path:"/api/health",method:"GET",public:!0,handler:(t,e)=>Me(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(t,e)=>{let n="3.0.24";e.setHeader("Cache-Control","no-store"),Me(e,{version:n})}},{path:"/api/notify",method:"POST",public:!0,handler:cRe},{path:"/api/notify",method:"GET",public:!0,handler:lRe},{path:"/proxy/*",method:"*",public:!0,handler:oyt},{path:"/preview/*",method:"GET",public:!0,handler:ayt},{path:"/api/ui/events",method:"GET",handler:CL},{path:"/api/local-token",method:"GET",handler:bL},{path:Pl.PATH,method:"POST",handler:bRe},{path:"/api/ui/state",method:"GET",handler:RL},{path:"/api/ui/state",method:"POST",handler:IL},{path:"/api/ui/stop",method:"POST",handler:kL},{path:"/api/ui/start",method:"POST",handler:PL},{path:"/api/ui/stop-tunnel",method:"POST",handler:OL},{path:"/api/ui/shutdown",method:"POST",handler:ML},{path:"/api/update",method:"POST",handler:NL},{path:"/api/system/stats",method:"GET",handler:URe},{path:"/api/key/one-time",method:"POST",handler:jCe},{path:"/api/key/regenerate",method:"POST",handler:VCe},{path:"/api/signaling/retry",method:"POST",handler:WCe},{path:"/api/device/approve",method:"POST",handler:zCe},{path:"/api/device/reject",method:"POST",handler:KCe},{path:"/api/device/pending",method:"GET",handler:YCe},{path:"/api/device/approved",method:"GET",handler:XCe},{path:"/api/device/rejected",method:"GET",handler:JCe},{path:"/api/device/approve-rejected",method:"POST",handler:QCe},{path:"/api/device/clear-rejected",method:"POST",handler:ZCe},{path:"/api/device/remove",method:"POST",handler:eRe},{path:"/api/device/label",method:"POST",handler:rRe},{path:"/api/device/disconnect",method:"POST",handler:tRe},{path:"/api/device/auto-approve",method:"GET",handler:nRe},{path:"/api/device/auto-approve",method:"POST",handler:iRe},{path:"/api/connections",method:"GET",handler:DL},{path:"/api/logs",method:"GET",handler:LL},{path:"/api/logs/clear",method:"POST",handler:UL},{path:"/api/permissions",method:"GET",handler:BL},{path:"/api/permissions/request",method:"POST",handler:GL},{path:"/api/desktop/toggle",method:"POST",handler:FL},{path:"/api/ui/rtc-toggle",method:"POST",handler:TL},{path:"/api/autostart",method:"GET",handler:qL},{path:"/api/autostart",method:"POST",handler:$L},{path:"/api/sleep-inhibit",method:"GET",handler:ARe},{path:"/api/sleep-inhibit",method:"POST",handler:CRe},{path:"/api/remote/enabled",method:"GET",handler:IRe},{path:"/api/remote/enabled",method:"POST",handler:kRe},{path:"/api/desktop-unlock",method:"GET",handler:PRe},{path:"/api/desktop-unlock/install",method:"POST",handler:ORe},{path:"/api/desktop-unlock/uninstall",method:"POST",handler:NRe},{path:"/api/desktop-unlock/type",method:"POST",handler:MRe},{path:"/api/sessions",method:"GET",handler:DRe},{path:"/api/sessions/delete",method:"POST",handler:LRe},{path:"/api/local-sites",method:"*",public:!0,handler:MCe},{path:"/api/codespace/stop",method:"POST",handler:iyt},{path:"/api/verify-key",method:"POST",public:!0,handler:syt},{path:"/api/proxy/start",method:"POST",public:!0,handler:BRe},{path:"/api/proxy/end",method:"POST",public:!0,handler:BRe}];var lyt=parseInt(process.env.PORT||"2208",10),Ex=null;function uyt(t){if(process.platform!=="win32")try{let e=(0,wm.execSync)(`pgrep -f "vite --config ${t}"`,{encoding:"utf8"}).trim();for(let n of e.split(`
534
- `).filter(Boolean))if((0,wm.execSync)(`ps -o ppid= -p ${n}`,{encoding:"utf8"}).trim()==="1")try{process.kill(Number(n))}catch{}}catch{}}function dyt(){if(!qRe)return;let t=(0,nn.join)(sa,"vite.config.js");if(!(0,ji.existsSync)(t))return;uyt(t);let e=(0,ji.existsSync)((0,nn.join)(sa,"node_modules",".bin","vite"))?(0,nn.join)(sa,"node_modules",".bin","vite"):(0,nn.join)(sa,"..","node_modules",".bin","vite");Ex=(0,wm.spawn)("node",[e,"--config",t],{cwd:sa,stdio:"ignore",detached:!1}),Ex.on("error",()=>{}),Ex.unref()}async function GRe(){let t=Pp(),e=t.sleepInhibitMode;e||(t.sleepInhibit===!1?e="none":e=Te.sleepInhibit?.defaultMode||"never"),I0(e),await m2(),$Re=rle(),dyt();let r=oM(cyt,{fallback:(c,l,{pathname:u})=>{if(u.startsWith("/api/")||u.startsWith("/socket.io")){Ze(l,404,"Not found");return}let d=u.replace(/^\//,"");if(d.split(/[\\/]/).includes("..")){Ze(l,400,"Bad request");return}if((0,ji.existsSync)(lc)&&d)try{let g=(0,nn.join)(lc,d);if((0,ji.existsSync)(g)&&!(0,ji.statSync)(g).isDirectory()&&Es(l,g))return}catch{}if((u==="/workspace"||u.startsWith("/workspace/")||u.startsWith("/_next/")||u==="/login"||u.startsWith("/login/"))&&(0,ji.existsSync)(lc)){let g=(0,nn.join)(lc,d);if(Es(l,g)||Es(l,`${g}.html`)||Es(l,(0,nn.join)(g,"index.html"))||(c.headers.rsc==="1"||d.endsWith(".txt"))&&(d.startsWith("workspace/terminal/")&&Es(l,(0,nn.join)(lc,"workspace","terminal","default.txt"))||Es(l,(0,nn.join)(lc,"workspace.txt")))||u.startsWith("/workspace")&&(Es(l,(0,nn.join)(lc,"workspace.html"))||Es(l,(0,nn.join)(lc,"workspace","index.html")))||u.startsWith("/login")&&(Es(l,(0,nn.join)(lc,"login.html"))||Es(l,(0,nn.join)(lc,"login","index.html"))))return;Ze(l,404,"Not found");return}let m=()=>{let g=d==="ui"||d===""?"index.html":d.replace(/^ui\/?/,""),y=(0,nn.join)(p8,g);Es(l,y)||Es(l,(0,nn.join)(p8,"index.html"))||Ze(l,404,"Not found")};if(qRe){tyt(c,l,m);return}m()}}),i=(0,A1.createServer)(async(c,l)=>{if(Yx(c.headers.host)){nyt(c,l);return}await r(c,l)});CD(),_L(),vL();let s=()=>XT().catch(c=>so.error(`permission refresh failed: ${c?.message||c}`));s(),process.platform==="darwin"&&setInterval(s,oK),await OCe(i),i.on("error",c=>{so.error(`HTTP server error: ${c?.message||c}`),c?.code==="EADDRINUSE"&&process.exit(1)}),i.listen(lyt,c=>{if(c)throw c;let l="3.0.24";h8(l),setInterval(()=>h8(l),l0.checkIntervalMs),g2(()=>ryt(l))});let o=!1,a=async c=>{if(o)return;o=!0,pL(),so.info(`\u{1F6D1} Received ${c}, shutting down gracefully...`);let l=setTimeout(()=>{so.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>so.info("\u2713 HTTP server closed")),Ex)try{Ex.kill()}catch{}let u=Ya();u&&(u.emit("server:shutdown"),u.close(()=>so.info("\u2713 Socket.IO closed"))),await new Promise(d=>setTimeout(d,500)),clearTimeout(l),so.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(u){so.error(`\u274C Error during shutdown: ${u?.message||u}`),clearTimeout(l),process.exit(1)}};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>a("SIGBREAK")),i}GRe().catch(t=>{so.error(`Server failed to start: ${t?.stack||t?.message||t}`),process.exit(1)});0&&(module.exports={startServer});
532
+ `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return R.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(R){var C=c((0,m.execSync)(T[w]).toString());return R?C:a(C)}function u(R){return new f.default(function(C,D){return(0,m.exec)(T[w],{},function($,G,V){if($)return D(new Error("Error while obtaining machine id: "+$.stack));var L=c(G.toString());return C(R?L:a(L))})})}Object.defineProperty(r,"__esModule",{value:!0});var d=i(35),f=s(d);r.machineIdSync=l,r.machineId=u;var m=i(70),g=i(71),y=process,w=y.platform,S={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},T={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:S[o()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(n,r,i){n.exports={default:i(36),__esModule:!0}},function(n,r,i){i(66),i(68),i(69),i(67),n.exports=i(6).Promise},function(n,r){n.exports=function(){}},function(n,r){n.exports=function(i,s,o,a){if(!(i instanceof s)||a!==void 0&&a in i)throw TypeError(o+": incorrect invocation!");return i}},function(n,r,i){var s=i(13),o=i(31),a=i(62);n.exports=function(c){return function(l,u,d){var f,m=s(l),g=o(m.length),y=a(d,g);if(c&&u!=u){for(;g>y;)if(f=m[y++],f!=f)return!0}else for(;g>y;y++)if((c||y in m)&&m[y]===u)return c||y||0;return!c&&-1}}},function(n,m,i){var s=i(7),o=i(44),a=i(43),c=i(3),l=i(31),u=i(64),d={},f={},m=n.exports=function(g,y,w,S,T){var R,C,D,$,G=T?function(){return g}:u(g),V=s(w,S,y?2:1),L=0;if(typeof G!="function")throw TypeError(g+" is not iterable!");if(a(G)){for(R=l(g.length);R>L;L++)if($=y?V(c(C=g[L])[0],C[1]):V(g[L]),$===d||$===f)return $}else for(D=G.call(g);!(C=D.next()).done;)if($=o(D,V,C.value,y),$===d||$===f)return $};m.BREAK=d,m.RETURN=f},function(n,r){n.exports=function(i,s,o){var a=o===void 0;switch(s.length){case 0:return a?i():i.call(o);case 1:return a?i(s[0]):i.call(o,s[0]);case 2:return a?i(s[0],s[1]):i.call(o,s[0],s[1]);case 3:return a?i(s[0],s[1],s[2]):i.call(o,s[0],s[1],s[2]);case 4:return a?i(s[0],s[1],s[2],s[3]):i.call(o,s[0],s[1],s[2],s[3])}return i.apply(o,s)}},function(n,r,i){var s=i(11);n.exports=Object("z").propertyIsEnumerable(0)?Object:function(o){return s(o)=="String"?o.split(""):Object(o)}},function(n,r,i){var s=i(10),o=i(1)("iterator"),a=Array.prototype;n.exports=function(c){return c!==void 0&&(s.Array===c||a[o]===c)}},function(n,r,i){var s=i(3);n.exports=function(o,a,c,l){try{return l?a(s(c)[0],c[1]):a(c)}catch(d){var u=o.return;throw u!==void 0&&s(u.call(o)),d}}},function(n,r,i){"use strict";var s=i(49),o=i(17),a=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),n.exports=function(l,u,d){l.prototype=s(c,{next:o(1,d)}),a(l,u+" Iterator")}},function(n,r,i){var s=i(1)("iterator"),o=!1;try{var a=[7][s]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch{}n.exports=function(c,l){if(!l&&!o)return!1;var u=!1;try{var d=[7],f=d[s]();f.next=function(){return{done:u=!0}},d[s]=function(){return f},c(d)}catch{}return u}},function(n,r){n.exports=function(i,s){return{value:s,done:!!i}}},function(n,r,i){var s=i(2),o=i(30).set,a=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,u=i(11)(c)=="process";n.exports=function(){var d,f,m,g=function(){var T,R;for(u&&(T=c.domain)&&T.exit();d;){R=d.fn,d=d.next;try{R()}catch(C){throw d?m():f=void 0,C}}f=void 0,T&&T.enter()};if(u)m=function(){c.nextTick(g)};else if(a){var y=!0,w=document.createTextNode("");new a(g).observe(w,{characterData:!0}),m=function(){w.data=y=!y}}else if(l&&l.resolve){var S=l.resolve();m=function(){S.then(g)}}else m=function(){o.call(s,g)};return function(T){var R={fn:T,next:void 0};f&&(f.next=R),d||(d=R,m()),f=R}}},function(n,r,i){var s=i(3),o=i(50),a=i(22),c=i(19)("IE_PROTO"),l=function(){},u="prototype",d=function(){var f,m=i(16)("iframe"),g=a.length,y=">";for(m.style.display="none",i(25).appendChild(m),m.src="javascript:",f=m.contentWindow.document,f.open(),f.write("<script>document.F=Object</script"+y),f.close(),d=f.F;g--;)delete d[u][a[g]];return d()};n.exports=Object.create||function(f,m){var g;return f!==null?(l[u]=s(f),g=new l,l[u]=null,g[c]=f):g=d(),m===void 0?g:o(g,m)}},function(n,r,i){var s=i(12),o=i(3),a=i(54);n.exports=i(4)?Object.defineProperties:function(c,l){o(c);for(var u,d=a(l),f=d.length,m=0;f>m;)s.f(c,u=d[m++],l[u]);return c}},function(n,r,i){var s=i(55),o=i(17),a=i(13),c=i(32),l=i(8),u=i(26),d=Object.getOwnPropertyDescriptor;r.f=i(4)?d:function(f,m){if(f=a(f),m=c(m,!0),u)try{return d(f,m)}catch{}if(l(f,m))return o(!s.f.call(f,m),f[m])}},function(n,r,i){var s=i(8),o=i(63),a=i(19)("IE_PROTO"),c=Object.prototype;n.exports=Object.getPrototypeOf||function(l){return l=o(l),s(l,a)?l[a]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(n,r,i){var s=i(8),o=i(13),a=i(39)(!1),c=i(19)("IE_PROTO");n.exports=function(l,u){var d,f=o(l),m=0,g=[];for(d in f)d!=c&&s(f,d)&&g.push(d);for(;u.length>m;)s(f,d=u[m++])&&(~a(g,d)||g.push(d));return g}},function(n,r,i){var s=i(53),o=i(22);n.exports=Object.keys||function(a){return s(a,o)}},function(n,r){r.f={}.propertyIsEnumerable},function(n,r,i){var s=i(5);n.exports=function(o,a,c){for(var l in a)c&&o[l]?o[l]=a[l]:s(o,l,a[l]);return o}},function(n,r,i){n.exports=i(5)},function(n,r,i){var s=i(9),o=i(3),a=function(c,l){if(o(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};n.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,u){try{u=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),u(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(d,f){return a(d,f),l?d.__proto__=f:u(d,f),d}})({},!1):void 0),check:a}},function(n,r,i){"use strict";var s=i(2),o=i(6),a=i(12),c=i(4),l=i(1)("species");n.exports=function(u){var d=typeof o[u]=="function"?o[u]:s[u];c&&d&&!d[l]&&a.f(d,l,{configurable:!0,get:function(){return this}})}},function(n,r,i){var s=i(3),o=i(14),a=i(1)("species");n.exports=function(c,l){var u,d=s(c).constructor;return d===void 0||(u=s(d)[a])==null?l:o(u)}},function(n,r,i){var s=i(20),o=i(15);n.exports=function(a){return function(c,l){var u,d,f=String(o(c)),m=s(l),g=f.length;return m<0||m>=g?a?"":void 0:(u=f.charCodeAt(m),u<55296||u>56319||m+1===g||(d=f.charCodeAt(m+1))<56320||d>57343?a?f.charAt(m):u:a?f.slice(m,m+2):(u-55296<<10)+(d-56320)+65536)}}},function(n,r,i){var s=i(20),o=Math.max,a=Math.min;n.exports=function(c,l){return c=s(c),c<0?o(c+l,0):a(c,l)}},function(n,r,i){var s=i(15);n.exports=function(o){return Object(s(o))}},function(n,r,i){var s=i(21),o=i(1)("iterator"),a=i(10);n.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[o]||c["@@iterator"]||a[s(c)]}},function(n,r,i){"use strict";var s=i(37),o=i(47),a=i(10),c=i(13);n.exports=i(27)(Array,"Array",function(l,u){this._t=c(l),this._i=0,this._k=u},function(){var l=this._t,u=this._k,d=this._i++;return!l||d>=l.length?(this._t=void 0,o(1)):u=="keys"?o(0,d):u=="values"?o(0,l[d]):o(0,[d,l[d]])},"values"),a.Arguments=a.Array,s("keys"),s("values"),s("entries")},function(n,r){},function(n,r,i){"use strict";var s,o,a,c=i(28),l=i(2),u=i(7),d=i(21),f=i(23),m=i(9),g=(i(3),i(14)),y=i(38),w=i(40),S=(i(58).set,i(60)),T=i(30).set,R=i(48)(),C="Promise",D=l.TypeError,G=l.process,$=l[C],G=l.process,V=d(G)=="process",L=function(){},k=!!(function(){try{var oe=$.resolve(1),J=(oe.constructor={})[i(1)("species")]=function(ve){ve(L,L)};return(V||typeof PromiseRejectionEvent=="function")&&oe.then(L)instanceof J}catch{}})(),E=function(oe,J){return oe===J||oe===$&&J===a},A=function(oe){var J;return!(!m(oe)||typeof(J=oe.then)!="function")&&J},M=function(oe){return E($,oe)?new I(oe):new o(oe)},I=o=function(oe){var J,ve;this.promise=new oe(function(we,xe){if(J!==void 0||ve!==void 0)throw D("Bad Promise constructor");J=we,ve=xe}),this.resolve=g(J),this.reject=g(ve)},P=function(oe){try{oe()}catch(J){return{error:J}}},F=function(oe,J){if(!oe._n){oe._n=!0;var ve=oe._c;R(function(){for(var we=oe._v,xe=oe._s==1,lt=0,Ue=function(U){var K,j,Q=xe?U.ok:U.fail,Z=U.resolve,ee=U.reject,ie=U.domain;try{Q?(xe||(oe._h==2&&b(oe),oe._h=1),Q===!0?K=we:(ie&&ie.enter(),K=Q(we),ie&&ie.exit()),K===U.promise?ee(D("Promise-chain cycle")):(j=A(K))?j.call(K,Z,ee):Z(K)):ee(we)}catch(ne){ee(ne)}};ve.length>lt;)Ue(ve[lt++]);oe._c=[],oe._n=!1,J&&!oe._h&&X(oe)})}},X=function(oe){T.call(l,function(){var J,ve,we,xe=oe._v;if(N(oe)&&(J=P(function(){V?G.emit("unhandledRejection",xe,oe):(ve=l.onunhandledrejection)?ve({promise:oe,reason:xe}):(we=l.console)&&we.error&&we.error("Unhandled promise rejection",xe)}),oe._h=V||N(oe)?2:1),oe._a=void 0,J)throw J.error})},N=function(oe){if(oe._h==1)return!1;for(var J,ve=oe._a||oe._c,we=0;ve.length>we;)if(J=ve[we++],J.fail||!N(J.promise))return!1;return!0},b=function(oe){T.call(l,function(){var J;V?G.emit("rejectionHandled",oe):(J=l.onrejectionhandled)&&J({promise:oe,reason:oe._v})})},q=function(oe){var J=this;J._d||(J._d=!0,J=J._w||J,J._v=oe,J._s=2,J._a||(J._a=J._c.slice()),F(J,!0))},pe=function(oe){var J,ve=this;if(!ve._d){ve._d=!0,ve=ve._w||ve;try{if(ve===oe)throw D("Promise can't be resolved itself");(J=A(oe))?R(function(){var we={_w:ve,_d:!1};try{J.call(oe,u(pe,we,1),u(q,we,1))}catch(xe){q.call(we,xe)}}):(ve._v=oe,ve._s=1,F(ve,!1))}catch(we){q.call({_w:ve,_d:!1},we)}}};k||($=function(oe){y(this,$,C,"_h"),g(oe),s.call(this);try{oe(u(pe,this,1),u(q,this,1))}catch(J){q.call(this,J)}},s=function(oe){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)($.prototype,{then:function(oe,J){var ve=M(S(this,$));return ve.ok=typeof oe!="function"||oe,ve.fail=typeof J=="function"&&J,ve.domain=V?G.domain:void 0,this._c.push(ve),this._a&&this._a.push(ve),this._s&&F(this,!1),ve.promise},catch:function(oe){return this.then(void 0,oe)}}),I=function(){var oe=new s;this.promise=oe,this.resolve=u(pe,oe,1),this.reject=u(q,oe,1)}),f(f.G+f.W+f.F*!k,{Promise:$}),i(18)($,C),i(59)(C),a=i(6)[C],f(f.S+f.F*!k,C,{reject:function(oe){var J=M(this),ve=J.reject;return ve(oe),J.promise}}),f(f.S+f.F*(c||!k),C,{resolve:function(oe){if(oe instanceof $&&E(oe.constructor,this))return oe;var J=M(this),ve=J.resolve;return ve(oe),J.promise}}),f(f.S+f.F*!(k&&i(46)(function(oe){$.all(oe).catch(L)})),C,{all:function(oe){var J=this,ve=M(J),we=ve.resolve,xe=ve.reject,lt=P(function(){var Ue=[],U=0,K=1;w(oe,!1,function(j){var Q=U++,Z=!1;Ue.push(void 0),K++,J.resolve(j).then(function(ee){Z||(Z=!0,Ue[Q]=ee,--K||we(Ue))},xe)}),--K||we(Ue)});return lt&&xe(lt.error),ve.promise},race:function(oe){var J=this,ve=M(J),we=ve.reject,xe=P(function(){w(oe,!1,function(lt){J.resolve(lt).then(ve.resolve,we)})});return xe&&we(xe.error),ve.promise}})},function(n,r,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(o){this._t=String(o),this._i=0},function(){var o,a=this._t,c=this._i;return c>=a.length?{value:void 0,done:!0}:(o=s(a,c),this._i+=o.length,{value:o,done:!1})})},function(n,r,i){i(65);for(var s=i(2),o=i(5),a=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],u=0;u<5;u++){var d=l[u],f=s[d],m=f&&f.prototype;m&&!m[c]&&o(m,c,d),a[d]=a.Array}},function(n,r){n.exports=require("child_process")},function(n,r){n.exports=require("crypto")}])})});var fyt={};yr(fyt,{startServer:()=>GRe});module.exports=UIe(fyt);var A1=require("http"),wm=require("child_process"),ji=require("fs"),nn=require("path"),C1=require("url");Rr();aM();Lt();tt();nu();n2();gj();Ha();Lq();Vf();Ic();async function MCe(t,e){let n=t.headers.authorization;if(!n||!n.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let r=n.slice(7);if(!h1(r,Zi()?.key)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await TR();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}Vf();wT();var LCe=require("url");var x1=ce(require("path"),1),UCe=ce(require("os"),1);Lt();var NCe=ce(require("path"),1),DCe=ce(require("os"),1);var BDt=NCe.default.join(DCe.default.homedir(),".9remote","pids");aL();Rp();tt();var YDt=Se("update"),XDt=x1.default.dirname((0,LCe.fileURLToPath)(__importMetaUrl));var JDt=x1.default.join(UCe.default.homedir(),".9remote","cloudflared.pid");function FCe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}var QDt=x1.default.join(Oe.STATE,l0.lockFile);ns();Ha();Rp();Rr();Ic();Vf();var qCe=ce(BCe(),1),s8=ce(require("crypto"),1),{machineIdSync:Lgt}=qCe.default;async function $Ce(t=null){let e=t||process.env.MACHINE_ID_SALT||"9remote-salt";try{let n=Lgt();return s8.default.createHash("sha256").update(n+e).digest("hex").substring(0,16)}catch(n){return console.error("Error getting machine ID:",n),s8.default.randomUUID().replace(/-/g,"").substring(0,16)}}ns();Lt();tt();E0();Vf();Bz();var o8=Se("session"),Ugt=10;async function GCe(t,e){let n=async()=>{let r=await mc(`${e}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{let i={apiKey:Dn(t),expiryMinutes:Ugt};return{...i,...kT(i)}})())});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error||`HTTP ${r.status}`)}return r.json()};try{let r;try{r=await n()}catch(s){if(o8.warn(`Temp key creation failed (${s.message}) \u2014 re-registering session`),!await a8(t,e))throw s;r=await n()}let i=eCe();return nCe(r.tempKey,i,r.expiresAt,e),{...r,oneTimeKey:`${r.tempKey}${i}`}}catch(r){return o8.error(`Temp key creation failed: ${r?.message||r}`),null}}function HCe(t,e){return e?.tempKey?`${t}/login?k=${e.tempKey}#${e.oneTimeKey}`:`${t}/login`}async function a8(t,e,n,r){try{let i=await mc(`${e}/api/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(t),hostPublicKey:RT(),hostX25519Key:IT(),tempKey:dx()?.tempKey||void 0})});if(!i.ok)throw new Error(`HTTP ${i.status}`);return n&&await mc(`${e}/api/session/update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(t),tunnelUrl:n,...kT({apiKey:Dn(t),tunnelUrl:n})})}).catch(()=>{}),r&&Dn(r)!==Dn(t)&&await mc(`${e}/api/session/delete`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:Dn(r),...kT({apiKey:Dn(r)})})}).catch(()=>{}),!0}catch(i){return o8.error(`Session registration failed: ${i?.message||i}`),!1}}f0();Vf();Rp();function c8(t){return Pp().remoteEnabled!==!1?!1:(Ze(t,409,"Remote access is off"),!0)}async function jCe(t,e){if(c8(e))return;let n=VT(),r=n.workerUrl||wc;if(!n.permanentKey){Ze(e,400,"No permanent key set");return}let i=await GCe(n.permanentKey,r);if(!i){Ze(e,500,"Temp key creation failed");return}let s=HCe(r,i);kc({oneTimeKey:i.oneTimeKey,oneTimeKeyExpiresAt:i.expiresAt,qrUrl:s}),Me(e,{oneTimeKey:i.oneTimeKey,expiresAt:i.expiresAt,qrUrl:s})}async function WCe(t,e){c8(e)||(_T("session-registered"),Me(e,vT()))}async function VCe(t,e){if(!c8(e))try{let n=VT(),r=n.workerUrl||wc,i=await $Ce(),s=sCe(i),o=Zi();if(!await a8(s,r,n.tunnelUrl,o?.key)){Ze(e,502,"Could not register the new key with the server");return}D7(i,s,o?.name||"Default"),Sg(Dn(s)),kc({permanentKey:s,oneTimeKey:"",oneTimeKeyExpiresAt:null,qrUrl:"",pairingUsed:!0}),Me(e,{ok:!0,permanentKey:s})}catch(n){Ze(e,500,n.message)}}Rr();nu();N0();async function zCe(t,e){let n=await _r(t,e);if(!n)return;let r=ACe(n.socketId);Me(e,{ok:r})}async function KCe(t,e){let n=await _r(t,e);if(!n)return;let r=RCe(n.socketId);Me(e,{ok:r})}function YCe(t,e){Me(e,{pending:EQ()})}function XCe(t,e){Me(e,{devices:_Q()})}function JCe(t,e){Me(e,{rejected:SQ()})}async function QCe(t,e){let n=await _r(t,e);if(!n)return;let r=CCe(n.deviceId);Me(e,{ok:r})}async function ZCe(t,e){let n=await _r(t,e);n&&(S1(n.deviceId),jg(n.deviceId),Me(e))}async function eRe(t,e){let n=await _r(t,e);n&&(S1(n.deviceId),mQ(n.deviceId),Me(e))}async function tRe(t,e){let n=await _r(t,e);if(!n)return;pQ(n.deviceId);let r=S1(n.deviceId);Me(e,{disconnected:r})}function nRe(t,e){Me(e,{enabled:QL()})}async function rRe(t,e){let n=await _r(t,e);if(!n)return;let r=gQ(n.deviceId,n.label);Me(e,{ok:r})}async function iRe(t,e){let n=await _r(t,e);if(!n)return;let r=bQ(!!n.enabled);Me(e,{enabled:r})}Rr();nu();es();xR();Fs();Fc();d2();Nz();var sRe={},Fgt=1e4;function Bgt(t,e){if(e?.csid&&qd.test(e.csid))return e.csid;let{sessionId:n,...r}=e||{};return lne(t,r)}function aRe(t,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"",csid:e.csid||"",...e};let n=JSON.parse(t||"{}");return{type:n.type||"stop",sessionId:n.sessionId||"",tool:n.tool||"",csid:n.csid||"",...n}}async function cRe(t,e){let n="";await new Promise(r=>{t.on("data",i=>n+=i),t.on("end",r)});try{uRe(aRe(n,null)),Me(e,{success:!0})}catch{Ze(e,400,"Invalid JSON")}}function lRe(t,e,{query:n}){uRe(aRe(null,n)),Me(e,{success:!0})}function oRe(t,e,n){let{type:r,sessionId:i,tool:s}=t,o={type:r,sessionId:i,tool:s,timestamp:n},c=nh({type:r,sessionId:i,tool:s})?.state||Jt.IDLE,l=ss(i);if(nt(e,"statusChange",{sessionId:i,state:c,tool:s,since:n,...l?{conversationId:l.id}:{}}),bF(i,o),nt(e,"chatNotification",o),(c===Jt.DONE||c===Jt.BLOCKED)&&KA(i),(c===Jt.DONE||c===Jt.BLOCKED)&&Mz(i),c!==Jt.DONE&&c!==Jt.BLOCKED)return;let u=`${i}:${c}`;n-(sRe[u]||0)<Fgt||(sRe[u]=n,ace({...o,state:c}))}function uRe(t){let{type:e,sessionId:n,tool:r}=t,i=Date.now(),s=Ya();if(!s||!n)return;let o=Bgt(r,t);if(o&&Da(n,r,o,"hook"),VA[e]===Jt.DONE){XA(n,()=>oRe(t,s,Date.now()));return}oRe(t,s,i)}Rr();s2();UR();Lt();var l8=ce(require("fs"),1),b1=ce(require("path"),1);nu();es();yh();Ha();var qgt=process.platform==="darwin"||process.platform==="win32",dRe=t=>qgt?t.toLowerCase():t,fRe=(t,e)=>{let n=dRe(t),r=dRe(e);return n===r||n.startsWith(r+b1.default.sep)},pRe=t=>[t.cwd,t.workspacePath].filter(Boolean);function $gt(t,e,n){if(e&&n.some(s=>s.id===e))return e;let r=null,i=-1;for(let s of n)for(let o of pRe(s))fRe(t,o)&&o.length>i&&(r=s.id,i=o.length);return r}function hRe({path:t,title:e},n=null){if(!t||typeof t!="string")return{error:"path is required"};let r=b1.default.resolve(t);try{r=l8.default.realpathSync(r)}catch{return{error:"File not found"}}if(wt(r))return{error:"Access denied"};if(!l8.default.statSync(r).isFile())return{error:"Not a file"};let i=_u(),s=i.filter(c=>pRe(c).some(l=>fRe(r,l)));if(n&&i.some(c=>c.id===n)&&!s.some(c=>c.id===n))return{error:"File is outside this terminal's workspace"};if(!s.length)return{error:"File is outside every open terminal's workspace"};let o=Ya();if(!o)return{error:"Server not ready"};let a=$gt(r,n,s);return nt(o,"artifactOpen",{path:r,title:e||b1.default.basename(r),sessionId:a}),{path:r}}var Ggt={name:"openArtifact",description:"Show a file you just created or edited in the 9Remote app, sliding it in beside the terminal. Use it for files worth looking at \u2014 html, markdown, svg, images, pdf, csv, diagrams, code. Skip files with nothing to see. The user closes it themselves.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the file."},title:{type:"string",description:"Optional label for the panel header."}},required:["path"]},run({path:t,title:e},n){let r=hRe({path:t,title:e},n?.sessionId);return r.error?r:`Opened ${r.path}`}},mRe=Ggt;hS();Fj();var Hgt=500;function jgt(t={applyAction:F_}){return{name:"report_task",description:"Report what you just finished, in one or two sentences. It lands on this session's card on the kanban board the user watches, so progress is visible without reading your terminal. Call it when a chunk of work completes, and again with status when your own state changes (todo | in_progress | needs_input | done). While a turn of yours is actually running, the live state wins \u2014 the self-report takes effect when you go idle.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"1-2 sentences of what was done or what changed"},status:{type:"string",enum:Uj,description:"Optional self-reported status; live turn state still wins while running"}},required:["summary"]},async run({summary:e,status:n}={},r={}){let i=String(e||"").trim().slice(0,Hgt);if(!i)return{error:"summary is required"};let s=r?.sessionId;if(!s)return{error:"no session identity; cannot tell which card is yours"};let{error:o}=await t.applyAction({type:"report",sessionId:s,summary:i,...n?{status:n}:{}});return o?{error:o}:"reported"}}}var gRe=jgt();Yk();var yRe=[mRe],_Re=new Map([...yRe,...Cf,gRe].map(t=>[t.name,t])),vRe=()=>yRe.map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,inputSchema:n}));var T1=(t,e=!1)=>({content:[{type:"text",text:t}],isError:e});async function Wgt(t,e,n){let r=_Re.get(t);if(!r)return T1(`Unknown tool: ${t}`,!0);try{let i=await r.run(e||{},n||{});return i?.error?T1(i.error,!0):T1(typeof i=="string"?i:JSON.stringify(i))}catch(i){return T1(i.message,!0)}}async function ERe(t,e){let{id:n,method:r,params:i}=t||{},s=o=>({jsonrpc:"2.0",id:n,result:o});return r==="initialize"?s({protocolVersion:i?.protocolVersion||Pl.PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:{name:Pl.SERVER_NAME,version:"3.0.25"}}):r==="tools/list"?s({tools:vRe()}):r==="tools/call"?s(await Wgt(i?.name,i?.arguments,e)):r==="ping"?s({}):n==null?null:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${r}`}}}var d8=ce(require("fs"),1),SRe=require("child_process");tt();r2();var Vgt=Se("artifact"),wRe=/(?:^|[\s\0])NINE_REMOTE_SESSION_ID=([^\s\0]+)/,u8=new WeakMap,f8=(t,e)=>(0,SRe.execFileSync)(t,e,{encoding:"utf8",timeout:Wy.PROBE_TIMEOUT_MS,stdio:["ignore","pipe","ignore"]});function zgt(t,e){let n=f8("lsof",["-nP",`-iTCP:${t}`,"-Fpn"]),r=null;for(let i of n.split(`
533
+ `))if(i[0]==="p")r=parseInt(i.slice(1),10);else if(i[0]==="n"&&r&&r!==e){let s=i.match(/^n(?:\[[^\]]+\]|[^:]+):(\d+)->/);if(s&&Number(s[1])===t)return r}return null}function Kgt(t){try{return process.platform==="linux"?d8.default.readFileSync(`/proc/${t}/environ`,"utf8").match(wRe)?.[1]||null:f8("ps",["-Eww","-o","command=","-p",String(t)]).match(wRe)?.[1]||null}catch{return null}}function Ygt(t){try{if(process.platform==="linux"){let e=d8.default.readFileSync(`/proc/${t}/stat`,"utf8");return parseInt(e.slice(e.lastIndexOf(")")+2).split(" ")[1],10)||null}return parseInt(f8("ps",["-o","ppid=","-p",String(t)]).trim(),10)||null}catch{return null}}function Xgt(t){for(let e=0;t>1&&t!==process.pid&&e<Wy.MAX_PARENT_HOPS;e++){let n=Kgt(t);if(n)return n;if(t=Ygt(t),!t)return null}return null}function xRe(t){let e=t?.headers?.[Wy.HEADER];if(e&&!/[${}]/.test(e))return e;let n=t?.socket;if(!n)return null;if(u8.has(n))return u8.get(n);let r=null;try{let i=zgt(n.remotePort,process.pid);i&&(r=Xgt(i))}catch(i){Vgt.warn(`caller probe failed: ${i.message}`)}return u8.set(n,r),r}async function bRe(t,e){if(!ale(t.headers.authorization))return Ze(e,401,"Unauthorized");if(!tw())return Ze(e,403,"MCP is turned off in 9Remote settings");let n=await _r(t,e);if(n===null&&!e.writableEnded)return Ze(e,400,"Invalid request");if(e.writableEnded)return;let r;try{r=await ERe(n,{sessionId:xRe(t)})}catch(i){r={jsonrpc:"2.0",id:n?.id??null,error:{code:-32603,message:i.message}}}if(!r)return e.writeHead(202),e.end();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(r))}Rr();GT();Ic();Gr();ns();function TRe(){return{mode:mL(),active:hL(),presets:Object.keys(Te.sleepInhibit?.presets||{})}}function ARe(t,e){Me(e,TRe())}async function CRe(t,e){let n=await _r(t,e);if(!n)return;let r=I0(n.mode);MT({sleepInhibitMode:r});let i=TRe();kn("sleepInhibit",i),Me(e,i)}Rr();Ic();nu();ns();function RRe(t){return{enabled:t}}function IRe(t,e){Me(e,RRe(Sv()))}async function kRe(t,e){let n=await _r(t,e);if(!n)return;if(typeof n.enabled!="boolean")return Ze(e,400,"enabled must be a boolean");MT({remoteEnabled:n.enabled}),PCe(n.enabled),Aa(n.enabled?"start-tunnel":"stop-tunnel");let r=RRe(n.enabled);kn("remote",r),Me(e,r)}Rr();mU();async function PRe(t,e){let n=await dA();Me(e,n)}async function ORe(t,e){let n=await rZ(),r=await dA();Me(e,{...n,...r})}async function MRe(t,e){let n=await _r(t,e);if(!n)return;if(typeof n.text!="string"||!n.text){Ze(e,400,"Missing text");return}let r=await $0(n.text);Me(e,{ok:r.ok,reason:r.reason||null})}async function NRe(t,e){let n=await nZ(),r=await dA();Me(e,{...n,...r})}_i();Rr();async function DRe(t,e){try{let n=await Rd();Me(e,{sessions:n})}catch(n){Ze(e,500,n.message)}}async function LRe(t,e){let n=await _r(t,e);if(n){if(!n.sessionId)return Ze(e,400,"sessionId required");try{await Id(n.sessionId),Me(e)}catch(r){Ze(e,500,r.message)}}}var Yu=ce(require("os"),1);Gr();xA();Rr();function Jgt(){let t=VZ();if(!t?.activeClients)return{total:0,streaming:0};let e=0;for(let n of t.activeClients.values())n.isStreaming&&e++;return{total:t.activeClients.size,streaming:e}}function Qgt(){let t=process.memoryUsage(),e=Yu.default.cpus();return{agent:{pid:process.pid,version:"3.0.25",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(t.heapUsed/1048576*10)/10,heapTotalMB:Math.round(t.heapTotal/1048576*10)/10,rssMB:Math.round(t.rss/1048576*10)/10,externalMB:Math.round(t.external/1048576*10)/10}},os:{hostname:Yu.default.hostname(),platform:Yu.default.platform(),arch:Yu.default.arch(),uptimeSec:Math.round(Yu.default.uptime()),loadAvg:Yu.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(Yu.default.totalmem()/1048576),freeMemMB:Math.round(Yu.default.freemem()/1048576)},remote:{available:SA(),...Jgt(),memoryWarningThresholdMB:Te.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function URe(t,e){try{Me(e,Qgt())}catch(n){Ze(e,500,"stats error",n.message)}}GT();Ic();Gr();sK();SK();var so=Se("server"),sa=(0,C1.fileURLToPath)(new URL(".",__importMetaUrl)),qRe=process.env.NODE_ENV==="development",Zgt=5173,p8=[(0,nn.join)(sa,"dist","ui"),(0,nn.join)(sa,"ui","dist"),(0,nn.join)(sa,"ui")].find(t=>(0,ji.existsSync)(t))||(0,nn.join)(sa,"dist","ui"),lc=[(0,nn.join)(sa,"dist","web"),(0,nn.join)(sa,"web"),(0,nn.join)(sa,"..","web","out")].find(t=>(0,ji.existsSync)(t))||p8,eyt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".txt":"text/x-component; charset=utf-8",".webmanifest":"application/manifest+json"};function tyt(t,e,n){let r=(0,A1.request)({hostname:"localhost",port:Zgt,path:t.url,method:t.method,headers:t.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});r.on("error",()=>n?n():void(e.writeHead(502),e.end("Vite dev server not ready"))),t.pipe(r)}function nyt(t,e){let n;try{n=(0,C1.parse)(t.url).pathname}catch{Ze(e,400,"Bad request");return}let r=vK(n,t.headers.host);if(!r){Ze(e,404,"Not found");return}for(let[i,s]of Object.entries(r.headers))e.setHeader(i,s);Es(e,(0,nn.join)(lc,r.path),{frameable:!0})||Ze(e,404,"Not found")}function Es(t,e,{frameable:n=!1}={}){if(!(0,ji.existsSync)(e))return!1;try{if((0,ji.statSync)(e).isDirectory()){let a=(0,nn.join)(e,"index.html");return(0,ji.existsSync)(a)?Es(t,a,{frameable:n}):!1}let i=(0,nn.extname)(e),s=eyt[i]||"application/octet-stream";t.setHeader("Content-Type",s),i===".html"&&!n&&t.setHeader("X-Frame-Options","SAMEORIGIN");let o=e.includes(`${nn.sep}_next${nn.sep}static${nn.sep}`);return t.hasHeader("Cache-Control")||t.setHeader("Cache-Control",o?"public, max-age=31536000, immutable":"no-cache"),t.writeHead(200),t.end((0,ji.readFileSync)(e)),!0}catch{return!1}}async function h8(t){try{let e=await mc(iM);if(!e.ok)return;let{version:n}=await e.json();if(n&&FCe(t,n)){YT({version:n}),kn("updateAvailable",{version:n}),WR();return}k0()&&(YT(null),WR())}catch{}}var FRe=0;function ryt(t){let e=Date.now();e-FRe<l0.connectCheckDebounceMs||(FRe=e,h8(t))}function iyt(t,e){if(process.env.CODESPACES!=="true"){Ze(e,400,"Not running on Codespaces");return}let n=process.env.CODESPACE_NAME;if(!n){Ze(e,400,"Codespace name not found");return}let r=Ya();r&&r.emit("codespace:stopping"),Me(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,wm.execFile)("gh",["codespace","stop","-c",n],{windowsHide:!0}),500)}async function syt(t,e){let{parseJsonBody:n}=await Promise.resolve().then(()=>(Rr(),ud)),r=await n(t,e);if(!r)return;let{verifyPresentedTail:i}=await Promise.resolve().then(()=>(Xz(),dCe)),s=i({tail:r.tail,tempKey:r.tempKey});if(s.ok){Me(e,{ok:!0});return}let o=t.headers["x-forwarded-for"]||t.socket?.remoteAddress||"unknown";if(r.tempKey&&r.tail)if(s.burned){so.warn(`wrong one-time code TAIL (${o}) \u2014 code burned, clearing from UI`);let{clearOneTimeKey:a}=await Promise.resolve().then(()=>(ns(),HL));a()}else so.warn(`stale one-time code TAIL (${o}) \u2014 code still live`);else r.tempKey?so.warn(`wrong one-time code TAIL (${o}) \u2014 no TAIL presented, code still live`):so.warn(`wrong API-key TAIL (${o}) \u2014 rejected`);setTimeout(()=>Me(e,{ok:!1,reason:s.reason}),s.penaltyMs||0)}var $Re;async function BRe(t,e,{pathname:n}){let r=t.headers.authorization;if(!r||!r.startsWith("Bearer ")||!h1(r.slice(7),Zi()?.key)){Ze(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Rr(),ud)),s=await i(t,e);if(!s)return;if(!s.port){Ze(e,400,"Port required");return}if(!n.endsWith("start")){PR(s.port),Me(e,{success:!0});return}let o=kR(s.port);if(!o){Ze(e,400,"Invalid port");return}Me(e,{success:!0,sessionId:o})}function oyt(t,e,{pathname:n,search:r}){let i=n.match(/^\/proxy\/([0-9a-f-]{36})(\/.*)?$/);i?ile($Re,t,e,i[1],i[2]||"/",r):Ze(e,404,"Not found")}function ayt(t,e,n){W_e(t,e,n)}var cyt=[{path:"/api/health",method:"GET",public:!0,handler:(t,e)=>Me(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(t,e)=>{let n="3.0.25";e.setHeader("Cache-Control","no-store"),Me(e,{version:n})}},{path:"/api/notify",method:"POST",public:!0,handler:cRe},{path:"/api/notify",method:"GET",public:!0,handler:lRe},{path:"/proxy/*",method:"*",public:!0,handler:oyt},{path:"/preview/*",method:"GET",public:!0,handler:ayt},{path:"/api/ui/events",method:"GET",handler:CL},{path:"/api/local-token",method:"GET",handler:bL},{path:Pl.PATH,method:"POST",handler:bRe},{path:"/api/ui/state",method:"GET",handler:RL},{path:"/api/ui/state",method:"POST",handler:IL},{path:"/api/ui/stop",method:"POST",handler:kL},{path:"/api/ui/start",method:"POST",handler:PL},{path:"/api/ui/stop-tunnel",method:"POST",handler:OL},{path:"/api/ui/shutdown",method:"POST",handler:ML},{path:"/api/update",method:"POST",handler:NL},{path:"/api/system/stats",method:"GET",handler:URe},{path:"/api/key/one-time",method:"POST",handler:jCe},{path:"/api/key/regenerate",method:"POST",handler:VCe},{path:"/api/signaling/retry",method:"POST",handler:WCe},{path:"/api/device/approve",method:"POST",handler:zCe},{path:"/api/device/reject",method:"POST",handler:KCe},{path:"/api/device/pending",method:"GET",handler:YCe},{path:"/api/device/approved",method:"GET",handler:XCe},{path:"/api/device/rejected",method:"GET",handler:JCe},{path:"/api/device/approve-rejected",method:"POST",handler:QCe},{path:"/api/device/clear-rejected",method:"POST",handler:ZCe},{path:"/api/device/remove",method:"POST",handler:eRe},{path:"/api/device/label",method:"POST",handler:rRe},{path:"/api/device/disconnect",method:"POST",handler:tRe},{path:"/api/device/auto-approve",method:"GET",handler:nRe},{path:"/api/device/auto-approve",method:"POST",handler:iRe},{path:"/api/connections",method:"GET",handler:DL},{path:"/api/logs",method:"GET",handler:LL},{path:"/api/logs/clear",method:"POST",handler:UL},{path:"/api/permissions",method:"GET",handler:BL},{path:"/api/permissions/request",method:"POST",handler:GL},{path:"/api/desktop/toggle",method:"POST",handler:FL},{path:"/api/ui/rtc-toggle",method:"POST",handler:TL},{path:"/api/autostart",method:"GET",handler:qL},{path:"/api/autostart",method:"POST",handler:$L},{path:"/api/sleep-inhibit",method:"GET",handler:ARe},{path:"/api/sleep-inhibit",method:"POST",handler:CRe},{path:"/api/remote/enabled",method:"GET",handler:IRe},{path:"/api/remote/enabled",method:"POST",handler:kRe},{path:"/api/desktop-unlock",method:"GET",handler:PRe},{path:"/api/desktop-unlock/install",method:"POST",handler:ORe},{path:"/api/desktop-unlock/uninstall",method:"POST",handler:NRe},{path:"/api/desktop-unlock/type",method:"POST",handler:MRe},{path:"/api/sessions",method:"GET",handler:DRe},{path:"/api/sessions/delete",method:"POST",handler:LRe},{path:"/api/local-sites",method:"*",public:!0,handler:MCe},{path:"/api/codespace/stop",method:"POST",handler:iyt},{path:"/api/verify-key",method:"POST",public:!0,handler:syt},{path:"/api/proxy/start",method:"POST",public:!0,handler:BRe},{path:"/api/proxy/end",method:"POST",public:!0,handler:BRe}];var lyt=parseInt(process.env.PORT||"2208",10),Ex=null;function uyt(t){if(process.platform!=="win32")try{let e=(0,wm.execSync)(`pgrep -f "vite --config ${t}"`,{encoding:"utf8"}).trim();for(let n of e.split(`
534
+ `).filter(Boolean))if((0,wm.execSync)(`ps -o ppid= -p ${n}`,{encoding:"utf8"}).trim()==="1")try{process.kill(Number(n))}catch{}}catch{}}function dyt(){if(!qRe)return;let t=(0,nn.join)(sa,"vite.config.js");if(!(0,ji.existsSync)(t))return;uyt(t);let e=(0,ji.existsSync)((0,nn.join)(sa,"node_modules",".bin","vite"))?(0,nn.join)(sa,"node_modules",".bin","vite"):(0,nn.join)(sa,"..","node_modules",".bin","vite");Ex=(0,wm.spawn)("node",[e,"--config",t],{cwd:sa,stdio:"ignore",detached:!1}),Ex.on("error",()=>{}),Ex.unref()}async function GRe(){let t=Pp(),e=t.sleepInhibitMode;e||(t.sleepInhibit===!1?e="none":e=Te.sleepInhibit?.defaultMode||"never"),I0(e),await m2(),$Re=rle(),dyt();let r=oM(cyt,{fallback:(c,l,{pathname:u})=>{if(u.startsWith("/api/")||u.startsWith("/socket.io")){Ze(l,404,"Not found");return}let d=u.replace(/^\//,"");if(d.split(/[\\/]/).includes("..")){Ze(l,400,"Bad request");return}if((0,ji.existsSync)(lc)&&d)try{let g=(0,nn.join)(lc,d);if((0,ji.existsSync)(g)&&!(0,ji.statSync)(g).isDirectory()&&Es(l,g))return}catch{}if((u==="/workspace"||u.startsWith("/workspace/")||u.startsWith("/_next/")||u==="/login"||u.startsWith("/login/"))&&(0,ji.existsSync)(lc)){let g=(0,nn.join)(lc,d);if(Es(l,g)||Es(l,`${g}.html`)||Es(l,(0,nn.join)(g,"index.html"))||(c.headers.rsc==="1"||d.endsWith(".txt"))&&(d.startsWith("workspace/terminal/")&&Es(l,(0,nn.join)(lc,"workspace","terminal","default.txt"))||Es(l,(0,nn.join)(lc,"workspace.txt")))||u.startsWith("/workspace")&&(Es(l,(0,nn.join)(lc,"workspace.html"))||Es(l,(0,nn.join)(lc,"workspace","index.html")))||u.startsWith("/login")&&(Es(l,(0,nn.join)(lc,"login.html"))||Es(l,(0,nn.join)(lc,"login","index.html"))))return;Ze(l,404,"Not found");return}let m=()=>{let g=d==="ui"||d===""?"index.html":d.replace(/^ui\/?/,""),y=(0,nn.join)(p8,g);Es(l,y)||Es(l,(0,nn.join)(p8,"index.html"))||Ze(l,404,"Not found")};if(qRe){tyt(c,l,m);return}m()}}),i=(0,A1.createServer)(async(c,l)=>{if(Yx(c.headers.host)){nyt(c,l);return}await r(c,l)});CD(),_L(),vL();let s=()=>XT().catch(c=>so.error(`permission refresh failed: ${c?.message||c}`));s(),process.platform==="darwin"&&setInterval(s,oK),await OCe(i),i.on("error",c=>{so.error(`HTTP server error: ${c?.message||c}`),c?.code==="EADDRINUSE"&&process.exit(1)}),i.listen(lyt,c=>{if(c)throw c;let l="3.0.25";h8(l),setInterval(()=>h8(l),l0.checkIntervalMs),g2(()=>ryt(l))});let o=!1,a=async c=>{if(o)return;o=!0,pL(),so.info(`\u{1F6D1} Received ${c}, shutting down gracefully...`);let l=setTimeout(()=>{so.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>so.info("\u2713 HTTP server closed")),Ex)try{Ex.kill()}catch{}let u=Ya();u&&(u.emit("server:shutdown"),u.close(()=>so.info("\u2713 Socket.IO closed"))),await new Promise(d=>setTimeout(d,500)),clearTimeout(l),so.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(u){so.error(`\u274C Error during shutdown: ${u?.message||u}`),clearTimeout(l),process.exit(1)}};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>a("SIGBREAK")),i}GRe().catch(t=>{so.error(`Server failed to start: ${t?.stack||t?.message||t}`),process.exit(1)});0&&(module.exports={startServer});
535
535
  /*! Bundled license information:
536
536
 
537
537
  negotiator/index.js: