@prompt-optimizer/mcp-server 0.1.0 → 0.1.1

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 (67) hide show
  1. package/README.md +9 -7
  2. package/dist/browser.js +10 -4200
  3. package/dist/chunk-2AOVKKBT.js +7 -0
  4. package/dist/chunk-5QROM7SH.js +3 -0
  5. package/dist/chunk-7FYOSVIN.js +3 -0
  6. package/dist/chunk-AKXNS3YY.js +4 -0
  7. package/dist/chunk-BBXFEEUH.js +43 -0
  8. package/dist/chunk-CHINCAF5.js +33 -0
  9. package/dist/chunk-EJ2IIPFF.js +3 -0
  10. package/dist/chunk-FLQML3XF.js +64 -0
  11. package/dist/chunk-GA7S5A7R.js +3 -0
  12. package/dist/chunk-IABPRAPS.js +3 -0
  13. package/dist/chunk-JE2EBI2C.js +3 -0
  14. package/dist/chunk-JL6XIA4S.js +4 -0
  15. package/dist/chunk-JXWLV6TC.js +12 -0
  16. package/dist/chunk-MUXGFCOV.js +7012 -0
  17. package/dist/chunk-NT2DBZVA.js +3 -0
  18. package/dist/chunk-NVZFDKDX.js +3 -0
  19. package/dist/chunk-PKJ2PK6J.js +106 -0
  20. package/dist/chunk-SDHFVY4F.js +6 -0
  21. package/dist/chunk-TWLLFRFQ.js +6 -0
  22. package/dist/desktop-business.js +4 -1225
  23. package/dist/desktop-comparison-UIIN3WK4.js +3 -0
  24. package/dist/desktop-storage-KJWV2A3P.js +3 -0
  25. package/dist/desktop.js +1 -24
  26. package/dist/dist-OM6QMJNC.js +10 -0
  27. package/dist/dist-YR425RV6.js +3 -0
  28. package/dist/index.js +1 -10
  29. package/dist/legacy.js +97 -26634
  30. package/dist/multipart-parser-XGXMMB2Z.js +4 -0
  31. package/dist/node-2SMUH4FH.js +3 -0
  32. package/dist/node-NX6BPYD5.js +3 -0
  33. package/dist/node-U7LDATXE.js +17 -0
  34. package/dist/registry-H5F4DGAM-2GPEVJMD.js +3 -0
  35. package/dist/src-3F22P42W.js +5 -0
  36. package/dist/start.js +2 -13
  37. package/package.json +10 -1
  38. package/preload-env.cjs +3 -352
  39. package/dist/chunk-3FYJ3FRD.js +0 -57
  40. package/dist/chunk-E7Z4Y3F4.js +0 -36402
  41. package/dist/chunk-GBDJTSRW.js +0 -298
  42. package/dist/chunk-HLCN3DLS.js +0 -19745
  43. package/dist/chunk-HYVN7FZZ.js +0 -4787
  44. package/dist/chunk-MEUCFQGU.js +0 -537
  45. package/dist/chunk-N6AUTPPS.js +0 -10647
  46. package/dist/chunk-Q52SACHI.js +0 -304
  47. package/dist/chunk-Q5B3KFB3.js +0 -31
  48. package/dist/chunk-QSPNNVX3.js +0 -49017
  49. package/dist/chunk-SO4YJHYW.js +0 -13450
  50. package/dist/chunk-SV2GETJH.js +0 -65
  51. package/dist/chunk-TFH2LO2H.js +0 -58
  52. package/dist/chunk-TFJEYQ3G.js +0 -786
  53. package/dist/chunk-TLOFCHZI.js +0 -70
  54. package/dist/chunk-TQGHULC7.js +0 -188
  55. package/dist/chunk-UTOMPKTK.js +0 -2209
  56. package/dist/chunk-XXALDAL7.js +0 -1838
  57. package/dist/chunk-YT3U6B54.js +0 -21
  58. package/dist/desktop-comparison-HDIQ6K45.js +0 -22
  59. package/dist/desktop-storage-YRABQCLF.js +0 -14
  60. package/dist/dist-O5VNBF5I.js +0 -622
  61. package/dist/dist-UMX52UME.js +0 -481
  62. package/dist/multipart-parser-XE6WGDAU.js +0 -373
  63. package/dist/node-2RBNZOSK.js +0 -2225
  64. package/dist/node-4Z3USCHW.js +0 -21
  65. package/dist/node-QHGLD5ST.js +0 -25
  66. package/dist/registry-H5F4DGAM-UHR4F6LL.js +0 -13
  67. package/dist/src-7PBMYCGI.js +0 -1398
@@ -0,0 +1,106 @@
1
+ import { createRequire as __mcpCreateRequire } from "node:module";
2
+ const require = __mcpCreateRequire(import.meta.url);
3
+ import{m as Nh}from"./chunk-BBXFEEUH.js";import{b as Ke,r as sn}from"./chunk-7FYOSVIN.js";import{a as X,c as H,e as $t}from"./chunk-EJ2IIPFF.js";var Dh=H((cL,Mh)=>{function mt(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Mh.exports=mt;mt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};mt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};mt.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0};mt.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};mt.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};mt.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};mt.prototype.start=mt.prototype.try;mt.prototype.errors=function(){return this._errors};mt.prototype.attempts=function(){return this._attempts};mt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],s=i.message,o=(t[s]||0)+1;t[s]=o,o>=n&&(e=i,n=o)}return e}});var Oh=H(ar=>{var fw=Dh();ar.operation=function(t){var e=ar.timeouts(t);return new fw(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};ar.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<e.retries;i++)r.push(this.createTimeout(i,e));return t&&t.forever&&!r.length&&r.push(this.createTimeout(i,e)),r.sort(function(s,o){return s-o}),r};ar.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,r=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return r=Math.min(r,e.maxTimeout),r};ar.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var r in t)typeof t[r]=="function"&&n.push(r)}for(var i=0;i<n.length;i++){var s=n[i],o=t[s];t[s]=function(d){var c=ar.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){c.retry(h)||(h&&(arguments[0]=c.mainError()),p.apply(this,arguments))}),c.attempt(function(){d.apply(t,f)})}.bind(t,o),t[s].options=e}}});var Lh=H((fL,Uh)=>{Uh.exports=Oh()});var Gh=H((pL,sa)=>{"use strict";var pw=Lh(),hw=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],ia=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},mw=(t,e,n)=>{let r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t},gw=t=>hw.includes(t),Fh=(t,e)=>new Promise((n,r)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=pw.operation(e);i.attempt(async s=>{try{n(await t(s))}catch(o){if(!(o instanceof Error)){r(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof ia)i.stop(),r(o.originalError);else if(o instanceof TypeError&&!gw(o.message))i.stop(),r(o);else{mw(o,s,e);try{await e.onFailedAttempt(o)}catch(l){r(l);return}i.retry(o)||r(i.mainError())}}})});sa.exports=Fh;sa.exports.default=Fh;sa.exports.AbortError=ia});var Ju=H((hL,Jh)=>{"use strict";var oa=Object.prototype.hasOwnProperty,Wh=Object.prototype.toString,qh=Object.defineProperty,Bh=Object.getOwnPropertyDescriptor,$h=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Wh.call(e)==="[object Array]"},Vh=function(e){if(!e||Wh.call(e)!=="[object Object]")return!1;var n=oa.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&oa.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||oa.call(e,i)},Hh=function(e,n){qh&&n.name==="__proto__"?qh(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Kh=function(e,n){if(n==="__proto__")if(oa.call(e,n)){if(Bh)return Bh(e,n).value}else return;return e[n]};Jh.exports=function t(){var e,n,r,i,s,o,l=arguments[0],d=1,c=arguments.length,f=!1;for(typeof l=="boolean"&&(f=l,l=arguments[1]||{},d=2),(l==null||typeof l!="object"&&typeof l!="function")&&(l={});d<c;++d)if(e=arguments[d],e!=null)for(n in e)r=Kh(l,n),i=Kh(e,n),l!==i&&(f&&i&&(Vh(i)||(s=$h(i)))?(s?(s=!1,o=r&&$h(r)?r:[]):o=r&&Vh(r)?r:{},Hh(l,{name:n,newValue:t(f,o,i)})):typeof i<"u"&&Hh(l,{name:n,newValue:i}));return l}});var zh=H((mL,_w)=>{_w.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Xh=H((gL,Yh)=>{"use strict";var yw=zh();Yh.exports={pkg:yw}});var Xu=H(gt=>{"use strict";var Zh=gt&&gt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gt,"__esModule",{value:!0});gt.GaxiosError=gt.GAXIOS_ERROR_SYMBOL=void 0;gt.defaultErrorRedactor=jh;var Qh=Zh(Ju()),Aw=Zh(Xh()),zu=Aw.default.pkg;gt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${zu.name}-gaxios-error`);var Yu=class t extends Error{config;response;code;status;error;[gt.GAXIOS_ERROR_SYMBOL]=zu.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&gt.GAXIOS_ERROR_SYMBOL in e&&e[gt.GAXIOS_ERROR_SYMBOL]===zu.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,i){if(super(e,{cause:i}),this.config=n,this.response=r,this.error=i instanceof Error?i:void 0,this.config=(0,Qh.default)(!0,{},n),this.response&&(this.response.config=(0,Qh.default)(!0,{},this.response.config)),this.response){try{this.response.data=Ew(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}i instanceof DOMException?this.code=i.name:i&&typeof i=="object"&&"code"in i&&(typeof i.code=="string"||typeof i.code=="number")&&(this.code=i.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let i="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let o=[];for(let l of e.data.error.errors)typeof l=="object"&&"message"in l&&typeof l.message=="string"&&o.push(l.message);return Object.assign({message:o.join(`
4
+ `)||r,code:s,status:i},e.data.error)}return Object.assign({message:r,code:s,status:i},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};gt.GaxiosError=Yu;function Ew(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function jh(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((o,l)=>{(/^authentication$/i.test(l)||/^authorization$/i.test(l)||/secret/i.test(l))&&s.set(l,e)})}function r(s,o){if(typeof s=="object"&&s!==null&&typeof s[o]=="string"){let l=s[o];(/grant_type=/i.test(l)||/assertion=/i.test(l)||/secret/i.test(l))&&(s[o]=e)}}function i(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((o,l)=>{(["grant_type","assertion"].includes(l)||/secret/.test(l))&&s.set(l,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),i(t.config.data),r(t.config,"body"),i(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(jh({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),i(t.response.data))),t}});var tm=H(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});Qu.getRetryConfig=Tw;async function Tw(t){let e=em(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||ww)(t))return{shouldRetry:!1,config:t.config};let i=Cw(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,i):new Promise(o=>{setTimeout(o,i)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function ww(t){let e=em(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,i]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=i){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function em(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Cw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var ju=H(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.GaxiosInterceptorManager=void 0;var Zu=class extends Set{};aa.GaxiosInterceptorManager=Zu});var im=H(jr=>{"use strict";var Iw=jr&&jr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Zr;Object.defineProperty(jr,"__esModule",{value:!0});jr.Gaxios=void 0;var Sw=Iw(Ju()),vw=X("https"),lr=Xu(),Pw=tm(),nm=X("stream"),rm=ju(),Rw=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),xw=204,la=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new rm.GaxiosInterceptorManager,response:new rm.GaxiosInterceptorManager}}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&&Zr.mergeHeaders(s,n.headers),r&&Zr.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})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Zr.#l(),r={...e};delete r.data;let i=await n(e.url,r),s=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(i,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let i=[];for await(let s of n.data)i.push(s);n.data=Buffer.concat(i.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=lr.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new lr.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof lr.GaxiosError?r=n:n instanceof Error?r=new lr.GaxiosError(n.message,e,void 0,n):r=new lr.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:i,config:s}=await(0,Pw.getRetryConfig)(r);if(i&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===xw)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new lr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),i=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let o of s)i.push(o.trim());for(let o of i)if(o instanceof RegExp){if(o.test(r.toString()))return!1}else if(o instanceof URL){if(o.origin===r.origin)return!1}else if(o.startsWith("*.")||o.startsWith(".")){let l=o.replace(/^\*\./,".");if(r.hostname.endsWith(l))return!1}else if(o===r.origin||o===r.hostname||o===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Zr.mergeHeaders(n,e.headers);let r=(0,Sw.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let o=r.paramsSerializer(r.params);o.startsWith("?")&&(o=o.slice(1));let l=r.url.toString().includes("?")?"&":"?";r.url=r.url+l+o}else{let o=r.url instanceof URL?r.url:new URL(r.url);for(let[l,d]of new URLSearchParams(r.params))o.searchParams.append(l,d);r.url=o}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let i=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof nm.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let o=await Rw();n.set("content-type",`multipart/related; boundary=${o}`),r.body=nm.Readable.from(this.getMultipartRequest(r.multipart,o))}else i?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let o=await Zr.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new o(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new vw.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=lr.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#i(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#i(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let i of e){let s=i.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
5
+ Content-Type: ${s}\r
6
+ \r
7
+ `,typeof i.content=="string"?yield i.content:yield*i.content,yield`\r
8
+ `}yield r}static#s;static#o;static async#a(){return this.#s||=(await import("./dist-OM6QMJNC.js")).HttpsProxyAgent,this.#s}static async#l(){let e=typeof window<"u"&&!!window;return this.#o||=e?window.fetch:(await import("./src-3F22P42W.js")).default,this.#o}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,o)=>{o==="set-cookie"?e.append(o,s):e.set(o,s)});return e}};jr.Gaxios=la;Zr=la});var Le=H(We=>{"use strict";var bw=We&&We.__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]})),kw=We&&We.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bw(e,t,n)};Object.defineProperty(We,"__esModule",{value:!0});We.instance=We.Gaxios=We.GaxiosError=void 0;We.request=Mw;var sm=im();Object.defineProperty(We,"Gaxios",{enumerable:!0,get:function(){return sm.Gaxios}});var Nw=Xu();Object.defineProperty(We,"GaxiosError",{enumerable:!0,get:function(){return Nw.GaxiosError}});kw(ju(),We);We.instance=new sm.Gaxios;async function Mw(t){return We.instance.request(t)}});var ec=H((om,ua)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,i=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",l=1e14,d=14,c=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function m(G){var S,q,$,N=J.prototype={constructor:J,toString:null,valueOf:null},K=new J(1),Q=20,oe=4,ie=-7,ae=21,fe=-1e7,Ee=1e7,tt=!1,nt=1,Se=0,sr={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},or="0123456789abcdefghijklmnopqrstuvwxyz",$u=!0;function J(A,w){var I,U,k,D,F,P,M,L,O=this;if(!(O instanceof J))return new J(A,w);if(w==null){if(A&&A._isBigNumber===!0){O.s=A.s,!A.c||A.e>Ee?O.c=O.e=null:A.e<fe?O.c=[O.e=0]:(O.e=A.e,O.c=A.c.slice());return}if((P=typeof A=="number")&&A*0==0){if(O.s=1/A<0?(A=-A,-1):1,A===~~A){for(D=0,F=A;F>=10;F/=10,D++);D>Ee?O.c=O.e=null:(O.e=D,O.c=[A]);return}L=String(A)}else{if(!n.test(L=String(A)))return $(O,L,P);O.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(D=L.indexOf("."))>-1&&(L=L.replace(".","")),(F=L.search(/e/i))>0?(D<0&&(D=F),D+=+L.slice(F+1),L=L.substring(0,F)):D<0&&(D=L.length)}else{if(T(w,2,or.length,"Base"),w==10&&$u)return O=new J(A),pt(O,Q+O.e+1,oe);if(L=String(A),P=typeof A=="number"){if(A*0!=0)return $(O,L,P,w);if(O.s=1/A<0?(L=L.slice(1),-1):1,J.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(o+A)}else O.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(I=or.slice(0,w),D=F=0,M=L.length;F<M;F++)if(I.indexOf(U=L.charAt(F))<0){if(U=="."){if(F>D){D=M;continue}}else if(!k&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){k=!0,F=-1,D=0;continue}return $(O,String(A),P,w)}P=!1,L=q(L,w,10,O.s),(D=L.indexOf("."))>-1?L=L.replace(".",""):D=L.length}for(F=0;L.charCodeAt(F)===48;F++);for(M=L.length;L.charCodeAt(--M)===48;);if(L=L.slice(F,++M)){if(M-=F,P&&J.DEBUG&&M>15&&(A>c||A!==i(A)))throw Error(o+O.s*A);if((D=D-F-1)>Ee)O.c=O.e=null;else if(D<fe)O.c=[O.e=0];else{if(O.e=D,O.c=[],F=(D+1)%d,D<0&&(F+=d),F<M){for(F&&O.c.push(+L.slice(0,F)),M-=d;F<M;)O.c.push(+L.slice(F,F+=d));F=d-(L=L.slice(F)).length}else F-=M;for(;F--;L+="0");O.c.push(+L)}}else O.c=[O.e=0]}J.clone=m,J.ROUND_UP=0,J.ROUND_DOWN=1,J.ROUND_CEIL=2,J.ROUND_FLOOR=3,J.ROUND_HALF_UP=4,J.ROUND_HALF_DOWN=5,J.ROUND_HALF_EVEN=6,J.ROUND_HALF_CEIL=7,J.ROUND_HALF_FLOOR=8,J.EUCLID=9,J.config=J.set=function(A){var w,I;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(w="DECIMAL_PLACES")&&(I=A[w],T(I,0,h,w),Q=I),A.hasOwnProperty(w="ROUNDING_MODE")&&(I=A[w],T(I,0,8,w),oe=I),A.hasOwnProperty(w="EXPONENTIAL_AT")&&(I=A[w],I&&I.pop?(T(I[0],-h,0,w),T(I[1],0,h,w),ie=I[0],ae=I[1]):(T(I,-h,h,w),ie=-(ae=I<0?-I:I))),A.hasOwnProperty(w="RANGE"))if(I=A[w],I&&I.pop)T(I[0],-h,-1,w),T(I[1],1,h,w),fe=I[0],Ee=I[1];else if(T(I,-h,h,w),I)fe=-(Ee=I<0?-I:I);else throw Error(s+w+" cannot be zero: "+I);if(A.hasOwnProperty(w="CRYPTO"))if(I=A[w],I===!!I)if(I)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))tt=I;else throw tt=!I,Error(s+"crypto unavailable");else tt=I;else throw Error(s+w+" not true or false: "+I);if(A.hasOwnProperty(w="MODULO_MODE")&&(I=A[w],T(I,0,9,w),nt=I),A.hasOwnProperty(w="POW_PRECISION")&&(I=A[w],T(I,0,h,w),Se=I),A.hasOwnProperty(w="FORMAT"))if(I=A[w],typeof I=="object")sr=I;else throw Error(s+w+" not an object: "+I);if(A.hasOwnProperty(w="ALPHABET"))if(I=A[w],typeof I=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(I))$u=I.slice(0,10)=="0123456789",or=I;else throw Error(s+w+" invalid: "+I)}else throw Error(s+"Object expected: "+A);return{DECIMAL_PLACES:Q,ROUNDING_MODE:oe,EXPONENTIAL_AT:[ie,ae],RANGE:[fe,Ee],CRYPTO:tt,MODULO_MODE:nt,POW_PRECISION:Se,FORMAT:sr,ALPHABET:or}},J.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!J.DEBUG)return!0;var w,I,U=A.c,k=A.e,D=A.s;e:if({}.toString.call(U)=="[object Array]"){if((D===1||D===-1)&&k>=-h&&k<=h&&k===i(k)){if(U[0]===0){if(k===0&&U.length===1)return!0;break e}if(w=(k+1)%d,w<1&&(w+=d),String(U[0]).length==w){for(w=0;w<U.length;w++)if(I=U[w],I<0||I>=l||I!==i(I))break e;if(I!==0)return!0}}}else if(U===null&&k===null&&(D===null||D===1||D===-1))return!0;throw Error(s+"Invalid BigNumber: "+A)},J.maximum=J.max=function(){return kh(arguments,-1)},J.minimum=J.min=function(){return kh(arguments,1)},J.random=(function(){var A=9007199254740992,w=Math.random()*A&2097151?function(){return i(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var U,k,D,F,P,M=0,L=[],O=new J(K);if(I==null?I=Q:T(I,0,h),F=r(I/d),tt)if(crypto.getRandomValues){for(U=crypto.getRandomValues(new Uint32Array(F*=2));M<F;)P=U[M]*131072+(U[M+1]>>>11),P>=9e15?(k=crypto.getRandomValues(new Uint32Array(2)),U[M]=k[0],U[M+1]=k[1]):(L.push(P%1e14),M+=2);M=F/2}else if(crypto.randomBytes){for(U=crypto.randomBytes(F*=7);M<F;)P=(U[M]&31)*281474976710656+U[M+1]*1099511627776+U[M+2]*4294967296+U[M+3]*16777216+(U[M+4]<<16)+(U[M+5]<<8)+U[M+6],P>=9e15?crypto.randomBytes(7).copy(U,M):(L.push(P%1e14),M+=7);M=F/7}else throw tt=!1,Error(s+"crypto unavailable");if(!tt)for(;M<F;)P=w(),P<9e15&&(L[M++]=P%1e14);for(F=L[--M],I%=d,F&&I&&(P=f[d-I],L[M]=i(F/P)*P);L[M]===0;L.pop(),M--);if(M<0)L=[D=0];else{for(D=-1;L[0]===0;L.splice(0,1),D-=d);for(M=1,P=L[0];P>=10;P/=10,M++);M<d&&(D-=d-M)}return O.e=D,O.c=L,O}})(),J.sum=function(){for(var A=1,w=arguments,I=new J(w[0]);A<w.length;)I=I.plus(w[A++]);return I},q=(function(){var A="0123456789";function w(I,U,k,D){for(var F,P=[0],M,L=0,O=I.length;L<O;){for(M=P.length;M--;P[M]*=U);for(P[0]+=D.indexOf(I.charAt(L++)),F=0;F<P.length;F++)P[F]>k-1&&(P[F+1]==null&&(P[F+1]=0),P[F+1]+=P[F]/k|0,P[F]%=k)}return P.reverse()}return function(I,U,k,D,F){var P,M,L,O,V,j,ee,pe,_e=I.indexOf("."),xe=Q,ce=oe;for(_e>=0&&(O=Se,Se=0,I=I.replace(".",""),pe=new J(U),j=pe.pow(I.length-_e),Se=O,pe.c=w(x(_(j.c),j.e,"0"),10,k,A),pe.e=pe.c.length),ee=w(I,U,k,F?(P=or,A):(P=A,or)),L=O=ee.length;ee[--O]==0;ee.pop());if(!ee[0])return P.charAt(0);if(_e<0?--L:(j.c=ee,j.e=L,j.s=D,j=S(j,pe,xe,ce,k),ee=j.c,V=j.r,L=j.e),M=L+xe+1,_e=ee[M],O=k/2,V=V||M<0||ee[M+1]!=null,V=ce<4?(_e!=null||V)&&(ce==0||ce==(j.s<0?3:2)):_e>O||_e==O&&(ce==4||V||ce==6&&ee[M-1]&1||ce==(j.s<0?8:7)),M<1||!ee[0])I=V?x(P.charAt(1),-xe,P.charAt(0)):P.charAt(0);else{if(ee.length=M,V)for(--k;++ee[--M]>k;)ee[M]=0,M||(++L,ee=[1].concat(ee));for(O=ee.length;!ee[--O];);for(_e=0,I="";_e<=O;I+=P.charAt(ee[_e++]));I=x(I,L,P.charAt(0))}return I}})(),S=(function(){function A(U,k,D){var F,P,M,L,O=0,V=U.length,j=k%p,ee=k/p|0;for(U=U.slice();V--;)M=U[V]%p,L=U[V]/p|0,F=ee*M+L*j,P=j*M+F%p*p+O,O=(P/D|0)+(F/p|0)+ee*L,U[V]=P%D;return O&&(U=[O].concat(U)),U}function w(U,k,D,F){var P,M;if(D!=F)M=D>F?1:-1;else for(P=M=0;P<D;P++)if(U[P]!=k[P]){M=U[P]>k[P]?1:-1;break}return M}function I(U,k,D,F){for(var P=0;D--;)U[D]-=P,P=U[D]<k[D]?1:0,U[D]=P*F+U[D]-k[D];for(;!U[0]&&U.length>1;U.splice(0,1));}return function(U,k,D,F,P){var M,L,O,V,j,ee,pe,_e,xe,ce,he,Ge,ra,Ku,Wu,Bt,js,ht=U.s==k.s?1:-1,He=U.c,ye=k.c;if(!He||!He[0]||!ye||!ye[0])return new J(!U.s||!k.s||(He?ye&&He[0]==ye[0]:!ye)?NaN:He&&He[0]==0||!ye?ht*0:ht/0);for(_e=new J(ht),xe=_e.c=[],L=U.e-k.e,ht=D+L+1,P||(P=l,L=g(U.e/d)-g(k.e/d),ht=ht/d|0),O=0;ye[O]==(He[O]||0);O++);if(ye[O]>(He[O]||0)&&L--,ht<0)xe.push(1),V=!0;else{for(Ku=He.length,Bt=ye.length,O=0,ht+=2,j=i(P/(ye[0]+1)),j>1&&(ye=A(ye,j,P),He=A(He,j,P),Bt=ye.length,Ku=He.length),ra=Bt,ce=He.slice(0,Bt),he=ce.length;he<Bt;ce[he++]=0);js=ye.slice(),js=[0].concat(js),Wu=ye[0],ye[1]>=P/2&&Wu++;do{if(j=0,M=w(ye,ce,Bt,he),M<0){if(Ge=ce[0],Bt!=he&&(Ge=Ge*P+(ce[1]||0)),j=i(Ge/Wu),j>1)for(j>=P&&(j=P-1),ee=A(ye,j,P),pe=ee.length,he=ce.length;w(ee,ce,pe,he)==1;)j--,I(ee,Bt<pe?js:ye,pe,P),pe=ee.length,M=1;else j==0&&(M=j=1),ee=ye.slice(),pe=ee.length;if(pe<he&&(ee=[0].concat(ee)),I(ce,ee,he,P),he=ce.length,M==-1)for(;w(ye,ce,Bt,he)<1;)j++,I(ce,Bt<he?js:ye,he,P),he=ce.length}else M===0&&(j++,ce=[0]);xe[O++]=j,ce[0]?ce[he++]=He[ra]||0:(ce=[He[ra]],he=1)}while((ra++<Ku||ce[0]!=null)&&ht--);V=ce[0]!=null,xe[0]||xe.splice(0,1)}if(P==l){for(O=1,ht=xe[0];ht>=10;ht/=10,O++);pt(_e,D+(_e.e=O+L*d-1)+1,F,V)}else _e.e=L,_e.r=+V;return _e}})();function Vu(A,w,I,U){var k,D,F,P,M;if(I==null?I=oe:T(I,0,8),!A.c)return A.toString();if(k=A.c[0],F=A.e,w==null)M=_(A.c),M=U==1||U==2&&(F<=ie||F>=ae)?R(M,F):x(M,F,"0");else if(A=pt(new J(A),w,I),D=A.e,M=_(A.c),P=M.length,U==1||U==2&&(w<=D||D<=ie)){for(;P<w;M+="0",P++);M=R(M,D)}else if(w-=F+(U===2&&D>F),M=x(M,D,"0"),D+1>P){if(--w>0)for(M+=".";w--;M+="0");}else if(w+=D-P,w>0)for(D+1==P&&(M+=".");w--;M+="0");return A.s<0&&k?"-"+M:M}function kh(A,w){for(var I,U,k=1,D=new J(A[0]);k<A.length;k++)U=new J(A[k]),(!U.s||(I=y(D,U))===w||I===0&&D.s===w)&&(D=U);return D}function Hu(A,w,I){for(var U=1,k=w.length;!w[--k];w.pop());for(k=w[0];k>=10;k/=10,U++);return(I=U+I*d-1)>Ee?A.c=A.e=null:I<fe?A.c=[A.e=0]:(A.e=I,A.c=w),A}$=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,w=/^([^.]+)\.$/,I=/^\.([^.]+)$/,U=/^-?(Infinity|NaN)$/,k=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(D,F,P,M){var L,O=P?F:F.replace(k,"");if(U.test(O))D.s=isNaN(O)?null:O<0?-1:1;else{if(!P&&(O=O.replace(A,function(V,j,ee){return L=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!M||M==L?j:V}),M&&(L=M,O=O.replace(w,"$1").replace(I,"0.$1")),F!=O))return new J(O,L);if(J.DEBUG)throw Error(s+"Not a"+(M?" base "+M:"")+" number: "+F);D.s=null}D.c=D.e=null}})();function pt(A,w,I,U){var k,D,F,P,M,L,O,V=A.c,j=f;if(V){e:{for(k=1,P=V[0];P>=10;P/=10,k++);if(D=w-k,D<0)D+=d,F=w,M=V[L=0],O=i(M/j[k-F-1]%10);else if(L=r((D+1)/d),L>=V.length)if(U){for(;V.length<=L;V.push(0));M=O=0,k=1,D%=d,F=D-d+1}else break e;else{for(M=P=V[L],k=1;P>=10;P/=10,k++);D%=d,F=D-d+k,O=F<0?0:i(M/j[k-F-1]%10)}if(U=U||w<0||V[L+1]!=null||(F<0?M:M%j[k-F-1]),U=I<4?(O||U)&&(I==0||I==(A.s<0?3:2)):O>5||O==5&&(I==4||U||I==6&&(D>0?F>0?M/j[k-F]:0:V[L-1])%10&1||I==(A.s<0?8:7)),w<1||!V[0])return V.length=0,U?(w-=A.e+1,V[0]=j[(d-w%d)%d],A.e=-w||0):V[0]=A.e=0,A;if(D==0?(V.length=L,P=1,L--):(V.length=L+1,P=j[d-D],V[L]=F>0?i(M/j[k-F]%j[F])*P:0),U)for(;;)if(L==0){for(D=1,F=V[0];F>=10;F/=10,D++);for(F=V[0]+=P,P=1;F>=10;F/=10,P++);D!=P&&(A.e++,V[0]==l&&(V[0]=1));break}else{if(V[L]+=P,V[L]!=l)break;V[L--]=0,P=1}for(D=V.length;V[--D]===0;V.pop());}A.e>Ee?A.c=A.e=null:A.e<fe&&(A.c=[A.e=0])}return A}function rn(A){var w,I=A.e;return I===null?A.toString():(w=_(A.c),w=I<=ie||I>=ae?R(w,I):x(w,I,"0"),A.s<0?"-"+w:w)}return N.absoluteValue=N.abs=function(){var A=new J(this);return A.s<0&&(A.s=1),A},N.comparedTo=function(A,w){return y(this,new J(A,w))},N.decimalPlaces=N.dp=function(A,w){var I,U,k,D=this;if(A!=null)return T(A,0,h),w==null?w=oe:T(w,0,8),pt(new J(D),A+D.e+1,w);if(!(I=D.c))return null;if(U=((k=I.length-1)-g(this.e/d))*d,k=I[k])for(;k%10==0;k/=10,U--);return U<0&&(U=0),U},N.dividedBy=N.div=function(A,w){return S(this,new J(A,w),Q,oe)},N.dividedToIntegerBy=N.idiv=function(A,w){return S(this,new J(A,w),0,1)},N.exponentiatedBy=N.pow=function(A,w){var I,U,k,D,F,P,M,L,O,V=this;if(A=new J(A),A.c&&!A.isInteger())throw Error(s+"Exponent not an integer: "+rn(A));if(w!=null&&(w=new J(w)),P=A.e>14,!V.c||!V.c[0]||V.c[0]==1&&!V.e&&V.c.length==1||!A.c||!A.c[0])return O=new J(Math.pow(+rn(V),P?A.s*(2-C(A)):+rn(A))),w?O.mod(w):O;if(M=A.s<0,w){if(w.c?!w.c[0]:!w.s)return new J(NaN);U=!M&&V.isInteger()&&w.isInteger(),U&&(V=V.mod(w))}else{if(A.e>9&&(V.e>0||V.e<-1||(V.e==0?V.c[0]>1||P&&V.c[1]>=24e7:V.c[0]<8e13||P&&V.c[0]<=9999975e7)))return D=V.s<0&&C(A)?-0:0,V.e>-1&&(D=1/D),new J(M?1/D:D);Se&&(D=r(Se/d+2))}for(P?(I=new J(.5),M&&(A.s=1),L=C(A)):(k=Math.abs(+rn(A)),L=k%2),O=new J(K);;){if(L){if(O=O.times(V),!O.c)break;D?O.c.length>D&&(O.c.length=D):U&&(O=O.mod(w))}if(k){if(k=i(k/2),k===0)break;L=k%2}else if(A=A.times(I),pt(A,A.e+1,1),A.e>14)L=C(A);else{if(k=+rn(A),k===0)break;L=k%2}V=V.times(V),D?V.c&&V.c.length>D&&(V.c.length=D):U&&(V=V.mod(w))}return U?O:(M&&(O=K.div(O)),w?O.mod(w):D?pt(O,Se,oe,F):O)},N.integerValue=function(A){var w=new J(this);return A==null?A=oe:T(A,0,8),pt(w,w.e+1,A)},N.isEqualTo=N.eq=function(A,w){return y(this,new J(A,w))===0},N.isFinite=function(){return!!this.c},N.isGreaterThan=N.gt=function(A,w){return y(this,new J(A,w))>0},N.isGreaterThanOrEqualTo=N.gte=function(A,w){return(w=y(this,new J(A,w)))===1||w===0},N.isInteger=function(){return!!this.c&&g(this.e/d)>this.c.length-2},N.isLessThan=N.lt=function(A,w){return y(this,new J(A,w))<0},N.isLessThanOrEqualTo=N.lte=function(A,w){return(w=y(this,new J(A,w)))===-1||w===0},N.isNaN=function(){return!this.s},N.isNegative=function(){return this.s<0},N.isPositive=function(){return this.s>0},N.isZero=function(){return!!this.c&&this.c[0]==0},N.minus=function(A,w){var I,U,k,D,F=this,P=F.s;if(A=new J(A,w),w=A.s,!P||!w)return new J(NaN);if(P!=w)return A.s=-w,F.plus(A);var M=F.e/d,L=A.e/d,O=F.c,V=A.c;if(!M||!L){if(!O||!V)return O?(A.s=-w,A):new J(V?F:NaN);if(!O[0]||!V[0])return V[0]?(A.s=-w,A):new J(O[0]?F:oe==3?-0:0)}if(M=g(M),L=g(L),O=O.slice(),P=M-L){for((D=P<0)?(P=-P,k=O):(L=M,k=V),k.reverse(),w=P;w--;k.push(0));k.reverse()}else for(U=(D=(P=O.length)<(w=V.length))?P:w,P=w=0;w<U;w++)if(O[w]!=V[w]){D=O[w]<V[w];break}if(D&&(k=O,O=V,V=k,A.s=-A.s),w=(U=V.length)-(I=O.length),w>0)for(;w--;O[I++]=0);for(w=l-1;U>P;){if(O[--U]<V[U]){for(I=U;I&&!O[--I];O[I]=w);--O[I],O[U]+=l}O[U]-=V[U]}for(;O[0]==0;O.splice(0,1),--L);return O[0]?Hu(A,O,L):(A.s=oe==3?-1:1,A.c=[A.e=0],A)},N.modulo=N.mod=function(A,w){var I,U,k=this;return A=new J(A,w),!k.c||!A.s||A.c&&!A.c[0]?new J(NaN):!A.c||k.c&&!k.c[0]?new J(k):(nt==9?(U=A.s,A.s=1,I=S(k,A,0,3),A.s=U,I.s*=U):I=S(k,A,0,nt),A=k.minus(I.times(A)),!A.c[0]&&nt==1&&(A.s=k.s),A)},N.multipliedBy=N.times=function(A,w){var I,U,k,D,F,P,M,L,O,V,j,ee,pe,_e,xe,ce=this,he=ce.c,Ge=(A=new J(A,w)).c;if(!he||!Ge||!he[0]||!Ge[0])return!ce.s||!A.s||he&&!he[0]&&!Ge||Ge&&!Ge[0]&&!he?A.c=A.e=A.s=null:(A.s*=ce.s,!he||!Ge?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(U=g(ce.e/d)+g(A.e/d),A.s*=ce.s,M=he.length,V=Ge.length,M<V&&(pe=he,he=Ge,Ge=pe,k=M,M=V,V=k),k=M+V,pe=[];k--;pe.push(0));for(_e=l,xe=p,k=V;--k>=0;){for(I=0,j=Ge[k]%xe,ee=Ge[k]/xe|0,F=M,D=k+F;D>k;)L=he[--F]%xe,O=he[F]/xe|0,P=ee*L+O*j,L=j*L+P%xe*xe+pe[D]+I,I=(L/_e|0)+(P/xe|0)+ee*O,pe[D--]=L%_e;pe[D]=I}return I?++U:pe.splice(0,1),Hu(A,pe,U)},N.negated=function(){var A=new J(this);return A.s=-A.s||null,A},N.plus=function(A,w){var I,U=this,k=U.s;if(A=new J(A,w),w=A.s,!k||!w)return new J(NaN);if(k!=w)return A.s=-w,U.minus(A);var D=U.e/d,F=A.e/d,P=U.c,M=A.c;if(!D||!F){if(!P||!M)return new J(k/0);if(!P[0]||!M[0])return M[0]?A:new J(P[0]?U:k*0)}if(D=g(D),F=g(F),P=P.slice(),k=D-F){for(k>0?(F=D,I=M):(k=-k,I=P),I.reverse();k--;I.push(0));I.reverse()}for(k=P.length,w=M.length,k-w<0&&(I=M,M=P,P=I,w=k),k=0;w;)k=(P[--w]=P[w]+M[w]+k)/l|0,P[w]=l===P[w]?0:P[w]%l;return k&&(P=[k].concat(P),++F),Hu(A,P,F)},N.precision=N.sd=function(A,w){var I,U,k,D=this;if(A!=null&&A!==!!A)return T(A,1,h),w==null?w=oe:T(w,0,8),pt(new J(D),A,w);if(!(I=D.c))return null;if(k=I.length-1,U=k*d+1,k=I[k]){for(;k%10==0;k/=10,U--);for(k=I[0];k>=10;k/=10,U++);}return A&&D.e+1>U&&(U=D.e+1),U},N.shiftedBy=function(A){return T(A,-c,c),this.times("1e"+A)},N.squareRoot=N.sqrt=function(){var A,w,I,U,k,D=this,F=D.c,P=D.s,M=D.e,L=Q+4,O=new J("0.5");if(P!==1||!F||!F[0])return new J(!P||P<0&&(!F||F[0])?NaN:F?D:1/0);if(P=Math.sqrt(+rn(D)),P==0||P==1/0?(w=_(F),(w.length+M)%2==0&&(w+="0"),P=Math.sqrt(+w),M=g((M+1)/2)-(M<0||M%2),P==1/0?w="5e"+M:(w=P.toExponential(),w=w.slice(0,w.indexOf("e")+1)+M),I=new J(w)):I=new J(P+""),I.c[0]){for(M=I.e,P=M+L,P<3&&(P=0);;)if(k=I,I=O.times(k.plus(S(D,k,L,1))),_(k.c).slice(0,P)===(w=_(I.c)).slice(0,P))if(I.e<M&&--P,w=w.slice(P-3,P+1),w=="9999"||!U&&w=="4999"){if(!U&&(pt(k,k.e+Q+2,0),k.times(k).eq(D))){I=k;break}L+=4,P+=4,U=1}else{(!+w||!+w.slice(1)&&w.charAt(0)=="5")&&(pt(I,I.e+Q+2,1),A=!I.times(I).eq(D));break}}return pt(I,I.e+Q+1,oe,A)},N.toExponential=function(A,w){return A!=null&&(T(A,0,h),A++),Vu(this,A,w,1)},N.toFixed=function(A,w){return A!=null&&(T(A,0,h),A=A+this.e+1),Vu(this,A,w)},N.toFormat=function(A,w,I){var U,k=this;if(I==null)A!=null&&w&&typeof w=="object"?(I=w,w=null):A&&typeof A=="object"?(I=A,A=w=null):I=sr;else if(typeof I!="object")throw Error(s+"Argument not an object: "+I);if(U=k.toFixed(A,w),k.c){var D,F=U.split("."),P=+I.groupSize,M=+I.secondaryGroupSize,L=I.groupSeparator||"",O=F[0],V=F[1],j=k.s<0,ee=j?O.slice(1):O,pe=ee.length;if(M&&(D=P,P=M,M=D,pe-=D),P>0&&pe>0){for(D=pe%P||P,O=ee.substr(0,D);D<pe;D+=P)O+=L+ee.substr(D,P);M>0&&(O+=L+ee.slice(D)),j&&(O="-"+O)}U=V?O+(I.decimalSeparator||"")+((M=+I.fractionGroupSize)?V.replace(new RegExp("\\d{"+M+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):V):O}return(I.prefix||"")+U+(I.suffix||"")},N.toFraction=function(A){var w,I,U,k,D,F,P,M,L,O,V,j,ee=this,pe=ee.c;if(A!=null&&(P=new J(A),!P.isInteger()&&(P.c||P.s!==1)||P.lt(K)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+rn(P));if(!pe)return new J(ee);for(w=new J(K),L=I=new J(K),U=M=new J(K),j=_(pe),D=w.e=j.length-ee.e-1,w.c[0]=f[(F=D%d)<0?d+F:F],A=!A||P.comparedTo(w)>0?D>0?w:L:P,F=Ee,Ee=1/0,P=new J(j),M.c[0]=0;O=S(P,w,0,1),k=I.plus(O.times(U)),k.comparedTo(A)!=1;)I=U,U=k,L=M.plus(O.times(k=L)),M=k,w=P.minus(O.times(k=w)),P=k;return k=S(A.minus(I),U,0,1),M=M.plus(k.times(L)),I=I.plus(k.times(U)),M.s=L.s=ee.s,D=D*2,V=S(L,U,D,oe).minus(ee).abs().comparedTo(S(M,I,D,oe).minus(ee).abs())<1?[L,U]:[M,I],Ee=F,V},N.toNumber=function(){return+rn(this)},N.toPrecision=function(A,w){return A!=null&&T(A,1,h),Vu(this,A,w,2)},N.toString=function(A){var w,I=this,U=I.s,k=I.e;return k===null?U?(w="Infinity",U<0&&(w="-"+w)):w="NaN":(A==null?w=k<=ie||k>=ae?R(_(I.c),k):x(_(I.c),k,"0"):A===10&&$u?(I=pt(new J(I),Q+k+1,oe),w=x(_(I.c),I.e,"0")):(T(A,2,or.length,"Base"),w=q(x(_(I.c),k,"0"),10,A,U,!0)),U<0&&I.c[0]&&(w="-"+w)),w},N.valueOf=N.toJSON=function(){return rn(this)},N._isBigNumber=!0,G!=null&&J.set(G),J}function g(G){var S=G|0;return G>0||G===S?S:S-1}function _(G){for(var S,q,$=1,N=G.length,K=G[0]+"";$<N;){for(S=G[$++]+"",q=d-S.length;q--;S="0"+S);K+=S}for(N=K.length;K.charCodeAt(--N)===48;);return K.slice(0,N+1||1)}function y(G,S){var q,$,N=G.c,K=S.c,Q=G.s,oe=S.s,ie=G.e,ae=S.e;if(!Q||!oe)return null;if(q=N&&!N[0],$=K&&!K[0],q||$)return q?$?0:-oe:Q;if(Q!=oe)return Q;if(q=Q<0,$=ie==ae,!N||!K)return $?0:!N^q?1:-1;if(!$)return ie>ae^q?1:-1;for(oe=(ie=N.length)<(ae=K.length)?ie:ae,Q=0;Q<oe;Q++)if(N[Q]!=K[Q])return N[Q]>K[Q]^q?1:-1;return ie==ae?0:ie>ae^q?1:-1}function T(G,S,q,$){if(G<S||G>q||G!==i(G))throw Error(s+($||"Argument")+(typeof G=="number"?G<S||G>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(G))}function C(G){var S=G.c.length-1;return g(G.e/d)==S&&G.c[S]%2!=0}function R(G,S){return(G.length>1?G.charAt(0)+"."+G.slice(1):G)+(S<0?"e":"e+")+S}function x(G,S,q){var $,N;if(S<0){for(N=q+".";++S;N+=q);G=N+G}else if($=G.length,++S>$){for(N=q,S-=$;--S;N+=q);G+=N}else S<$&&(G=G.slice(0,S)+"."+G.slice(S));return G}e=m(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof ua<"u"&&ua.exports?ua.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(om)});var cm=H((wL,um)=>{var am=ec(),lm=um.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function l(c){return n.lastIndex=0,n.test(c)?'"'+c.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function d(c,f){var p,h,m,g,_=r,y,T=f[c],C=T!=null&&(T instanceof am||am.isBigNumber(T));switch(T&&typeof T=="object"&&typeof T.toJSON=="function"&&(T=T.toJSON(c)),typeof o=="function"&&(T=o.call(f,c,T)),typeof T){case"string":return C?T:l(T);case"number":return isFinite(T)?String(T):"null";case"boolean":case"null":case"bigint":return String(T);case"object":if(!T)return"null";if(r+=i,y=[],Object.prototype.toString.apply(T)==="[object Array]"){for(g=T.length,p=0;p<g;p+=1)y[p]=d(p,T)||"null";return m=y.length===0?"[]":r?`[
9
+ `+r+y.join(`,
10
+ `+r)+`
11
+ `+_+"]":"["+y.join(",")+"]",r=_,m}if(o&&typeof o=="object")for(g=o.length,p=0;p<g;p+=1)typeof o[p]=="string"&&(h=o[p],m=d(h,T),m&&y.push(l(h)+(r?": ":":")+m));else Object.keys(T).forEach(function(R){var x=d(R,T);x&&y.push(l(R)+(r?": ":":")+x)});return m=y.length===0?"{}":r?`{
12
+ `+r+y.join(`,
13
+ `+r)+`
14
+ `+_+"}":"{"+y.join(",")+"}",r=_,m}}typeof lm.stringify!="function"&&(lm.stringify=function(c,f,p){var h;if(r="",i="",typeof p=="number")for(h=0;h<p;h+=1)i+=" ";else typeof p=="string"&&(i=p);if(o=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return d("",{"":c})})})()});var fm=H((CL,dm)=>{var ca=null,Dw=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Ow=/(?: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)/,Uw=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:`
15
+ `,r:"\r",t:" "},s,o=function(_){throw{name:"SyntaxError",message:_,at:n,text:s}},l=function(_){return _&&_!==r&&o("Expected '"+_+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},d=function(){var _,y="";for(r==="-"&&(y="-",l("-"));r>="0"&&r<="9";)y+=r,l();if(r===".")for(y+=".";l()&&r>="0"&&r<="9";)y+=r;if(r==="e"||r==="E")for(y+=r,l(),(r==="-"||r==="+")&&(y+=r,l());r>="0"&&r<="9";)y+=r,l();if(_=+y,!isFinite(_))o("Bad number");else return ca==null&&(ca=ec()),y.length>15?e.storeAsString?y:e.useNativeBigInt?BigInt(y):new ca(y):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new ca(_):_},c=function(){var _,y,T="",C;if(r==='"')for(var R=n;l();){if(r==='"')return n-1>R&&(T+=s.substring(R,n-1)),l(),T;if(r==="\\"){if(n-1>R&&(T+=s.substring(R,n-1)),l(),r==="u"){for(C=0,y=0;y<4&&(_=parseInt(l(),16),!!isFinite(_));y+=1)C=C*16+_;T+=String.fromCharCode(C)}else if(typeof i[r]=="string")T+=i[r];else break;R=n}}o("Bad string")},f=function(){for(;r&&r<=" ";)l()},p=function(){switch(r){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}o("Unexpected '"+r+"'")},h,m=function(){var _=[];if(r==="["){if(l("["),f(),r==="]")return l("]"),_;for(;r;){if(_.push(h()),f(),r==="]")return l("]"),_;l(","),f()}}o("Bad array")},g=function(){var _,y=Object.create(null);if(r==="{"){if(l("{"),f(),r==="}")return l("}"),y;for(;r;){if(_=c(),f(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(y,_)&&o('Duplicate key "'+_+'"'),Dw.test(_)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():y[_]=h():Ow.test(_)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():y[_]=h():y[_]=h(),f(),r==="}")return l("}"),y;l(","),f()}}o("Bad object")};return h=function(){switch(f(),r){case"{":return g();case"[":return m();case'"':return c();case"-":return d();default:return r>="0"&&r<="9"?d():p()}},function(_,y){var T;return s=_+"",n=0,r=" ",T=h(),f(),r&&o("Syntax error"),typeof y=="function"?(function C(R,x){var G,S,q=R[x];return q&&typeof q=="object"&&Object.keys(q).forEach(function($){S=C(q,$),S!==void 0?q[$]=S:delete q[$]}),y.call(R,x,q)})({"":T},""):T}};dm.exports=Uw});var mm=H((IL,da)=>{var pm=cm().stringify,hm=fm();da.exports=function(t){return{parse:hm(t),stringify:pm}};da.exports.parse=hm();da.exports.stringify=pm});var tc=H(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.GCE_LINUX_BIOS_PATHS=void 0;St.isGoogleCloudServerless=ym;St.isGoogleComputeEngineLinux=Am;St.isGoogleComputeEngineMACAddress=Em;St.isGoogleComputeEngine=Tm;St.detectGCPResidency=Fw;var gm=X("fs"),_m=X("os");St.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Lw=/^42:01/;function ym(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Am(){if((0,_m.platform)()!=="linux")return!1;try{(0,gm.statSync)(St.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,gm.readFileSync)(St.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Em(){let t=(0,_m.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(Lw.test(n))return!0}return!1}function Tm(){return Am()||Em()}function Fw(){return ym()||Tm()}});var wm=H(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.Colours=void 0;var qe=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="")}};fa.Colours=qe;qe.enabled=!1;qe.reset="";qe.bright="";qe.dim="";qe.red="";qe.green="";qe.yellow="";qe.blue="";qe.magenta="";qe.cyan="";qe.white="";qe.grey="";qe.refresh()});var vm=H(me=>{"use strict";var Gw=me&&me.__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]})),qw=me&&me.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Cm=me&&me.__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"&&Gw(n,e,r[i]);return qw(n,e),n}})();Object.defineProperty(me,"__esModule",{value:!0});me.env=me.DebugLogBackendBase=me.placeholder=me.AdhocDebugLogger=me.LogSeverity=void 0;me.getNodeBackend=rc;me.getDebugBackend=$w;me.getStructuredBackend=Vw;me.setBackend=Hw;me.log=Sm;var Bw=X("events"),eo=Cm(X("process")),Im=Cm(X("util")),rt=wm(),vt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(vt||(me.LogSeverity=vt={}));var to=class extends Bw.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(vt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(vt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(vt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(vt.ERROR,...r),this.func.sublog=r=>Sm(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)}};me.AdhocDebugLogger=to;me.placeholder=new to("",()=>{}).func;var ei=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=eo.env[me.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)}}};me.DebugLogBackendBase=ei;var nc=class extends ei{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=`${rt.Colours.green}${e}${rt.Colours.reset}`,o=`${rt.Colours.yellow}${eo.pid}${rt.Colours.reset}`,l;switch(n.severity){case vt.ERROR:l=`${rt.Colours.red}${n.severity}${rt.Colours.reset}`;break;case vt.INFO:l=`${rt.Colours.magenta}${n.severity}${rt.Colours.reset}`;break;case vt.WARNING:l=`${rt.Colours.yellow}${n.severity}${rt.Colours.reset}`;break;default:l=(i=n.severity)!==null&&i!==void 0?i:vt.DEFAULT;break}let d=Im.formatWithOptions({colors:rt.Colours.enabled},...r),c=Object.assign({},n);delete c.severity;let f=Object.getOwnPropertyNames(c).length?JSON.stringify(c):"",p=f?`${rt.Colours.grey}${f}${rt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",o,s,l,d,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function rc(){return new nc}var ic=class extends ei{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=eo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";eo.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function $w(t){return new ic(t)}var sc=class extends ei{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 l=(o=i.severity)!==null&&o!==void 0?o:vt.INFO,d=Object.assign({severity:l,message:Im.format(...s)},i),c=JSON.stringify(d);r?r(i,c):console.log("%s",c)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Vw(t){return new sc(t)}me.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var oc=new Map,it;function Hw(t){it=t,oc.clear()}function Sm(t,e){if(!it&&!eo.env[me.env.nodeEnables]||!t)return me.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=oc.get(t);if(n)return n.func;if(it===null)return me.placeholder;it===void 0&&(it=rc());let r=(()=>{let i;return new to(t,(o,...l)=>{if(i!==it){if(it===null)return;it===void 0&&(it=rc()),i=it}it?.log(t,o,...l)})})();return oc.set(t,r),r.func}});var ac=H(ur=>{"use strict";var Kw=ur&&ur.__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]})),Ww=ur&&ur.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Kw(e,t,n)};Object.defineProperty(ur,"__esModule",{value:!0});Ww(vm(),ur)});var ro=H(te=>{"use strict";var Rm=te&&te.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Jw=te&&te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zw=te&&te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&Rm(n,e,r[i]);return Jw(n,e),n}})(),Yw=te&&te.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Rm(e,t,n)};Object.defineProperty(te,"__esModule",{value:!0});te.gcpResidencyCache=te.METADATA_SERVER_DETECTION=te.HEADERS=te.HEADER_VALUE=te.HEADER_NAME=te.SECONDARY_HOST_ADDRESS=te.HOST_ADDRESS=te.BASE_PATH=void 0;te.instance=tC;te.project=nC;te.universe=rC;te.bulk=iC;te.isAvailable=oC;te.resetIsAvailableCache=aC;te.getGCPResidency=cc;te.setGCPResidency=xm;te.requestTimeout=bm;var lc=Le(),Xw=mm(),Qw=tc(),Zw=zw(ac());te.BASE_PATH="/computeMetadata/v1";te.HOST_ADDRESS="http://169.254.169.254";te.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";te.HEADER_NAME="Metadata-Flavor";te.HEADER_VALUE="Google";te.HEADERS=Object.freeze({[te.HEADER_NAME]:te.HEADER_VALUE});var Pm=Zw.log("gcp-metadata");te.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function uc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||te.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(te.BASE_PATH,t).href}function jw(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 no(t,e={},n=3,r=!1){let i=new Headers(te.HEADERS),s="",o={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,m)=>i.set(m,h)),s=p.metadataKey,o=p.params||o,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(jw(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>i.set(h,p)),o=e.params||o);let l=r?eC:lc.request,d={url:`${uc()}/${s}`,headers:i,retryConfig:{noResponseRetries:n},params:o,responseType:"text",timeout:bm()};Pm.info("instance request %j",d);let c=await l(d);Pm.info("instance metadata is %s",c.data);let f=c.headers.get(te.HEADER_NAME);if(f!==te.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${te.HEADER_NAME} header. Expected '${te.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof c.data=="string")try{return Xw.parse(c.data)}catch{}return c.data}async function eC(t){let e={...t,url:t.url?.toString().replace(uc(),uc(te.SECONDARY_HOST_ADDRESS))},n=(0,lc.request)(t),r=(0,lc.request)(e);return Promise.any([n,r])}function tC(t){return no("instance",t)}function nC(t){return no("project",t)}function rC(t){return no("universe",t)}async function iC(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await no(n),i=n.metadataKey;e[i]=r})())),e}function sC(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var pa;async function oC(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in te.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(te.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return cc();case"ping-only":}}try{return pa===void 0&&(pa=no("instance",void 0,sC(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await pa,!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 aC(){pa=void 0}te.gcpResidencyCache=null;function cc(){return te.gcpResidencyCache===null&&xm(),te.gcpResidencyCache}function xm(t=null){te.gcpResidencyCache=t!==null?t:(0,Qw.detectGCPResidency)()}function bm(){return cc()?0:3e3}Yw(tc(),te)});var Mm=H(ha=>{"use strict";ha.byteLength=uC;ha.toByteArray=dC;ha.fromByteArray=hC;var Vt=[],_t=[],lC=typeof Uint8Array<"u"?Uint8Array:Array,dc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(cr=0,km=dc.length;cr<km;++cr)Vt[cr]=dc[cr],_t[dc.charCodeAt(cr)]=cr;var cr,km;_t[45]=62;_t[95]=63;function Nm(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 uC(t){var e=Nm(t),n=e[0],r=e[1];return(n+r)*3/4-r}function cC(t,e,n){return(e+n)*3/4-n}function dC(t){var e,n=Nm(t),r=n[0],i=n[1],s=new lC(cC(t,r,i)),o=0,l=i>0?r-4:r,d;for(d=0;d<l;d+=4)e=_t[t.charCodeAt(d)]<<18|_t[t.charCodeAt(d+1)]<<12|_t[t.charCodeAt(d+2)]<<6|_t[t.charCodeAt(d+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=_t[t.charCodeAt(d)]<<2|_t[t.charCodeAt(d+1)]>>4,s[o++]=e&255),i===1&&(e=_t[t.charCodeAt(d)]<<10|_t[t.charCodeAt(d+1)]<<4|_t[t.charCodeAt(d+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function fC(t){return Vt[t>>18&63]+Vt[t>>12&63]+Vt[t>>6&63]+Vt[t&63]}function pC(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(fC(r));return i.join("")}function hC(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,l=n-r;o<l;o+=s)i.push(pC(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(Vt[e>>2]+Vt[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(Vt[e>>10]+Vt[e>>4&63]+Vt[e<<2&63]+"=")),i.join("")}});var pc=H(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.fromArrayBufferToHex=mC;function mC(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Dm=H(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.BrowserCrypto=void 0;var ti=Mm(),gC=pc(),hc=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 ti.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),ti.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=ti.toByteArray(t.padBase64(r)),l=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,l,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 ti.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(e){let n=ti.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return ti.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,gC.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))}};ma.BrowserCrypto=hc});var Om=H(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.NodeCrypto=void 0;var ni=X("crypto"),mc=class{async sha256DigestBase64(e){return ni.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ni.randomBytes(e).toString("base64")}async verify(e,n,r){let i=ni.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,r,"base64")}async sign(e,n){let r=ni.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 ni.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:yC(e);return _C(ni.createHmac("sha256",r).update(n).digest())}};ga.NodeCrypto=mc;function _C(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 yC(t){return Buffer.from(t)}});var io=H(on=>{"use strict";var AC=on&&on.__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]})),EC=on&&on.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&AC(e,t,n)};Object.defineProperty(on,"__esModule",{value:!0});on.createCrypto=CC;on.hasBrowserCrypto=Um;var TC=Dm(),wC=Om();EC(pc(),on);function CC(){return Um()?new TC.BrowserCrypto:new wC.NodeCrypto}function Um(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var ri=H((gc,Fm)=>{var _a=X("buffer"),Ht=_a.Buffer;function Lm(t,e){for(var n in t)e[n]=t[n]}Ht.from&&Ht.alloc&&Ht.allocUnsafe&&Ht.allocUnsafeSlow?Fm.exports=_a:(Lm(_a,gc),gc.Buffer=dr);function dr(t,e,n){return Ht(t,e,n)}dr.prototype=Object.create(Ht.prototype);Lm(Ht,dr);dr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Ht(t,e,n)};dr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=Ht(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};dr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ht(t)};dr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return _a.SlowBuffer(t)}});var qm=H((OL,Gm)=>{"use strict";function _c(t){var e=(t/8|0)+(t%8===0?0:1);return e}var IC={ES256:_c(256),ES384:_c(384),ES512:_c(521)};function SC(t){var e=IC[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Gm.exports=SC});var yc=H((UL,Wm)=>{"use strict";var ya=ri().Buffer,$m=qm(),Aa=128,Vm=0,vC=32,PC=16,RC=2,Hm=PC|vC|Vm<<6,Ea=RC|Vm<<6;function xC(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Km(t){if(ya.isBuffer(t))return t;if(typeof t=="string")return ya.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function bC(t,e){t=Km(t);var n=$m(e),r=n+1,i=t.length,s=0;if(t[s++]!==Hm)throw new Error('Could not find expected "seq"');var o=t[s++];if(o===(Aa|1)&&(o=t[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(t[s++]!==Ea)throw new Error('Could not find expected "int" for "r"');var l=t[s++];if(i-s-2<l)throw new Error('"r" specified length of "'+l+'", only "'+(i-s-2)+'" available');if(r<l)throw new Error('"r" specified length of "'+l+'", max of "'+r+'" is acceptable');var d=s;if(s+=l,t[s++]!==Ea)throw new Error('Could not find expected "int" for "s"');var c=t[s++];if(i-s!==c)throw new Error('"s" specified length of "'+c+'", expected "'+(i-s)+'"');if(r<c)throw new Error('"s" specified length of "'+c+'", max of "'+r+'" is acceptable');var f=s;if(s+=c,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var p=n-l,h=n-c,m=ya.allocUnsafe(p+l+h+c);for(s=0;s<p;++s)m[s]=0;t.copy(m,s,d+Math.max(-p,0),d+l),s=n;for(var g=s;s<g+h;++s)m[s]=0;return t.copy(m,s,f+Math.max(-h,0),f+c),m=m.toString("base64"),m=xC(m),m}function Bm(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var i=t[e+r]>=Aa;return i&&--r,r}function kC(t,e){t=Km(t);var n=$m(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var i=Bm(t,0,n),s=Bm(t,n,t.length),o=n-i,l=n-s,d=2+o+1+1+l,c=d<Aa,f=ya.allocUnsafe((c?2:3)+d),p=0;return f[p++]=Hm,c?f[p++]=d:(f[p++]=Aa|1,f[p++]=d&255),f[p++]=Ea,f[p++]=o,i<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,i,n),f[p++]=Ea,f[p++]=l,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}Wm.exports={derToJose:bC,joseToDer:kC}});var Pt=H(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.LRUCache=void 0;an.snakeToCamel=zm;an.originalOrCamelOptions=OC;an.removeUndefinedValuesInObject=UC;an.isValidFile=LC;an.getWellKnownCertificateConfigFileLocation=FC;var NC=X("fs"),MC=X("os"),Ac=X("path"),DC="certificate_config.json",Jm="gcloud";function zm(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function OC(t){function e(n){let r=t||{};return r[n]??r[zm(n)]}return{get:e}}var Ec=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()}};an.LRUCache=Ec;function UC(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function LC(t){try{return(await NC.promises.lstat(t)).isFile()}catch{return!1}}function FC(){let t=process.env.CLOUDSDK_CONFIG||(GC()?Ac.join(process.env.APPDATA||"",Jm):Ac.join(process.env.HOME||"",".config",Jm));return Ac.join(t,DC)}function GC(){return MC.platform().startsWith("win")}});var Ym=H((FL,qC)=>{qC.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 Tc=H(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.USER_AGENT=Sn.PRODUCT_NAME=Sn.pkg=void 0;var Xm=Ym();Sn.pkg=Xm;var Qm="google-api-nodejs-client";Sn.PRODUCT_NAME=Qm;var BC=`${Qm}/${Xm.version}`;Sn.USER_AGENT=BC});var st=H(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.AuthClient=Rt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Rt.DEFAULT_UNIVERSE=void 0;var $C=X("events"),wc=Le(),VC=Pt(),HC=ac(),Cc=Tc();Rt.DEFAULT_UNIVERSE="googleapis.com";Rt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Ic=class t extends $C.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Rt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Rt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,VC.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")??Rt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new wc.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&&wc.Gaxios.mergeHeaders(s,n.headers),r&&wc.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,HC.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(`${Cc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Cc.USER_AGENT}`):e.headers.set("User-Agent",Cc.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"]}}}};Rt.AuthClient=Ic});var vc=H(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.LoginTicket=void 0;var Sc=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()}}};Ta.LoginTicket=Sc});var vn=H(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.OAuth2Client=Kt.ClientAuthentication=Kt.CertificateFormat=Kt.CodeChallengeMethod=void 0;var Zm=Le(),KC=X("querystring"),WC=X("stream"),JC=yc(),jm=Pt(),Pc=io(),ii=st(),zC=vc(),eg;(function(t){t.Plain="plain",t.S256="S256"})(eg||(Kt.CodeChallengeMethod=eg={}));var ln;(function(t){t.PEM="PEM",t.JWK="JWK"})(ln||(Kt.CertificateFormat=ln={}));var so;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(so||(Kt.ClientAuthentication=so={}));var Rc=class t extends ii.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=ln.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||so.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()+"?"+KC.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Pc.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===so.ClientSecretBasic){let d=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${d.toString("base64")}`)}this.clientAuthentication===so.ClientSecretPost&&(i.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,jm.removeUndefinedValuesInObject)(i)),headers:r};ii.AuthClient.setMethodName(s,"getTokenAsync");let o=await this.transporter.request(s),l=o.data;return o.data&&o.data.expires_in&&(l.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete l.expires_in),this.emit("tokens",l),{tokens:l,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,jm.removeUndefinedValuesInObject)(r))};ii.AuthClient.setMethodName(o,"refreshTokenNoCache"),i=await this.transporter.request(o)}catch(o){throw o instanceof Zm.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 l=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(l)}}if(this.refreshHandler){let l=await this.processAndValidateRefreshHandler();if(l?.access_token){this.setCredentials(l);let d=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(d)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,i=null;try{r=await this.refreshToken(n.refresh_token),i=r.tokens}catch(l){let d=l;throw d.response&&(d.response.status===403||d.response.status===404)&&(d.message=`Could not refresh access token: ${d.message}`),d}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(ii.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=Zm.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),l=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,d=i.config.data instanceof WC.Readable,c=s===401||s===403;if(!n&&c&&!d&&o)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&c&&!d&&l){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Pc.hasBrowserCrypto)()?ln.JWK:ln.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case ln.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case ln.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let c={...t.RETRY_CONFIG,url:i};ii.AuthClient.setMethodName(c,"getFederatedSignonCertsAsync"),r=await this.transporter.request(c)}catch(c){throw c instanceof Error&&(c.message=`Failed to retrieve verification certificates: ${c.message}`),c}let s=r?.headers.get("cache-control"),o=-1;if(s){let c=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;c&&(o=Number(c)*1e3)}let l={};switch(n){case ln.PEM:l=r.data;break;case ln.JWK:for(let c of r.data.keys)l[c.kid]=c;break;default:throw new Error(`Unsupported certificate format ${n}`)}let d=new Date;return this.certificateExpiry=o===-1?null:new Date(d.getTime()+o),this.certificateCache=l,this.certificateCacheFormat=n,{certs:l,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};ii.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,Pc.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(l.length!==3)throw new Error("Wrong number of segments in token: "+e);let d=l[0]+"."+l[1],c=l[2],f,p;try{f=JSON.parse(o.decodeBase64StringUtf8(l[0]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token envelope: ${l[0]}': ${R.message}`),R}if(!f)throw new Error("Can't parse token envelope: "+l[0]);try{p=JSON.parse(o.decodeBase64StringUtf8(l[1]))}catch(R){throw R instanceof Error&&(R.message=`Can't parse token payload '${l[0]}`),R}if(!p)throw new Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(c=JC.joseToDer(c,"ES256").toString("base64")),!await o.verify(h,d,c))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let g=Number(p.iat);if(isNaN(g))throw new Error("iat field using invalid format");let _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let y=new Date().getTime()/1e3;if(_>=y+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let T=g-t.CLOCK_SKEW_SECS_,C=_+t.CLOCK_SKEW_SECS_;if(y<T)throw new Error("Token used too early, "+y+" < "+T+": "+JSON.stringify(p));if(y>C)throw new Error("Token used too late, "+y+" > "+C+": "+JSON.stringify(p));if(i&&i.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let R=p.aud,x=!1;if(r.constructor===Array?x=r.indexOf(R)>-1:x=R===r,!x)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new zC.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Kt.OAuth2Client=Rc});var bc=H(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.Compute=void 0;var YC=Le(),tg=ro(),XC=vn(),xc=class extends XC.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 tg.instance(i)}catch(i){throw i instanceof YC.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 tg.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))}};wa.Compute=xc});var Nc=H(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.IdTokenClient=void 0;var QC=vn(),kc=class extends QC.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}};Ca.IdTokenClient=kc});var Mc=H(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.GCPEnv=void 0;si.clear=ZC;si.getEnv=jC;var ng=ro(),Wt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Wt||(si.GCPEnv=Wt={}));var oo;function ZC(){oo=void 0}async function jC(){return oo||(oo=eI(),oo)}async function eI(){let t=Wt.NONE;return tI()?t=Wt.APP_ENGINE:nI()?t=Wt.CLOUD_FUNCTIONS:await oI()?await sI()?t=Wt.KUBERNETES_ENGINE:rI()?t=Wt.CLOUD_RUN:iI()?t=Wt.CLOUD_RUN_JOBS:t=Wt.COMPUTE_ENGINE:t=Wt.NONE,t}function tI(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function nI(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function rI(){return!!process.env.K_CONFIGURATION}function iI(){return!!process.env.CLOUD_RUN_JOB}async function sI(){try{return await ng.instance("attributes/cluster-name"),!0}catch{return!1}}async function oI(){return ng.isAvailable()}});var Dc=H((WL,rg)=>{var Ia=ri().Buffer,aI=X("stream"),lI=X("util");function Sa(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Ia.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Ia.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}lI.inherits(Sa,aI);Sa.prototype.write=function(e){this.buffer=Ia.concat([this.buffer,Ia.from(e)]),this.emit("data",e)};Sa.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};rg.exports=Sa});var sg=H((JL,ig)=>{"use strict";var ao=X("buffer").Buffer,Oc=X("buffer").SlowBuffer;ig.exports=va;function va(t,e){if(!ao.isBuffer(t)||!ao.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}va.install=function(){ao.prototype.equal=Oc.prototype.equal=function(e){return va(this,e)}};var uI=ao.prototype.equal,cI=Oc.prototype.equal;va.restore=function(){ao.prototype.equal=uI,Oc.prototype.equal=cI}});var Gc=H((zL,hg)=>{var ai=ri().Buffer,yt=X("crypto"),ag=yc(),og=X("util"),dI=`"%s" is not a valid algorithm.
16
+ Supported algorithms are:
17
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,lo="secret must be a string or buffer",oi="key must be a string or a buffer",fI="key must be a string, a buffer or an object",Lc=typeof yt.createPublicKey=="function";Lc&&(oi+=" or a KeyObject",lo+="or a KeyObject");function lg(t){if(!ai.isBuffer(t)&&typeof t!="string"&&(!Lc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw xt(oi)}function ug(t){if(!ai.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw xt(fI)}function pI(t){if(!ai.isBuffer(t)){if(typeof t=="string")return t;if(!Lc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw xt(lo)}}function Fc(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cg(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function xt(t){var e=[].slice.call(arguments,1),n=og.format.bind(og,t).apply(null,e);return new TypeError(n)}function hI(t){return ai.isBuffer(t)||typeof t=="string"}function uo(t){return hI(t)||(t=JSON.stringify(t)),t}function dg(t){return function(n,r){pI(r),n=uo(n);var i=yt.createHmac("sha"+t,r),s=(i.update(n),i.digest("base64"));return Fc(s)}}var Uc,mI="timingSafeEqual"in yt?function(e,n){return e.byteLength!==n.byteLength?!1:yt.timingSafeEqual(e,n)}:function(e,n){return Uc||(Uc=sg()),Uc(e,n)};function gI(t){return function(n,r,i){var s=dg(t)(n,i);return mI(ai.from(r),ai.from(s))}}function fg(t){return function(n,r){ug(r),n=uo(n);var i=yt.createSign("RSA-SHA"+t),s=(i.update(n),i.sign(r,"base64"));return Fc(s)}}function pg(t){return function(n,r,i){lg(i),n=uo(n),r=cg(r);var s=yt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(i,r,"base64")}}function _I(t){return function(n,r){ug(r),n=uo(n);var i=yt.createSign("RSA-SHA"+t),s=(i.update(n),i.sign({key:r,padding:yt.constants.RSA_PKCS1_PSS_PADDING,saltLength:yt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Fc(s)}}function yI(t){return function(n,r,i){lg(i),n=uo(n),r=cg(r);var s=yt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:i,padding:yt.constants.RSA_PKCS1_PSS_PADDING,saltLength:yt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function AI(t){var e=fg(t);return function(){var r=e.apply(null,arguments);return r=ag.derToJose(r,"ES"+t),r}}function EI(t){var e=pg(t);return function(r,i,s){i=ag.joseToDer(i,"ES"+t).toString("base64");var o=e(r,i,s);return o}}function TI(){return function(){return""}}function wI(){return function(e,n){return n===""}}hg.exports=function(e){var n={hs:dg,rs:fg,ps:_I,es:AI,none:TI},r={hs:gI,rs:pg,ps:yI,es:EI,none:wI},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw xt(dI,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:n[s](o),verify:r[s](o)}}});var qc=H((YL,mg)=>{var CI=X("buffer").Buffer;mg.exports=function(e){return typeof e=="string"?e:typeof e=="number"||CI.isBuffer(e)?e.toString():JSON.stringify(e)}});var Tg=H((XL,Eg)=>{var II=ri().Buffer,gg=Dc(),SI=Gc(),vI=X("stream"),_g=qc(),Bc=X("util");function yg(t,e){return II.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function PI(t,e,n){n=n||"utf8";var r=yg(_g(t),"binary"),i=yg(_g(e),n);return Bc.format("%s.%s",r,i)}function Ag(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,i=t.encoding,s=SI(e.alg),o=PI(e,n,i),l=s.sign(o,r);return Bc.format("%s.%s",o,l)}function Pa(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new gg(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new gg(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Bc.inherits(Pa,vI);Pa.prototype.sign=function(){try{var e=Ag({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Pa.sign=Ag;Eg.exports=Pa});var kg=H((QL,bg)=>{var Cg=ri().Buffer,wg=Dc(),RI=Gc(),xI=X("stream"),Ig=qc(),bI=X("util"),kI=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function NI(t){return Object.prototype.toString.call(t)==="[object Object]"}function MI(t){if(NI(t))return t;try{return JSON.parse(t)}catch{return}}function Sg(t){var e=t.split(".",1)[0];return MI(Cg.from(e,"base64").toString("binary"))}function DI(t){return t.split(".",2).join(".")}function vg(t){return t.split(".")[2]}function OI(t,e){e=e||"utf8";var n=t.split(".")[1];return Cg.from(n,"base64").toString(e)}function Pg(t){return kI.test(t)&&!!Sg(t)}function Rg(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Ig(t);var i=vg(t),s=DI(t),o=RI(e);return o.verify(s,i,n)}function xg(t,e){if(e=e||{},t=Ig(t),!Pg(t))return null;var n=Sg(t);if(!n)return null;var r=OI(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:vg(t)}}function li(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new wg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new wg(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}bI.inherits(li,xI);li.prototype.verify=function(){try{var e=Rg(this.signature.buffer,this.algorithm,this.key.buffer),n=xg(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};li.decode=xg;li.isValid=Pg;li.verify=Rg;bg.exports=li});var $c=H(Pn=>{var Ng=Tg(),Ra=kg(),UI=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Pn.ALGORITHMS=UI;Pn.sign=Ng.sign;Pn.verify=Ra.verify;Pn.decode=Ra.decode;Pn.isValid=Ra.isValid;Pn.createSign=function(e){return new Ng(e)};Pn.createVerify=function(e){return new Ra(e)}});var Dg=H(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.buildPayloadForJwsSign=Mg;xa.getJwsSign=qI;var LI=$c(),FI="RS256",GI="https://oauth2.googleapis.com/token";function Mg(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:GI,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function qI(t){let e=Mg(t);return(0,LI.sign)({header:{alg:FI},payload:e,secret:t.key})}});var Og=H(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.getToken=KI;var BI=Dg(),$I="https://oauth2.googleapis.com/token",VI="urn:ietf:params:oauth:grant-type:jwt-bearer",HI=t=>({method:"POST",url:$I,data:new URLSearchParams({grant_type:VI,assertion:(0,BI.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function KI(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=HI(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 Ug=H(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ErrorWithCode=void 0;var Hc=class extends Error{code;constructor(e,n){super(e),this.code=n}};ba.ErrorWithCode=Hc});var Xc=H(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.getCredentials=zI;var WI=X("path"),Lg=X("fs"),JI=X("util"),ka=Ug(),Fg=Lg.readFile?(0,JI.promisify)(Lg.readFile):async()=>{throw new ka.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Rn;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Rn||(Rn={}));var Kc=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Fg(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 ka.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:i}}},Wc=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Fg(this.keyFilePath,"utf8")}}},Jc=class{async getCredentials(){throw new ka.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")}},zc=class{static create(e){switch(WI.extname(e)){case Rn.JSON:return new Kc(e);case Rn.DER:case Rn.CRT:case Rn.PEM:return new Wc(e);case Rn.P12:case Rn.PFX:return new Jc;default:throw new ka.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function zI(t){return zc.create(t).getCredentials()}});var Gg=H(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.TokenHandler=void 0;var YI=Og(),XI=Xc(),Qc=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,XI.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,YI.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}}};Na.TokenHandler=Qc});var qg=H(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.revokeToken=jI;var QI="https://oauth2.googleapis.com/revoke?token=",ZI=!0;async function jI(t,e){let n=QI+t;return await e.request({url:n,retry:ZI})}});var ed=H(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.GoogleToken=void 0;var eS=Le(),Bg=Gg(),tS=qg(),jc=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,eS.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 Bg.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,tS.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Bg.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};Ma.GoogleToken=jc});var nd=H(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.JWTAccess=void 0;var nS=$c(),rS=Pt(),$g={alg:"RS256",typ:"JWT"},td=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new rS.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 l=Math.floor(Date.now()/1e3),d=t.getExpirationTime(l),c;if(Array.isArray(r)&&(r=r.join(" ")),r?c={iss:this.email,sub:this.email,scope:r,exp:d,iat:l}:c={iss:this.email,sub:this.email,aud:e,exp:d,iat:l},n){for(let g in c)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 f=this.keyId?{...$g,kid:this.keyId}:$g,p=Object.assign(c,n),h=nS.sign({header:f,payload:p,secret:this.key}),m=new Headers({authorization:`Bearer ${h}`});return this.cache.set(i,{expiration:d*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)}})})}};Da.JWTAccess=td});var id=H(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.JWT=void 0;var Vg=ed(),iS=Xc(),sS=nd(),oS=vn(),Oa=st(),rd=class t extends oS.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!==Oa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Oa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Oa.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 sS.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!==Oa.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 Vg.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 Vg.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,iS.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.")}};Ua.JWT=rd});var od=H(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.UserRefreshClient=ui.USER_REFRESH_ACCOUNT_TYPE=void 0;var aS=vn(),lS=st();ui.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var sd=class t extends aS.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 lS.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}};ui.UserRefreshClient=sd});var ld=H(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.Impersonated=ci.IMPERSONATED_ACCOUNT_TYPE=void 0;var Hg=vn(),uS=Le(),cS=Pt();ci.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var ad=class t extends Hg.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 Hg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,cS.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 uS.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}};ci.Impersonated=ad});var cd=H(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.OAuthClientAuthHandler=void 0;co.getErrorFromOAuthErrorResponse=pS;var di=Le(),dS=io(),fS=["PUT","POST","PATCH"],ud=class{#e=(0,dS.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new di.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new di.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=di.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=di.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=di.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,i=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${i}`);di.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!fS.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"]}}}};co.OAuthClientAuthHandler=ud;function pS(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 l=Object.keys(e);e.stack&&l.push("stack"),l.forEach(d=>{d!=="message"&&Object.defineProperty(o,d,{value:e[d],writable:!1,enumerable:!0})})}return o}});var Fa=H(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.StsCredentials=void 0;var hS=Le(),mS=st(),Kg=cd(),gS=Pt(),dd=class t extends Kg.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,gS.removeUndefinedValuesInObject)(i)),responseType:"json"};mS.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let o=await this.transporter.request(s),l=o.data;return l.res=o,l}catch(o){throw o instanceof hS.GaxiosError&&o.response?(0,Kg.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}};La.StsCredentials=dd});var xn=H(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.BaseExternalAccountClient=At.CLOUD_RESOURCE_MANAGER=At.EXTERNAL_ACCOUNT_TYPE=At.EXPIRATION_TIME_OFFSET=void 0;var _S=Le(),yS=X("stream"),fd=st(),AS=Fa(),Wg=Pt(),ES=Tc(),TS="urn:ietf:params:oauth:grant-type:token-exchange",wS="urn:ietf:params:oauth:token-type:access_token",pd="https://www.googleapis.com/auth/cloud-platform",CS=3600;At.EXPIRATION_TIME_OFFSET=300*1e3;At.EXTERNAL_ACCOUNT_TYPE="external_account";At.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var IS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",SS="https://sts.{universeDomain}/v1/token",hd=class t extends fd.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,Wg.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==At.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${At.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")??SS.replace("{universeDomain}",this.universeDomain);let o=n.get("subject_token_type"),l=n.get("workforce_pool_user_project"),d=n.get("service_account_impersonation_url"),c=n.get("service_account_impersonation"),f=(0,Wg.originalOrCamelOptions)(c).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 AS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[pd],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=o,this.workforcePoolUserProject=l;let p=new RegExp(IS);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=CS),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"};fd.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=_S.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,l=s.config.data instanceof yS.Readable;if(!n&&(o===401||o===403)&&!l&&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:TS,audience:this.audience,requestedTokenType:wS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[pd]: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"};fd.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||[pd]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${ES.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};At.BaseExternalAccountClient=hd});var Jg=H(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.FileSubjectTokenSupplier=void 0;var gd=X("util"),_d=X("fs"),vS=(0,gd.promisify)(_d.readFile??(()=>{})),PS=(0,gd.promisify)(_d.realpath??(()=>{})),RS=(0,gd.promisify)(_d.lstat??(()=>{})),md=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 PS(e),!(await RS(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 vS(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}};Ga.FileSubjectTokenSupplier=md});var zg=H(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.UrlSubjectTokenSupplier=void 0;var xS=st(),yd=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};xS.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}};qa.UrlSubjectTokenSupplier=yd});var Yg=H(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.CertificateSubjectTokenSupplier=ot.InvalidConfigurationError=ot.CertificateSourceUnavailableError=ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ba=Pt(),$a=X("fs"),Va=X("crypto"),bS=X("https");ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Jt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};ot.CertificateSourceUnavailableError=Jt;var Et=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};ot.InvalidConfigurationError=Et;var Ad=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Et("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Et("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Et("Cannot create mTLS Agent with missing certificate or key");return new bS.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,Ba.isValidFile)(e))return e;throw new Jt(`Provided certificate config path is invalid: ${e}`)}let n=process.env[ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Ba.isValidFile)(n))return n;throw new Jt(`Path from environment variable "${ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Ba.getWellKnownCertificateConfigFileLocation)();if(await(0,Ba.isValidFile)(r))return r;throw new Jt(`Could not find certificate configuration file. Searched override path, the "${ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await $a.promises.readFile(e,"utf8")}catch{throw new Jt(`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 Et(`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 Et?r:new Et(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,i;try{r=await $a.promises.readFile(e),new Va.X509Certificate(r)}catch(s){let o=s instanceof Error?s.message:String(s);throw new Jt(`Failed to read certificate file at ${e}: ${o}`)}try{i=await $a.promises.readFile(n),(0,Va.createPrivateKey)(i)}catch(s){let o=s instanceof Error?s.message:String(s);throw new Jt(`Failed to read private key file at ${n}: ${o}`)}return{cert:r,key:i}}async#r(e){let n=new Va.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await $a.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((d,c)=>{try{return new Va.X509Certificate(d)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Et(`Failed to parse certificate at index ${c} in trust chain file ${this.trustChainPath}: ${p}`)}}),o=s.findIndex(d=>n.raw.equals(d.raw)),l;if(o===-1)l=[n,...s];else if(o===0)l=s;else throw new Et(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);return JSON.stringify(l.map(d=>d.raw.toString("base64")))}catch(r){if(r instanceof Et)throw r;let i=r instanceof Error?r.message:String(r);throw new Jt(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};ot.CertificateSubjectTokenSupplier=Ad});var wd=H(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.IdentityPoolClient=void 0;var kS=xn(),Ed=Pt(),NS=Jg(),MS=zg(),Xg=Yg(),DS=Fa(),Qg=Le(),Td=class t extends kS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Ed.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,Ed.originalOrCamelOptions)(r),o=(0,Ed.originalOrCamelOptions)(s.get("format")),l=o.get("type")||"text",d=o.get("subject_token_field_name");if(l!=="json"&&l!=="text")throw new Error(`Invalid credential_source format "${l}"`);if(l==="json"&&!d)throw new Error("Missing subject_token_field_name for JSON credential_source format");let c=s.get("file"),f=s.get("url"),p=s.get("certificate"),h=s.get("headers");if(c&&f||f&&p||c&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(c)this.credentialSourceType="file",this.subjectTokenSupplier=new NS.FileSubjectTokenSupplier({filePath:c,formatType:l,subjectTokenFieldName:d});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new MS.UrlSubjectTokenSupplier({url:f,formatType:l,subjectTokenFieldName:d,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let m=new Xg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=m}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Xg.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new DS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Qg.Gaxios({agent:n})}),this.transporter=new Qg.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ha.IdentityPoolClient=Td});var Id=H(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.AwsRequestSigner=void 0;var Ka=Le(),jg=io(),Zg="AWS4-HMAC-SHA256",OS="aws4_request",Cd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,jg.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,l=await this.getCredentials(),d=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 c=await LS({crypto:this.crypto,host:d.host,canonicalUri:d.pathname,canonicalQuerystring:d.search.slice(1),method:i,region:this.region,securityCredentials:l,requestPayload:s,additionalAmzHeaders:o}),f=Ka.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:d.host},o||{});l.token&&Ka.Gaxios.mergeHeaders(f,{"x-amz-security-token":l.token});let p={url:r,method:i,headers:f};return s!==void 0&&(p.body=s),p}};Wa.AwsRequestSigner=Cd;async function fo(t,e,n){return await t.signWithHmacSha256(e,n)}async function US(t,e,n,r,i){let s=await fo(t,`AWS4${e}`,n),o=await fo(t,s,r),l=await fo(t,o,i);return await fo(t,l,"aws4_request")}async function LS(t){let e=Ka.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 l=Ka.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),d="",c=[...l.keys()].sort();c.forEach(C=>{d+=`${C}:${l.get(C)}
18
+ `});let f=c.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
19
+ ${t.canonicalUri}
20
+ ${t.canonicalQuerystring}
21
+ ${d}
22
+ ${f}
23
+ ${p}`,m=`${o}/${t.region}/${r}/${OS}`,g=`${Zg}
24
+ ${s}
25
+ ${m}
26
+ `+await t.crypto.sha256DigestHex(h),_=await US(t.crypto,t.securityCredentials.secretAccessKey,o,t.region,r),y=await fo(t.crypto,_,g),T=`${Zg} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${f}, Signature=${(0,jg.fromArrayBufferToHex)(y)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:T,canonicalQuerystring:t.canonicalQuerystring}}});var e_=H(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.DefaultAwsSecurityCredentialsSupplier=void 0;var Ja=st(),Sd=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};Ja.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 Ja.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 Ja.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 Ja.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}};za.DefaultAwsSecurityCredentialsSupplier=Sd});var Pd=H(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.AwsClient=void 0;var FS=Id(),GS=xn(),qS=e_(),t_=Pt(),BS=Le(),vd=class t extends GS.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,t_.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,t_.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let o=s.get("region_url"),l=s.get("url"),d=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new qS.DefaultAwsSecurityCredentialsSupplier({regionUrl:o,securityCredentialsUrl:l,imdsV2SessionTokenUrl:d}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw 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 FS.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 BS.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}))}};Ya.AwsClient=vd});var Nd=H(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.InvalidSubjectTokenError=ve.InvalidMessageFieldError=ve.InvalidCodeFieldError=ve.InvalidTokenTypeFieldError=ve.InvalidExpirationTimeFieldError=ve.InvalidSuccessFieldError=ve.InvalidVersionFieldError=ve.ExecutableResponseError=ve.ExecutableResponse=void 0;var Xa="urn:ietf:params:oauth:token-type:saml2",Rd="urn:ietf:params:oauth:token-type:id_token",xd="urn:ietf:params:oauth:token-type:jwt",bd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Qa("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Za("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!==Xa&&this.tokenType!==Rd&&this.tokenType!==xd)throw new ja(`Executable response must contain a 'token_type' field when successful and it must be one of ${Rd}, ${xd}, or ${Xa}.`);if(this.tokenType===Xa){if(!e.saml_response)throw new po(`Executable response must contain a 'saml_response' field when token_type=${Xa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new po(`Executable response must contain a 'id_token' field when token_type=${Rd} or ${xd}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new el("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new tl("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)}};ve.ExecutableResponse=bd;var zt=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};ve.ExecutableResponseError=zt;var Qa=class extends zt{};ve.InvalidVersionFieldError=Qa;var Za=class extends zt{};ve.InvalidSuccessFieldError=Za;var kd=class extends zt{};ve.InvalidExpirationTimeFieldError=kd;var ja=class extends zt{};ve.InvalidTokenTypeFieldError=ja;var el=class extends zt{};ve.InvalidCodeFieldError=el;var tl=class extends zt{};ve.InvalidMessageFieldError=tl;var po=class extends zt{};ve.InvalidSubjectTokenError=po});var Od=H(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.PluggableAuthHandler=fi.ExecutableError=void 0;var fr=Nd(),$S=X("child_process"),Md=X("fs"),nl=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)}};fi.ExecutableError=nl;var Dd=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=$S.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";i.stdout.on("data",l=>{s+=l}),i.stderr.on("data",l=>{s+=l});let o=setTimeout(()=>(i.removeAllListeners(),i.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",l=>{if(clearTimeout(o),l===0)try{let d=JSON.parse(s),c=new fr.ExecutableResponse(d);return n(c)}catch(d){return d instanceof fr.ExecutableResponseError?r(d):r(new fr.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new nl(s,l.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Md.promises.realpath(this.outputFile)}catch{return}if(!(await Md.promises.lstat(e)).isFile())return;let n=await Md.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new fr.ExecutableResponse(r).isValid()?new fr.ExecutableResponse(r):void 0}catch(r){throw r instanceof fr.ExecutableResponseError?r:new fr.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}};fi.PluggableAuthHandler=Dd});var Ld=H(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.PluggableAuthClient=pi.ExecutableError=void 0;var VS=xn(),HS=Nd(),n_=Od(),KS=Od();Object.defineProperty(pi,"ExecutableError",{enumerable:!0,get:function(){return KS.ExecutableError}});var WS=30*1e3,r_=5*1e3,i_=120*1e3,JS="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",s_=1,Ud=class extends VS.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=WS;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<r_||this.timeoutMillis>i_)throw new Error(`Timeout must be between ${r_} and ${i_} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new n_.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[JS]!=="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>s_)throw new Error(`Version of executable is not currently supported, maximum supported version is ${s_}.`);if(!e.success)throw new n_.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new HS.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}};pi.PluggableAuthClient=Ud});var Gd=H(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});rl.ExternalAccountClient=void 0;var zS=xn(),YS=wd(),XS=Pd(),QS=Ld(),Fd=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===zS.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new XS.AwsClient(e):e.credential_source?.executable?new QS.PluggableAuthClient(e):new YS.IdentityPoolClient(e):null}};rl.ExternalAccountClient=Fd});var $d=H(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.ExternalAccountAuthorizedUserClient=hi.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var a_=st(),o_=cd(),l_=Le(),ZS=X("stream"),jS=xn();hi.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var ev="https://sts.{universeDomain}/v1/oauthtoken",qd=class t extends o_.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"};a_.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 l_.GaxiosError&&i.response?(0,o_.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},Bd=class extends a_.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 qd({tokenRefreshEndpoint:e.token_url??ev.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=jS.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=l_.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,l=s.config.data instanceof ZS.Readable;if(!n&&(o===401||o===403)&&!l&&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}};hi.ExternalAccountAuthorizedUserClient=Bd});var Hd=H(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.GdchClient=bn.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var tv=X("crypto"),nv=X("fs"),rv=X("https"),iv=vn(),sv=3600;bn.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var Vd=class t extends iv.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||sv,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!==bn.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${bn.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)),l=`${s}.${o}`,d=tv.sign("sha256",Buffer.from(l),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),c=this.base64UrlEncode(d);return`${l}.${c}`}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 nv.promises.readFile(r);return new rv.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")}};bn.GdchClient=Vd});var f_=H(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.GoogleAuth=bt.GoogleAuthExceptionMessages=void 0;var ov=X("child_process"),ho=X("fs"),av=Le(),mo=ro(),lv=X("os"),il=X("path"),uv=io(),cv=bc(),dv=Nc(),fv=Mc(),mi=id(),u_=od(),gi=ld(),pv=Gd(),go=xn(),Kd=st(),c_=$d(),Wd=Hd(),d_=Pt();bt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
27
+ To learn more about authentication and Google APIs, visit:
28
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
29
+ To learn more about authentication and Google APIs, visit:
30
+ https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
31
+ To learn more about Universe Domain retrieval, visit:
32
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Jd=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(bt.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===bt.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(bt.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 mo.universe("universe-domain"),e||=Kd.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Kd.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,d_.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Kd.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 mi.JWT?n.scopes=this.scopes:n instanceof go.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof mi.JWT?n.scopes=this.scopes:n instanceof go.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new cv.Compute(e));throw new Error(bt.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=mo.getGCPResidency()||await mo.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=il.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=il.join(s,".config","gcloud"))}if(!n)return null;let r=il.join(n,"application_default_credentials.json");return ho.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=ho.realpathSync(e),!ho.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=ho.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!==gi.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${gi.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 gi.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let r,i=(0,d_.originalOrCamelOptions)(n).get("universe_domain");return e.type===u_.USER_REFRESH_ACCOUNT_TYPE?(r=new u_.UserRefreshClient(n),r.fromJSON(e)):e.type===gi.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===go.EXTERNAL_ACCOUNT_TYPE?(r=pv.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===c_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new c_.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Wd.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Wd.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new mi.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("")),l=this._cacheClientFromJSON(o,n);return r(l)}catch(o){if(!this.keyFilename)throw o;let l=new mi.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=l,this.setGapicJWTValues(l),r(l)}}catch(o){return i(o)}})})}fromAPIKey(e,n={}){return new mi.JWT({...n,apiKey:e})}_isWindows(){let e=lv.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,ov.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!==go.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await mo.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 gi.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof go.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([mo.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(bt.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 Wd.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=il.resolve(this.keyFilename),n=ho.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 dv.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=av.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,fv.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 gi.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,uv.createCrypto)();if(r instanceof mi.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}};bt.GoogleAuth=Jd});var p_=H(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.IAMAuth=void 0;var zd=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}}};sl.IAMAuth=zd});var h_=H(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DownscopedClient=Yt.EXPIRATION_TIME_OFFSET=Yt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var hv=Le(),mv=X("stream"),Yd=st(),gv=Fa(),_v="urn:ietf:params:oauth:grant-type:token-exchange",yv="urn:ietf:params:oauth:token-type:access_token",Av="urn:ietf:params:oauth:token-type:access_token";Yt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Yt.EXPIRATION_TIME_OFFSET=300*1e3;var Xd=class extends Yd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Yd.AuthClient?{}:e),e instanceof Yd.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>Yt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Yt.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 gv.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=hv.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,l=s.config.data instanceof mv.Readable;if(!n&&(o===401||o===403)&&!l&&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:_v,requestedTokenType:yv,subjectToken:e,subjectTokenType:Av},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}};Yt.DownscopedClient=Xd});var m_=H(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.PassThroughClient=void 0;var Ev=st(),Qd=class extends Ev.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ol.PassThroughClient=Qd});var T_=H(Y=>{"use strict";var Tv=Y&&Y.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wv=Y&&Y.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tv(e,t,n)};Object.defineProperty(Y,"__esModule",{value:!0});Y.GoogleAuth=Y.auth=Y.GDCH_SERVICE_ACCOUNT_TYPE=Y.GdchClient=Y.PassThroughClient=Y.ExternalAccountAuthorizedUserClient=Y.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Y.ExecutableError=Y.PluggableAuthClient=Y.DownscopedClient=Y.BaseExternalAccountClient=Y.ExternalAccountClient=Y.IdentityPoolClient=Y.AwsRequestSigner=Y.AwsClient=Y.UserRefreshClient=Y.LoginTicket=Y.ClientAuthentication=Y.OAuth2Client=Y.CodeChallengeMethod=Y.Impersonated=Y.JWT=Y.JWTAccess=Y.IdTokenClient=Y.IAMAuth=Y.GCPEnv=Y.Compute=Y.DEFAULT_UNIVERSE=Y.AuthClient=Y.gaxios=Y.gcpMetadata=void 0;var g_=f_();Object.defineProperty(Y,"GoogleAuth",{enumerable:!0,get:function(){return g_.GoogleAuth}});Y.gcpMetadata=ro();Y.gaxios=Le();var __=st();Object.defineProperty(Y,"AuthClient",{enumerable:!0,get:function(){return __.AuthClient}});Object.defineProperty(Y,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return __.DEFAULT_UNIVERSE}});var Cv=bc();Object.defineProperty(Y,"Compute",{enumerable:!0,get:function(){return Cv.Compute}});var Iv=Mc();Object.defineProperty(Y,"GCPEnv",{enumerable:!0,get:function(){return Iv.GCPEnv}});var Sv=p_();Object.defineProperty(Y,"IAMAuth",{enumerable:!0,get:function(){return Sv.IAMAuth}});var vv=Nc();Object.defineProperty(Y,"IdTokenClient",{enumerable:!0,get:function(){return vv.IdTokenClient}});var Pv=nd();Object.defineProperty(Y,"JWTAccess",{enumerable:!0,get:function(){return Pv.JWTAccess}});var Rv=id();Object.defineProperty(Y,"JWT",{enumerable:!0,get:function(){return Rv.JWT}});var xv=ld();Object.defineProperty(Y,"Impersonated",{enumerable:!0,get:function(){return xv.Impersonated}});var Zd=vn();Object.defineProperty(Y,"CodeChallengeMethod",{enumerable:!0,get:function(){return Zd.CodeChallengeMethod}});Object.defineProperty(Y,"OAuth2Client",{enumerable:!0,get:function(){return Zd.OAuth2Client}});Object.defineProperty(Y,"ClientAuthentication",{enumerable:!0,get:function(){return Zd.ClientAuthentication}});var bv=vc();Object.defineProperty(Y,"LoginTicket",{enumerable:!0,get:function(){return bv.LoginTicket}});var kv=od();Object.defineProperty(Y,"UserRefreshClient",{enumerable:!0,get:function(){return kv.UserRefreshClient}});var Nv=Pd();Object.defineProperty(Y,"AwsClient",{enumerable:!0,get:function(){return Nv.AwsClient}});var Mv=Id();Object.defineProperty(Y,"AwsRequestSigner",{enumerable:!0,get:function(){return Mv.AwsRequestSigner}});var Dv=wd();Object.defineProperty(Y,"IdentityPoolClient",{enumerable:!0,get:function(){return Dv.IdentityPoolClient}});var Ov=Gd();Object.defineProperty(Y,"ExternalAccountClient",{enumerable:!0,get:function(){return Ov.ExternalAccountClient}});var Uv=xn();Object.defineProperty(Y,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Uv.BaseExternalAccountClient}});var Lv=h_();Object.defineProperty(Y,"DownscopedClient",{enumerable:!0,get:function(){return Lv.DownscopedClient}});var y_=Ld();Object.defineProperty(Y,"PluggableAuthClient",{enumerable:!0,get:function(){return y_.PluggableAuthClient}});Object.defineProperty(Y,"ExecutableError",{enumerable:!0,get:function(){return y_.ExecutableError}});var A_=$d();Object.defineProperty(Y,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return A_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Y,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return A_.ExternalAccountAuthorizedUserClient}});var Fv=m_();Object.defineProperty(Y,"PassThroughClient",{enumerable:!0,get:function(){return Fv.PassThroughClient}});var E_=Hd();Object.defineProperty(Y,"GdchClient",{enumerable:!0,get:function(){return E_.GdchClient}});Object.defineProperty(Y,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return E_.GDCH_SERVICE_ACCOUNT_TYPE}});wv(ed(),Y);var Gv=new g_.GoogleAuth;Y.auth=Gv});var un=H((kF,I_)=>{"use strict";var w_=["nodebuffer","arraybuffer","fragments"],C_=typeof Blob<"u";C_&&w_.push("blob");I_.exports={BINARY_TYPES:w_,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:C_,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _o=H((NF,al)=>{"use strict";var{EMPTY_BUFFER:qv}=un(),jd=Buffer[Symbol.species];function Bv(t,e){if(t.length===0)return qv;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 jd(n.buffer,n.byteOffset,r):n}function S_(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function v_(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $v(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ef(t){if(ef.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new jd(t):ArrayBuffer.isView(t)?e=new jd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ef.readOnly=!1),e}al.exports={concat:Bv,mask:S_,toArrayBuffer:$v,toBuffer:ef,unmask:v_};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=X("bufferutil");al.exports.mask=function(e,n,r,i,s){s<48?S_(e,n,r,i,s):t.mask(e,n,r,i,s)},al.exports.unmask=function(e,n){e.length<32?v_(e,n):t.unmask(e,n)}}catch{}});var x_=H((MF,R_)=>{"use strict";var P_=Symbol("kDone"),tf=Symbol("kRun"),nf=class{constructor(e){this[P_]=()=>{this.pending--,this[tf]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tf]()}[tf](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[P_])}}};R_.exports=nf});var Ai=H((DF,M_)=>{"use strict";var yo=X("zlib"),b_=_o(),Vv=x_(),{kStatusCode:k_}=un(),Hv=Buffer[Symbol.species],Kv=Buffer.from([0,0,255,255]),ul=Symbol("permessage-deflate"),cn=Symbol("total-length"),_i=Symbol("callback"),kn=Symbol("buffers"),yi=Symbol("error"),ll,rf=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,!ll){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ll=new Vv(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[_i];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?n.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let 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){ll.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){ll.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"?yo.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=yo.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ul]=this,this._inflate[cn]=0,this._inflate[kn]=[],this._inflate.on("error",Jv),this._inflate.on("data",N_)}this._inflate[_i]=r,this._inflate.write(e),n&&this._inflate.write(Kv),this._inflate.flush(()=>{let s=this._inflate[yi];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=b_.concat(this._inflate[kn],this._inflate[cn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[cn]=0,this._inflate[kn]=[],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"?yo.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=yo.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[cn]=0,this._deflate[kn]=[],this._deflate.on("data",Wv)}this._deflate[_i]=r,this._deflate.write(e),this._deflate.flush(yo.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=b_.concat(this._deflate[kn],this._deflate[cn]);n&&(s=new Hv(s.buffer,s.byteOffset,s.length-4)),this._deflate[_i]=null,this._deflate[cn]=0,this._deflate[kn]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};M_.exports=rf;function Wv(t){this[kn].push(t),this[cn]+=t.length}function N_(t){if(this[cn]+=t.length,this[ul]._maxPayload<1||this[cn]<=this[ul]._maxPayload){this[kn].push(t);return}this[yi]=new RangeError("Max payload size exceeded"),this[yi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[yi][k_]=1009,this.removeListener("data",N_),this.reset()}function Jv(t){if(this[ul]._inflate=null,this[yi]){this[_i](this[yi]);return}t[k_]=1007,this[_i](t)}});var Ei=H((OF,cl)=>{"use strict";var{isUtf8:D_}=X("buffer"),{hasBlob:zv}=un(),Yv=[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 Xv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function sf(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 Qv(t){return zv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}cl.exports={isBlob:Qv,isValidStatusCode:Xv,isValidUTF8:sf,tokenChars:Yv};if(D_)cl.exports.isValidUTF8=function(t){return t.length<24?sf(t):D_(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=X("utf-8-validate");cl.exports.isValidUTF8=function(e){return e.length<32?sf(e):t(e)}}catch{}});var cf=H((UF,B_)=>{"use strict";var{Writable:Zv}=X("stream"),O_=Ai(),{BINARY_TYPES:jv,EMPTY_BUFFER:U_,kStatusCode:eP,kWebSocket:tP}=un(),{concat:of,toArrayBuffer:nP,unmask:rP}=_o(),{isValidStatusCode:iP,isValidUTF8:L_}=Ei(),dl=Buffer[Symbol.species],Tt=0,F_=1,G_=2,q_=3,af=4,lf=5,fl=6,uf=class extends Zv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||jv[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[tP]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Tt}_write(e,n,r){if(this._opcode===8&&this._state==Tt)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 dl(r.buffer,r.byteOffset+e,r.length-e),new dl(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 dl(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 Tt:this.getInfo(e);break;case F_:this.getPayloadLength16(e);break;case G_:this.getPayloadLength64(e);break;case q_:this.getMask();break;case af:this.getData(e);break;case lf:case fl: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[O_.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=F_:this._payloadLength===127?this._state=G_: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=q_:this._state=af}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=af}getData(e){let n=U_;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&&rP(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=lf,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[O_.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}this._fragments.push(s)}this.dataMessage(n),this._state===Tt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Tt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=of(r,n):this._binaryType==="arraybuffer"?i=nP(of(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Tt):(this._state=fl,setImmediate(()=>{this.emit("message",i,!0),this._state=Tt,this.startLoop(e)}))}else{let i=of(r,n);if(!this._skipUTF8Validation&&!L_(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===lf||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Tt):(this._state=fl,setImmediate(()=>{this.emit("message",i,!1),this._state=Tt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,U_),this.end();else{let r=e.readUInt16BE(0);if(!iP(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new dl(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!L_(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=Tt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Tt):(this._state=fl,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Tt,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[eP]=i,o}};B_.exports=uf});var pf=H((FF,H_)=>{"use strict";var{Duplex:LF}=X("stream"),{randomFillSync:sP}=X("crypto"),{types:{isUint8Array:oP}}=X("util"),$_=Ai(),{EMPTY_BUFFER:aP,kWebSocket:lP,NOOP:uP}=un(),{isBlob:Ti,isValidStatusCode:cP}=Ei(),{mask:V_,toBuffer:pr}=_o(),wt=Symbol("kByteLength"),dP=Buffer.alloc(4),pl=8*1024,hr,wi=pl,kt=0,fP=1,pP=2,df=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=kt,this.onerror=uP,this[lP]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||dP,n.generateMask?n.generateMask(r):(wi===pl&&(hr===void 0&&(hr=Buffer.alloc(pl)),sP(hr,0,pl),wi=0),r[0]=hr[wi++],r[1]=hr[wi++],r[2]=hr[wi++],r[3]=hr[wi++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let l;typeof e=="string"?(!n.mask||o)&&n[wt]!==void 0?l=n[wt]:(e=Buffer.from(e),l=e.length):(l=e.length,i=n.mask&&n.readOnly&&!o);let d=l;l>=65536?(s+=8,d=127):l>125&&(s+=2,d=126);let c=Buffer.allocUnsafe(i?l+s:s);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=d,d===126?c.writeUInt16BE(l,2):d===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),n.mask?(c[1]|=128,c[s-4]=r[0],c[s-3]=r[1],c[s-2]=r[2],c[s-1]=r[3],o?[c,e]:i?(V_(e,r,c,s,l),[c]):(V_(e,r,e,0,l),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=aP;else{if(typeof e!="number"||!cP(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 l=Buffer.byteLength(n);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+l),s.writeUInt16BE(e,0),typeof n=="string")s.write(n,2);else if(oP(n))s.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[wt]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==kt?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):Ti(e)?(i=e.size,s=!1):(e=pr(e),i=e.length,s=pr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[wt]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Ti(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==kt?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):Ti(e)?(i=e.size,s=!1):(e=pr(e),i=e.length,s=pr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[wt]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Ti(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==kt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[$_.extensionName],s=n.binary?2:1,o=n.compress,l,d;typeof e=="string"?(l=Buffer.byteLength(e),d=!1):Ti(e)?(l=e.size,d=!1):(e=pr(e),l=e.length,d=pr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=i._threshold),this._compress=o):(o=!1,s=0),n.fin&&(this._firstFragment=!0);let c={[wt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:o};Ti(e)?this._state!==kt?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==kt?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[wt],this._state=pP,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(ff,this,l,i);return}this._bufferedBytes-=r[wt];let o=pr(s);n?this.dispatch(o,n,r,i):(this._state=kt,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(hP,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[$_.extensionName];this._bufferedBytes+=r[wt],this._state=fP,s.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");ff(this,d,i);return}this._bufferedBytes-=r[wt],this._state=kt,r.readOnly=!1,this.sendFrame(t.frame(l,r),i),this.dequeue()})}dequeue(){for(;this._state===kt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][wt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][wt],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)}};H_.exports=df;function ff(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 hP(t,e,n){ff(t,e,n),t.onerror(e)}});var j_=H((GF,Z_)=>{"use strict";var{kForOnEventAttribute:Ao,kListener:hf}=un(),K_=Symbol("kCode"),W_=Symbol("kData"),J_=Symbol("kError"),z_=Symbol("kMessage"),Y_=Symbol("kReason"),Ci=Symbol("kTarget"),X_=Symbol("kType"),Q_=Symbol("kWasClean"),dn=class{constructor(e){this[Ci]=null,this[X_]=e}get target(){return this[Ci]}get type(){return this[X_]}};Object.defineProperty(dn.prototype,"target",{enumerable:!0});Object.defineProperty(dn.prototype,"type",{enumerable:!0});var mr=class extends dn{constructor(e,n={}){super(e),this[K_]=n.code===void 0?0:n.code,this[Y_]=n.reason===void 0?"":n.reason,this[Q_]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[K_]}get reason(){return this[Y_]}get wasClean(){return this[Q_]}};Object.defineProperty(mr.prototype,"code",{enumerable:!0});Object.defineProperty(mr.prototype,"reason",{enumerable:!0});Object.defineProperty(mr.prototype,"wasClean",{enumerable:!0});var Ii=class extends dn{constructor(e,n={}){super(e),this[J_]=n.error===void 0?null:n.error,this[z_]=n.message===void 0?"":n.message}get error(){return this[J_]}get message(){return this[z_]}};Object.defineProperty(Ii.prototype,"error",{enumerable:!0});Object.defineProperty(Ii.prototype,"message",{enumerable:!0});var Eo=class extends dn{constructor(e,n={}){super(e),this[W_]=n.data===void 0?null:n.data}get data(){return this[W_]}};Object.defineProperty(Eo.prototype,"data",{enumerable:!0});var mP={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[Ao]&&i[hf]===e&&!i[Ao])return;let r;if(t==="message")r=function(s,o){let l=new Eo("message",{data:o?s:s.toString()});l[Ci]=this,hl(e,this,l)};else if(t==="close")r=function(s,o){let l=new mr("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ci]=this,hl(e,this,l)};else if(t==="error")r=function(s){let o=new Ii("error",{error:s,message:s.message});o[Ci]=this,hl(e,this,o)};else if(t==="open")r=function(){let s=new dn("open");s[Ci]=this,hl(e,this,s)};else return;r[Ao]=!!n[Ao],r[hf]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[hf]===e&&!n[Ao]){this.removeListener(t,n);break}}};Z_.exports={CloseEvent:mr,ErrorEvent:Ii,Event:dn,EventTarget:mP,MessageEvent:Eo};function hl(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ml=H((qF,ey)=>{"use strict";var{tokenChars:To}=Ei();function Xt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function gP(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,s=!1,o,l,d=-1,c=-1,f=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(f===-1&&To[c]===1)d===-1&&(d=p);else if(p!==0&&(c===32||c===9))f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let m=t.slice(d,f);c===44?(Xt(e,m,n),n=Object.create(null)):o=m,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&To[c]===1)d===-1&&(d=p);else if(c===32||c===9)f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),Xt(n,t.slice(d,f),!0),c===44&&(Xt(e,o,n),n=Object.create(null),o=void 0),d=f=-1}else if(c===61&&d!==-1&&f===-1)l=t.slice(d,p),d=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(i){if(To[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:r||(r=!0),i=!1}else if(s)if(To[c]===1)d===-1&&(d=p);else if(c===34&&d!==-1)s=!1,f=p;else if(c===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)s=!0;else if(f===-1&&To[c]===1)d===-1&&(d=p);else if(d!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let m=t.slice(d,f);r&&(m=m.replace(/\\/g,""),r=!1),Xt(n,l,m),c===44&&(Xt(e,o,n),n=Object.create(null),o=void 0),l=void 0,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let h=t.slice(d,f);return o===void 0?Xt(e,h,n):(l===void 0?Xt(n,h,!0):r?Xt(n,l,h.replace(/\\/g,"")):Xt(n,l,h),Xt(e,o,n)),e}function _P(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(", ")}ey.exports={format:_P,parse:gP}});var Al=H((VF,fy)=>{"use strict";var yP=X("events"),AP=X("https"),EP=X("http"),ry=X("net"),TP=X("tls"),{randomBytes:wP,createHash:CP}=X("crypto"),{Duplex:BF,Readable:$F}=X("stream"),{URL:mf}=X("url"),Nn=Ai(),IP=cf(),SP=pf(),{isBlob:vP}=Ei(),{BINARY_TYPES:ty,CLOSE_TIMEOUT:PP,EMPTY_BUFFER:gl,GUID:RP,kForOnEventAttribute:gf,kListener:xP,kStatusCode:bP,kWebSocket:ke,NOOP:iy}=un(),{EventTarget:{addEventListener:kP,removeEventListener:NP}}=j_(),{format:MP,parse:DP}=ml(),{toBuffer:OP}=_o(),sy=Symbol("kAborted"),_f=[8,13],fn=["CONNECTING","OPEN","CLOSING","CLOSED"],UP=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends yP{constructor(e,n,r){super(),this._binaryType=ty[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=gl,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]),oy(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ty.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 IP({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 SP(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[ke]=this,s[ke]=this,e[ke]=this,i.on("conclude",GP),i.on("drain",qP),i.on("error",BP),i.on("message",$P),i.on("ping",VP),i.on("pong",HP),s.onerror=KP,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",uy),e.on("data",yl),e.on("end",cy),e.on("error",dy),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[Nn.extensionName]&&this._extensions[Nn.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){at(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())}),ly(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){yf(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||gl,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){yf(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||gl,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){yf(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Nn.extensionName]||(i.compress=!1),this._sender.send(e||gl,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ge,"CONNECTING",{enumerable:!0,value:fn.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:fn.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:fn.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:fn.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:fn.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:fn.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:fn.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:fn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[gf])return e[xP];return null},set(e){for(let n of this.listeners(t))if(n[gf]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[gf]:!0})}})});ge.prototype.addEventListener=kP;ge.prototype.removeEventListener=NP;fy.exports=ge;function oy(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:PP,protocolVersion:_f[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!_f.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${_f.join(", ")})`);let s;if(e instanceof mf)s=e;else try{s=new mf(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:",l=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!o&&!l?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let _=new SyntaxError(d);if(t._redirects===0)throw _;_l(t,_);return}let c=o?443:80,f=wP(16).toString("base64"),p=o?AP.request:EP.request,h=new Set,m;if(i.createConnection=i.createConnection||(o?FP:LP),i.defaultPort=i.defaultPort||c,i.port=s.port||c,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(m=new Nn({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=MP({[Nn.extensionName]:m.offer()})),n.length){for(let _ of n){if(typeof _!="string"||!UP.test(_)||h.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(_)}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}`),l){let _=i.path.split(":");i.socketPath=_[0],i.path=_[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?i.socketPath:s.host;let _=r&&r.headers;if(r={...r,headers:{}},_)for(let[y,T]of Object.entries(_))r.headers[y.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let _=l?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,_||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=p(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=p(i);i.timeout&&g.on("timeout",()=>{at(t,g,"Opening handshake has timed out")}),g.on("error",_=>{g===null||g[sy]||(g=t._req=null,_l(t,_))}),g.on("response",_=>{let y=_.headers.location,T=_.statusCode;if(y&&i.followRedirects&&T>=300&&T<400){if(++t._redirects>i.maxRedirects){at(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new mf(y,e)}catch{let x=new SyntaxError(`Invalid URL: ${y}`);_l(t,x);return}oy(t,C,n,r)}else t.emit("unexpected-response",g,_)||at(t,g,`Unexpected server response: ${_.statusCode}`)}),g.on("upgrade",(_,y,T)=>{if(t.emit("upgrade",_),t.readyState!==ge.CONNECTING)return;g=t._req=null;let C=_.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){at(t,y,"Invalid Upgrade header");return}let R=CP("sha1").update(f+RP).digest("base64");if(_.headers["sec-websocket-accept"]!==R){at(t,y,"Invalid Sec-WebSocket-Accept header");return}let x=_.headers["sec-websocket-protocol"],G;if(x!==void 0?h.size?h.has(x)||(G="Server sent an invalid subprotocol"):G="Server sent a subprotocol but none was requested":h.size&&(G="Server sent no subprotocol"),G){at(t,y,G);return}x&&(t._protocol=x);let S=_.headers["sec-websocket-extensions"];if(S!==void 0){if(!m){at(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let q;try{q=DP(S)}catch{at(t,y,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(q);if($.length!==1||$[0]!==Nn.extensionName){at(t,y,"Server indicated an extension that was not requested");return}try{m.accept(q[Nn.extensionName])}catch{at(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Nn.extensionName]=m}t.setSocket(y,T,{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 _l(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function LP(t){return t.path=t.socketPath,ry.connect(t)}function FP(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ry.isIP(t.host)?"":t.host),TP.connect(t)}function at(t,e,n){t._readyState=ge.CLOSING;let r=new Error(n);Error.captureStackTrace(r,at),e.setHeader?(e[sy]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_l,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function yf(t,e,n){if(e){let r=vP(e)?e.size:OP(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${fn[t.readyState]})`);process.nextTick(n,r)}}function GP(t,e){let n=this[ke];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ke]!==void 0&&(n._socket.removeListener("data",yl),process.nextTick(ay,n._socket),t===1005?n.close():n.close(t,e))}function qP(){let t=this[ke];t.isPaused||t._socket.resume()}function BP(t){let e=this[ke];e._socket[ke]!==void 0&&(e._socket.removeListener("data",yl),process.nextTick(ay,e._socket),e.close(t[bP])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ny(){this[ke].emitClose()}function $P(t,e){this[ke].emit("message",t,e)}function VP(t){let e=this[ke];e._autoPong&&e.pong(t,!this._isServer,iy),e.emit("ping",t)}function HP(t){this[ke].emit("pong",t)}function ay(t){t.resume()}function KP(t){let e=this[ke];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,ly(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ly(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function uy(){let t=this[ke];if(this.removeListener("close",uy),this.removeListener("data",yl),this.removeListener("end",cy),t._readyState=ge.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[ke]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ny),t._receiver.on("finish",ny))}function yl(t){this[ke]._receiver.write(t)||this.pause()}function cy(){let t=this[ke];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function dy(){let t=this[ke];this.removeListener("error",dy),this.on("error",iy),t&&(t._readyState=ge.CLOSING,this.destroy())}});var gy=H((KF,my)=>{"use strict";var HF=Al(),{Duplex:WP}=X("stream");function py(t){t.emit("close")}function JP(){!this.destroyed&&this._writableState.finished&&this.destroy()}function hy(t){this.removeListener("error",hy),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function zP(t,e){let n=!0,r=new WP({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let l=!o&&r._readableState.objectMode?s.toString():s;r.push(l)||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(py,r);return}let o=!1;t.once("error",function(d){o=!0,s(d)}),t.once("close",function(){o||s(i),process.nextTick(py,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",JP),r.on("error",hy),r}my.exports=zP});var Af=H((WF,_y)=>{"use strict";var{tokenChars:YP}=Ei();function XP(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&&YP[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 l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),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}_y.exports={parse:XP}});var Iy=H((zF,Cy)=>{"use strict";var QP=X("events"),El=X("http"),{Duplex:JF}=X("stream"),{createHash:ZP}=X("crypto"),yy=ml(),gr=Ai(),jP=Af(),e0=Al(),{CLOSE_TIMEOUT:t0,GUID:n0,kWebSocket:r0}=un(),i0=/^[+/0-9A-Za-z]{22}==$/,Ay=0,Ey=1,wy=2,Ef=class extends QP{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:t0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:e0,...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=El.createServer((r,i)=>{let s=El.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=s0(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=Ay}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===wy){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(wo,this);return}if(e&&this.once("close",e),this._state!==Ey)if(this._state=Ey,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(wo,this):process.nextTick(wo,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{wo(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",Ty);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){_r(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){_r(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!i0.test(s)){_r(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){_r(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Co(n,400);return}let d=e.headers["sec-websocket-protocol"],c=new Set;if(d!==void 0)try{c=jP.parse(d)}catch{_r(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let h=new gr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=yy.parse(f);m[gr.extensionName]&&(h.accept(m[gr.extensionName]),p[gr.extensionName]=h)}catch{_r(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(m,g,_,y)=>{if(!m)return Co(n,g||401,_,y);this.completeUpgrade(p,s,c,e,n,r,i)});return}if(!this.options.verifyClient(h))return Co(n,401)}this.completeUpgrade(p,s,c,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,l){if(!s.readable||!s.writable)return s.destroy();if(s[r0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ay)return Co(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ZP("sha1").update(n+n0).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[gr.extensionName]){let p=e[gr.extensionName].params,h=yy.format({[gr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${h}`),f._extensions=e}this.emit("headers",c,i),s.write(c.concat(`\r
33
+ `).join(`\r
34
+ `)),s.removeListener("error",Ty),f.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(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(wo,this)})),l(f,i)}};Cy.exports=Ef;function s0(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 wo(t){t._state=wy,t.emit("close")}function Ty(){this.destroy()}function Co(t,e,n,r){n=n||El.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} ${El.STATUS_CODES[e]}\r
35
+ `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
36
+ `)+`\r
37
+ \r
38
+ `+n)}function _r(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,_r),t.emit("wsClientError",o,n,e)}else Co(n,r,i,s)}});var nu=$t(Gh(),1),iE=$t(T_(),1);import{createWriteStream as h0}from"fs";import*as ru from"fs/promises";import{writeFile as m0}from"fs/promises";import{Readable as g0}from"node:stream";import{finished as _0}from"node:stream/promises";var o0=$t(gy(),1),a0=$t(ml(),1),l0=$t(Ai(),1),u0=$t(cf(),1),c0=$t(pf(),1),d0=$t(Af(),1),Tf=$t(Al(),1),f0=$t(Iy(),1);import*as sE from"path";var y0,A0;function E0(){return{geminiUrl:y0,vertexUrl:A0}}function T0(t,e,n,r){var i,s;if(!t?.baseUrl){let o=E0();return e?(i=o.vertexUrl)!==null&&i!==void 0?i:n:(s=o.geminiUrl)!==null&&s!==void 0?s:r}return t.baseUrl}var Ot=class{};function z(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 u(t,e,n){for(let s=0;s<e.length-1;s++){let o=e[s];if(o.endsWith("[]")){let l=o.slice(0,-2);if(!(l in t))if(Array.isArray(n))t[l]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${o}`);if(Array.isArray(t[l])){let d=t[l];if(Array.isArray(n))for(let c=0;c<d.length;c++){let f=d[c];u(f,e.slice(s+1),n[c])}else for(let c of d)u(c,e.slice(s+1),n)}return}else if(o.endsWith("[0]")){let l=o.slice(0,-3);l in t||(t[l]=[{}]);let d=t[l];u(d[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 a(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(l=>a(l,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 w0(t,e){for(let[n,r]of Object.entries(e)){let i=n.split("."),s=r.split("."),o=new Set,l=-1;for(let d=0;d<i.length;d++)if(i[d]==="*"){l=d;break}if(l!==-1&&s.length>l)for(let d=l;d<s.length;d++){let c=s[d];c!=="*"&&!c.endsWith("[]")&&!c.endsWith("[0]")&&o.add(c)}Sf(t,i,s,0,o)}}function Sf(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),l=t;if(o in l&&Array.isArray(l[o]))for(let d of l[o])Sf(d,e,n,r+1,i)}else if(s==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,l=Object.keys(o).filter(c=>!c.startsWith("_")&&!i.has(c)),d={};for(let c of l)d[c]=o[c];for(let[c,f]of Object.entries(d)){let p=[];for(let h of n.slice(r))h==="*"?p.push(c):p.push(h);u(o,p,f)}for(let c of l)delete o[c]}}else{let o=t;s in o&&Sf(o[s],e,n,r+1,i)}}function vp(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function C0(t){let e={},n=a(t,["operationName"]);n!=null&&u(e,["operationName"],n);let r=a(t,["resourceName"]);return r!=null&&u(e,["_url","resourceName"],r),e}function I0(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["response","generateVideoResponse"]);return o!=null&&u(e,["response"],v0(o)),e}function S0(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["response"]);return o!=null&&u(e,["response"],P0(o)),e}function v0(t){let e={},n=a(t,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>R0(o))),u(e,["generatedVideos"],s)}let r=a(t,["raiMediaFilteredCount"]);r!=null&&u(e,["raiMediaFilteredCount"],r);let i=a(t,["raiMediaFilteredReasons"]);return i!=null&&u(e,["raiMediaFilteredReasons"],i),e}function P0(t){let e={},n=a(t,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>x0(o))),u(e,["generatedVideos"],s)}let r=a(t,["raiMediaFilteredCount"]);r!=null&&u(e,["raiMediaFilteredCount"],r);let i=a(t,["raiMediaFilteredReasons"]);return i!=null&&u(e,["raiMediaFilteredReasons"],i),e}function R0(t){let e={},n=a(t,["video"]);return n!=null&&u(e,["video"],O0(n)),e}function x0(t){let e={},n=a(t,["_self"]);return n!=null&&u(e,["video"],U0(n)),e}function b0(t){let e={},n=a(t,["operationName"]);return n!=null&&u(e,["_url","operationName"],n),e}function k0(t){let e={},n=a(t,["operationName"]);return n!=null&&u(e,["_url","operationName"],n),e}function N0(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["response"]);return o!=null&&u(e,["response"],M0(o)),e}function M0(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["parent"]);r!=null&&u(e,["parent"],r);let i=a(t,["documentName"]);return i!=null&&u(e,["documentName"],i),e}function Pp(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["response"]);return o!=null&&u(e,["response"],D0(o)),e}function D0(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["parent"]);r!=null&&u(e,["parent"],r);let i=a(t,["documentName"]);return i!=null&&u(e,["documentName"],i),e}function O0(t){let e={},n=a(t,["uri"]);n!=null&&u(e,["uri"],n);let r=a(t,["encodedVideo"]);r!=null&&u(e,["videoBytes"],vp(r));let i=a(t,["encoding"]);return i!=null&&u(e,["mimeType"],i),e}function U0(t){let e={},n=a(t,["gcsUri"]);n!=null&&u(e,["uri"],n);let r=a(t,["bytesBase64Encoded"]);r!=null&&u(e,["videoBytes"],vp(r));let i=a(t,["mimeType"]);return i!=null&&u(e,["mimeType"],i),e}var Sy;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(Sy||(Sy={}));var vy;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(vy||(vy={}));var Py;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(Py||(Py={}));var Mn;(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"})(Mn||(Mn={}));var Ry;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Ry||(Ry={}));var xy;(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"})(xy||(xy={}));var by;(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"})(by||(by={}));var ky;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ky||(ky={}));var Ny;(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"})(Ny||(Ny={}));var My;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(My||(My={}));var Dy;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Dy||(Dy={}));var Oy;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(Oy||(Oy={}));var Uy;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Uy||(Uy={}));var Ly;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Ly||(Ly={}));var Fy;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(Fy||(Fy={}));var Gy;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(Gy||(Gy={}));var qy;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(qy||(qy={}));var By;(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"})(By||(By={}));var $y;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})($y||($y={}));var Vy;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Vy||(Vy={}));var Hy;(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"})(Hy||(Hy={}));var Ky;(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"})(Ky||(Ky={}));var Wy;(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"})(Wy||(Wy={}));var Jy;(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"})(Jy||(Jy={}));var vl;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(vl||(vl={}));var zy;(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"})(zy||(zy={}));var Yy;(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"})(Yy||(Yy={}));var Xy;(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"})(Xy||(Xy={}));var Qy;(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"})(Qy||(Qy={}));var vf;(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"})(vf||(vf={}));var Zy;(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"})(Zy||(Zy={}));var jy;(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"})(jy||(jy={}));var eA;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(eA||(eA={}));var tA;(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"})(tA||(tA={}));var nA;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(nA||(nA={}));var rA;(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"})(rA||(rA={}));var iA;(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"})(iA||(iA={}));var Pf;(function(t){t.COLLECTION="COLLECTION"})(Pf||(Pf={}));var sA;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(sA||(sA={}));var oA;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(oA||(oA={}));var Pl;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(Pl||(Pl={}));var aA;(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"})(aA||(aA={}));var lA;(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"})(lA||(lA={}));var uA;(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"})(uA||(uA={}));var cA;(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"})(cA||(cA={}));var dA;(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"})(dA||(dA={}));var fA;(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"})(fA||(fA={}));var pA;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(pA||(pA={}));var hA;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(hA||(hA={}));var mA;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(mA||(mA={}));var gA;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(gA||(gA={}));var _A;(function(t){t.CROP="CROP",t.PAD="PAD"})(_A||(_A={}));var yA;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION"})(yA||(yA={}));var AA;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(AA||(AA={}));var EA;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(EA||(EA={}));var TA;(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"})(TA||(TA={}));var wA;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(wA||(wA={}));var CA;(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"})(CA||(CA={}));var IA;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(IA||(IA={}));var SA;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(SA||(SA={}));var vA;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(vA||(vA={}));var PA;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(PA||(PA={}));var RA;(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"})(RA||(RA={}));var xA;(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"})(xA||(xA={}));var bA;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(bA||(bA={}));var Si;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(Si||(Si={}));var Ln=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()}};var Ar=class{get text(){var e,n,r,i,s,o,l,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let c="",f=!1,p=[];for(let h of(d=(l=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||l===void 0?void 0:l.parts)!==null&&d!==void 0?d:[]){for(let[m,g]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(g!==null||g!==void 0)&&p.push(m);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,c+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?c:void 0}get data(){var e,n,r,i,s,o,l,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let c="",f=[];for(let p of(d=(l=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||l===void 0?void 0:l.parts)!==null&&d!==void 0?d:[]){for(let[h,m]of Object.entries(p))h!=="inlineData"&&(m!==null||m!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(c+=atob(p.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),c.length>0?btoa(c):void 0}get functionCalls(){var e,n,r,i,s,o,l,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let c=(d=(l=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||l===void 0?void 0:l.parts)===null||d===void 0?void 0:d.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(c?.length!==0)return c}get executableCode(){var e,n,r,i,s,o,l,d,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 executable code from the first one.");let f=(d=(l=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||l===void 0?void 0:l.parts)===null||d===void 0?void 0:d.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(c=f?.[0])===null||c===void 0?void 0:c.code}get codeExecutionResult(){var e,n,r,i,s,o,l,d,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 code execution result from the first one.");let f=(d=(l=(o=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content)===null||l===void 0?void 0:l.parts)===null||d===void 0?void 0:d.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(c=f?.[0])===null||c===void 0?void 0:c.output}},Rl=class{},xl=class{},Rf=class{},xf=class{},bf=class{},kf=class{},bl=class{},kl=class{},Nl=class{},Nf=class{};var Ml=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,i,s=e;return n?i=S0(s):i=I0(s),Object.assign(r,i),r}};var Mf=class{},Dl=class{},Ol=class{},Ul=class{},Df=class{},Of=class{},Uf=class{};var Lf=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=N0(e);return Object.assign(r,s),r}},Ff=class{},Gf=class{},qf=class{},Bf=class{};var Ll=class{};var $f=class{get text(){var e,n,r;let i="",s=!1,o=[];for(let l 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[d,c]of Object.entries(l))d!=="text"&&d!=="thought"&&c!==null&&o.push(d);if(typeof l.text=="string"){if(typeof l.thought=="boolean"&&l.thought)continue;s=!0,i+=l.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[l,d]of Object.entries(o))l!=="inlineData"&&d!==null&&s.push(l);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}};var Vf=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var Fl=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,s=Pp(e);return Object.assign(r,s),r}};function de(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 oE(t,e){let n=de(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 aE(t){return Array.isArray(t)?t.map(e=>Gl(e)):[Gl(t)]}function Gl(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function lE(t){let e=Gl(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function uE(t){let e=Gl(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function kA(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 cE(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>kA(e)):[kA(t)]}function Hf(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function NA(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function MA(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function Ne(t){if(t==null)throw new Error("ContentUnion is required");return Hf(t)?t:{role:"user",parts:cE(t)}}function Rp(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let r=Ne(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(t.isVertexAI()){let n=Ne(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>Ne(n)):[Ne(e)]}function Xe(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(NA(t)||MA(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Ne(t)]}let e=[],n=[],r=Hf(t[0]);for(let i of t){let s=Hf(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(NA(i)||MA(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:cE(n)}),e}function L0(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1)e.type=Object.values(Mn).includes(n[0].toUpperCase())?n[0].toUpperCase():Mn.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let r of n)e.anyOf.push({type:Object.values(Mn).includes(r.toUpperCase())?r.toUpperCase():Mn.TYPE_UNSPECIFIED})}}function vi(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&&L0(t.type,e);for(let[o,l]of Object.entries(t))if(l!=null)if(o=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(l instanceof Array)continue;e.type=Object.values(Mn).includes(l.toUpperCase())?l.toUpperCase():Mn.TYPE_UNSPECIFIED}else if(n.includes(o))e[o]=vi(l);else if(r.includes(o)){let d=[];for(let c of l){if(c.type=="null"){e.nullable=!0;continue}d.push(vi(c))}e[o]=d}else if(i.includes(o)){let d={};for(let[c,f]of Object.entries(l))d[c]=vi(f);e[o]=d}else{if(o==="additionalProperties")continue;e[o]=l}return e}function xp(t){return vi(t)}function bp(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 kp(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function bi(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=vi(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=vi(e.response));return t}function ki(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 F0(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 mn(t,e){if(typeof e!="string")throw new Error("name must be a string");return F0(t,e,"cachedContents")}function dE(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 Fn(t){return vp(t)}function G0(t){return t!=null&&typeof t=="object"&&"name"in t}function fE(t){return t!=null&&typeof t=="object"&&"video"in t}function pE(t){return t!=null&&typeof t=="object"&&"uri"in t}function Np(t){var e;let n;if(G0(t)&&(n=t.name),!(pE(t)&&(n=t.uri,n===void 0))&&!(fE(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 hE(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function mE(t){for(let e of["models","tunedModels","publisherModels"])if(q0(t,e))return t[e];return[]}function q0(t,e){return t!==null&&typeof t=="object"&&e in t}function B0(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 $0(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=B0(i,e);o.functionDeclarations&&n.push(...o.functionDeclarations)}return{functionDeclarations:n}}function gE(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 V0(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 _E(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 d=o.response;if(typeof d!="object"||d===null)continue;if(d.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function Ni(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 yE(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 H0(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function K0(t){let e={},n=a(t,["apiKey"]);if(n!=null&&u(e,["apiKey"],n),a(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(a(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(a(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(a(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(a(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(a(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function W0(t){let e={},n=a(t,["responsesFile"]);n!=null&&u(e,["fileName"],n);let r=a(t,["inlinedResponses","inlinedResponses"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>vR(o))),u(e,["inlinedResponses"],s)}let i=a(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["inlinedEmbedContentResponses"],s)}return e}function J0(t){let e={},n=a(t,["predictionsFormat"]);n!=null&&u(e,["format"],n);let r=a(t,["gcsDestination","outputUriPrefix"]);r!=null&&u(e,["gcsUri"],r);let i=a(t,["bigqueryDestination","outputUri"]);i!=null&&u(e,["bigqueryUri"],i);let s=a(t,["vertexMultimodalDatasetDestination"]);return s!=null&&u(e,["vertexDataset"],LR(s)),e}function z0(t){let e={},n=a(t,["format"]);n!=null&&u(e,["predictionsFormat"],n);let r=a(t,["gcsUri"]);r!=null&&u(e,["gcsDestination","outputUriPrefix"],r);let i=a(t,["bigqueryUri"]);if(i!=null&&u(e,["bigqueryDestination","outputUri"],i),a(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let s=a(t,["vertexDataset"]);return s!=null&&u(e,["vertexMultimodalDatasetDestination"],FR(s)),e}function Il(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata","displayName"]);r!=null&&u(e,["displayName"],r);let i=a(t,["metadata","state"]);i!=null&&u(e,["state"],yE(i));let s=a(t,["metadata","createTime"]);s!=null&&u(e,["createTime"],s);let o=a(t,["metadata","endTime"]);o!=null&&u(e,["endTime"],o);let l=a(t,["metadata","updateTime"]);l!=null&&u(e,["updateTime"],l);let d=a(t,["metadata","model"]);d!=null&&u(e,["model"],d);let c=a(t,["metadata","output"]);return c!=null&&u(e,["dest"],W0(_E(c))),e}function Kf(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["displayName"]);r!=null&&u(e,["displayName"],r);let i=a(t,["state"]);i!=null&&u(e,["state"],yE(i));let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["createTime"]);o!=null&&u(e,["createTime"],o);let l=a(t,["startTime"]);l!=null&&u(e,["startTime"],l);let d=a(t,["endTime"]);d!=null&&u(e,["endTime"],d);let c=a(t,["updateTime"]);c!=null&&u(e,["updateTime"],c);let f=a(t,["model"]);f!=null&&u(e,["model"],f);let p=a(t,["inputConfig"]);p!=null&&u(e,["src"],Y0(p));let h=a(t,["outputConfig"]);h!=null&&u(e,["dest"],J0(_E(h)));let m=a(t,["completionStats"]);m!=null&&u(e,["completionStats"],m);let g=a(t,["outputInfo"]);return g!=null&&u(e,["outputInfo"],g),e}function Y0(t){let e={},n=a(t,["instancesFormat"]);n!=null&&u(e,["format"],n);let r=a(t,["gcsSource","uris"]);r!=null&&u(e,["gcsUri"],r);let i=a(t,["bigquerySource","inputUri"]);i!=null&&u(e,["bigqueryUri"],i);let s=a(t,["vertexMultimodalDatasetSource","datasetName"]);return s!=null&&u(e,["vertexDatasetName"],s),e}function X0(t,e){let n={};if(a(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(a(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(a(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");let r=a(e,["fileName"]);r!=null&&u(n,["fileName"],r);let i=a(e,["inlinedRequests"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>SR(t,o))),u(n,["requests","requests"],s)}if(a(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is not supported in Gemini API.");return n}function Q0(t){let e={},n=a(t,["format"]);n!=null&&u(e,["instancesFormat"],n);let r=a(t,["gcsUri"]);r!=null&&u(e,["gcsSource","uris"],r);let i=a(t,["bigqueryUri"]);if(i!=null&&u(e,["bigquerySource","inputUri"],i),a(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let s=a(t,["vertexDatasetName"]);return s!=null&&u(e,["vertexMultimodalDatasetSource","datasetName"],s),e}function Z0(t){let e={},n=a(t,["data"]);if(n!=null&&u(e,["data"],n),a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function j0(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function eR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function tR(t){let e={},n=a(t,["content"]);n!=null&&u(e,["content"],n);let r=a(t,["citationMetadata"]);r!=null&&u(e,["citationMetadata"],nR(r));let i=a(t,["tokenCount"]);i!=null&&u(e,["tokenCount"],i);let s=a(t,["finishReason"]);s!=null&&u(e,["finishReason"],s);let o=a(t,["groundingMetadata"]);o!=null&&u(e,["groundingMetadata"],o);let l=a(t,["avgLogprobs"]);l!=null&&u(e,["avgLogprobs"],l);let d=a(t,["index"]);d!=null&&u(e,["index"],d);let c=a(t,["logprobsResult"]);c!=null&&u(e,["logprobsResult"],c);let f=a(t,["safetyRatings"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),u(e,["safetyRatings"],h)}let p=a(t,["urlContextMetadata"]);return p!=null&&u(e,["urlContextMetadata"],p),e}function nR(t){let e={},n=a(t,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),u(e,["citations"],r)}return e}function AE(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>MR(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function rR(t,e){let n={},r=a(t,["displayName"]);if(e!==void 0&&r!=null&&u(e,["batch","displayName"],r),a(t,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");let i=a(t,["webhookConfig"]);return e!==void 0&&i!=null&&u(e,["batch","webhookConfig"],i),n}function iR(t,e){let n={},r=a(t,["displayName"]);e!==void 0&&r!=null&&u(e,["displayName"],r);let i=a(t,["dest"]);if(e!==void 0&&i!=null&&u(e,["outputConfig"],z0(V0(i))),a(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function DA(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["_url","model"],de(t,r));let i=a(e,["src"]);i!=null&&u(n,["batch","inputConfig"],X0(t,gE(t,i)));let s=a(e,["config"]);return s!=null&&rR(s,n),n}function sR(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["model"],de(t,r));let i=a(e,["src"]);i!=null&&u(n,["inputConfig"],Q0(gE(t,i)));let s=a(e,["config"]);return s!=null&&iR(s,n),n}function oR(t,e){let n={},r=a(t,["displayName"]);return e!==void 0&&r!=null&&u(e,["batch","displayName"],r),n}function aR(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["_url","model"],de(t,r));let i=a(e,["src"]);i!=null&&u(n,["batch","inputConfig"],hR(t,i));let s=a(e,["config"]);return s!=null&&oR(s,n),n}function lR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function uR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function cR(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["name"]);r!=null&&u(e,["name"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);return s!=null&&u(e,["error"],s),e}function dR(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["name"]);r!=null&&u(e,["name"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);return s!=null&&u(e,["error"],s),e}function fR(t,e){let n={},r=a(e,["contents"]);if(r!=null){let s=Rp(t,r);Array.isArray(s)&&(s=s.map(o=>o)),u(n,["requests[]","request","content"],s)}let i=a(e,["config"]);return i!=null&&(u(n,["_self"],pR(i,n)),w0(n,{"requests[].*":"requests[].request.*"})),n}function pR(t,e){let n={},r=a(t,["taskType"]);e!==void 0&&r!=null&&u(e,["requests[]","taskType"],r);let i=a(t,["title"]);e!==void 0&&i!=null&&u(e,["requests[]","title"],i);let s=a(t,["outputDimensionality"]);if(e!==void 0&&s!=null&&u(e,["requests[]","outputDimensionality"],s),a(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(a(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");if(a(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is not supported in Gemini API.");if(a(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is not supported in Gemini API.");return n}function hR(t,e){let n={},r=a(e,["fileName"]);r!=null&&u(n,["file_name"],r);let i=a(e,["inlinedRequests"]);return i!=null&&u(n,["requests"],fR(t,i)),n}function mR(t){let e={};if(a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let n=a(t,["fileUri"]);n!=null&&u(e,["fileUri"],n);let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function gR(t){let e={},n=a(t,["id"]);n!=null&&u(e,["id"],n);let r=a(t,["args"]);r!=null&&u(e,["args"],r);let i=a(t,["name"]);if(i!=null&&u(e,["name"],i),a(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(a(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function _R(t){let e={},n=a(t,["allowedFunctionNames"]);n!=null&&u(e,["allowedFunctionNames"],n);let r=a(t,["mode"]);if(r!=null&&u(e,["mode"],r),a(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function yR(t,e,n){let r={},i=a(e,["systemInstruction"]);n!==void 0&&i!=null&&u(n,["systemInstruction"],AE(Ne(i)));let s=a(e,["temperature"]);s!=null&&u(r,["temperature"],s);let o=a(e,["topP"]);o!=null&&u(r,["topP"],o);let l=a(e,["topK"]);l!=null&&u(r,["topK"],l);let d=a(e,["candidateCount"]);d!=null&&u(r,["candidateCount"],d);let c=a(e,["maxOutputTokens"]);c!=null&&u(r,["maxOutputTokens"],c);let f=a(e,["stopSequences"]);f!=null&&u(r,["stopSequences"],f);let p=a(e,["responseLogprobs"]);p!=null&&u(r,["responseLogprobs"],p);let h=a(e,["logprobs"]);h!=null&&u(r,["logprobs"],h);let m=a(e,["presencePenalty"]);m!=null&&u(r,["presencePenalty"],m);let g=a(e,["frequencyPenalty"]);g!=null&&u(r,["frequencyPenalty"],g);let _=a(e,["seed"]);_!=null&&u(r,["seed"],_);let y=a(e,["responseMimeType"]);y!=null&&u(r,["responseMimeType"],y);let T=a(e,["responseSchema"]);T!=null&&u(r,["responseSchema"],xp(T));let C=a(e,["responseJsonSchema"]);if(C!=null&&u(r,["responseJsonSchema"],C),a(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(a(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let R=a(e,["safetySettings"]);if(n!==void 0&&R!=null){let ae=R;Array.isArray(ae)&&(ae=ae.map(fe=>DR(fe))),u(n,["safetySettings"],ae)}let x=a(e,["tools"]);if(n!==void 0&&x!=null){let ae=ki(x);Array.isArray(ae)&&(ae=ae.map(fe=>UR(bi(fe)))),u(n,["tools"],ae)}let G=a(e,["toolConfig"]);if(n!==void 0&&G!=null&&u(n,["toolConfig"],OR(G)),a(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let S=a(e,["cachedContent"]);n!==void 0&&S!=null&&u(n,["cachedContent"],mn(t,S));let q=a(e,["responseModalities"]);q!=null&&u(r,["responseModalities"],q);let $=a(e,["mediaResolution"]);$!=null&&u(r,["mediaResolution"],$);let N=a(e,["speechConfig"]);if(N!=null&&u(r,["speechConfig"],bp(N)),a(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let K=a(e,["thinkingConfig"]);K!=null&&u(r,["thinkingConfig"],K);let Q=a(e,["imageConfig"]);Q!=null&&u(r,["imageConfig"],IR(Q));let oe=a(e,["enableEnhancedCivicAnswers"]);if(oe!=null&&u(r,["enableEnhancedCivicAnswers"],oe),a(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");let ie=a(e,["serviceTier"]);return n!==void 0&&ie!=null&&u(n,["serviceTier"],ie),r}function AR(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["candidates"]);if(r!=null){let c=r;Array.isArray(c)&&(c=c.map(f=>tR(f))),u(e,["candidates"],c)}let i=a(t,["modelVersion"]);i!=null&&u(e,["modelVersion"],i);let s=a(t,["promptFeedback"]);s!=null&&u(e,["promptFeedback"],s);let o=a(t,["responseId"]);o!=null&&u(e,["responseId"],o);let l=a(t,["usageMetadata"]);l!=null&&u(e,["usageMetadata"],l);let d=a(t,["modelStatus"]);return d!=null&&u(e,["modelStatus"],d),e}function ER(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function TR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],Ni(t,r)),n}function wR(t){let e={},n=a(t,["authConfig"]);n!=null&&u(e,["authConfig"],K0(n));let r=a(t,["enableWidget"]);return r!=null&&u(e,["enableWidget"],r),e}function CR(t){let e={},n=a(t,["searchTypes"]);if(n!=null&&u(e,["searchTypes"],n),a(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(a(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");let r=a(t,["timeRangeFilter"]);return r!=null&&u(e,["timeRangeFilter"],r),e}function IR(t){let e={},n=a(t,["aspectRatio"]);n!=null&&u(e,["aspectRatio"],n);let r=a(t,["imageSize"]);if(r!=null&&u(e,["imageSize"],r),a(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(a(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is not supported in Gemini API.");if(a(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(a(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(a(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return e}function SR(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["request","model"],de(t,r));let i=a(e,["contents"]);if(i!=null){let l=Xe(i);Array.isArray(l)&&(l=l.map(d=>AE(d))),u(n,["request","contents"],l)}let s=a(e,["metadata"]);s!=null&&u(n,["metadata"],s);let o=a(e,["config"]);return o!=null&&u(n,["request","generationConfig"],yR(t,o,a(n,["request"],{}))),n}function vR(t){let e={},n=a(t,["response"]);n!=null&&u(e,["response"],AR(n));let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["error"]);return i!=null&&u(e,["error"],i),e}function PR(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);if(e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),a(t,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return n}function RR(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);e!==void 0&&i!=null&&u(e,["_query","pageToken"],i);let s=a(t,["filter"]);return e!==void 0&&s!=null&&u(e,["_query","filter"],s),n}function xR(t){let e={},n=a(t,["config"]);return n!=null&&PR(n,e),e}function bR(t){let e={},n=a(t,["config"]);return n!=null&&RR(n,e),e}function kR(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["operations"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>Il(o))),u(e,["batchJobs"],s)}return e}function NR(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["batchPredictionJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>Kf(o))),u(e,["batchJobs"],s)}return e}function MR(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],mR(s));let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],gR(o));let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],Z0(d));let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);h!=null&&u(e,["videoMetadata"],h);let m=a(t,["toolCall"]);m!=null&&u(e,["toolCall"],m);let g=a(t,["toolResponse"]);g!=null&&u(e,["toolResponse"],g);let _=a(t,["partMetadata"]);return _!=null&&u(e,["partMetadata"],_),e}function DR(t){let e={},n=a(t,["category"]);if(n!=null&&u(e,["category"],n),a(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let r=a(t,["threshold"]);return r!=null&&u(e,["threshold"],r),e}function OR(t){let e={},n=a(t,["retrievalConfig"]);n!=null&&u(e,["retrievalConfig"],n);let r=a(t,["functionCallingConfig"]);r!=null&&u(e,["functionCallingConfig"],_R(r));let i=a(t,["includeServerSideToolInvocations"]);return i!=null&&u(e,["includeServerSideToolInvocations"],i),e}function UR(t){let e={};if(a(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let n=a(t,["computerUse"]);n!=null&&u(e,["computerUse"],n);let r=a(t,["fileSearch"]);r!=null&&u(e,["fileSearch"],r);let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],CR(i));let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],wR(s));let o=a(t,["codeExecution"]);if(o!=null&&u(e,["codeExecution"],o),a(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let l=a(t,["functionDeclarations"]);if(l!=null){let p=l;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["functionDeclarations"],p)}let d=a(t,["googleSearchRetrieval"]);if(d!=null&&u(e,["googleSearchRetrieval"],d),a(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");let c=a(t,["urlContext"]);c!=null&&u(e,["urlContext"],c);let f=a(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["mcpServers"],p)}return e}function LR(t){let e={},n=a(t,["bigqueryDestination","outputUri"]);n!=null&&u(e,["bigqueryDestination"],n);let r=a(t,["displayName"]);return r!=null&&u(e,["displayName"],r),e}function FR(t){let e={},n=a(t,["bigqueryDestination"]);n!=null&&u(e,["bigqueryDestination","outputUri"],n);let r=a(t,["displayName"]);return r!=null&&u(e,["displayName"],r),e}var pn;(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"})(pn||(pn={}));var hn=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}};var Wf=class extends Ot{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hn(pn.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=DA(this.apiClient,e),r=n._url,i=z("{model}:batchGenerateContent",r),l=n.batch.inputConfig.requests,d=l.requests,c=[];for(let f of d){let p=Object.assign({},f);if(p.systemInstruction){let h=p.systemInstruction;delete p.systemInstruction;let m=p.request;m.systemInstruction=h,p.request=m}c.push(p)}return l.requests=c,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,l="",d={};if(this.apiClient.isVertexAI()){let c=sR(this.apiClient,e);return l=z("batchPredictionJobs",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json()),o.then(f=>Kf(f))}else{let c=DA(this.apiClient,e);return l=z("{model}:batchGenerateContent",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json()),o.then(f=>Il(f))}}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 l=aR(this.apiClient,e);return s=z("{model}:asyncBatchEmbedContent",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>Il(d))}}async get(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=TR(this.apiClient,e);return l=z("batchPredictionJobs/{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o.then(f=>Kf(f))}else{let c=ER(this.apiClient,e);return l=z("batches/{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o.then(f=>Il(f))}}async cancel(e){var n,r,i,s;let o="",l={};if(this.apiClient.isVertexAI()){let d=eR(this.apiClient,e);o=z("batchPredictionJobs/{name}:cancel",d._url),l=d._query,delete d._url,delete d._query,await this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}else{let d=j0(this.apiClient,e);o=z("batches/{name}:cancel",d._url),l=d._query,delete d._url,delete d._query,await this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(d),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,l="",d={};if(this.apiClient.isVertexAI()){let c=bR(e);return l=z("batchPredictionJobs",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=NR(f),h=new Ll;return Object.assign(h,p),h})}else{let c=xR(e);return l=z("batches",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=kR(f),h=new Ll;return Object.assign(h,p),h})}}async delete(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=uR(this.apiClient,e);return l=z("batchPredictionJobs/{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>dR(f))}else{let c=lR(this.apiClient,e);return l=z("batches/{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>cR(f))}}};function GR(t){let e={},n=a(t,["apiKey"]);if(n!=null&&u(e,["apiKey"],n),a(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(a(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(a(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(a(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(a(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(a(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function qR(t){let e={},n=a(t,["data"]);if(n!=null&&u(e,["data"],n),a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function OA(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>ux(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function UA(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>cx(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function BR(t,e){let n={},r=a(t,["ttl"]);e!==void 0&&r!=null&&u(e,["ttl"],r);let i=a(t,["expireTime"]);e!==void 0&&i!=null&&u(e,["expireTime"],i);let s=a(t,["displayName"]);e!==void 0&&s!=null&&u(e,["displayName"],s);let o=a(t,["contents"]);if(e!==void 0&&o!=null){let f=Xe(o);Array.isArray(f)&&(f=f.map(p=>OA(p))),u(e,["contents"],f)}let l=a(t,["systemInstruction"]);e!==void 0&&l!=null&&u(e,["systemInstruction"],OA(Ne(l)));let d=a(t,["tools"]);if(e!==void 0&&d!=null){let f=d;Array.isArray(f)&&(f=f.map(p=>px(p))),u(e,["tools"],f)}let c=a(t,["toolConfig"]);if(e!==void 0&&c!=null&&u(e,["toolConfig"],dx(c)),a(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function $R(t,e){let n={},r=a(t,["ttl"]);e!==void 0&&r!=null&&u(e,["ttl"],r);let i=a(t,["expireTime"]);e!==void 0&&i!=null&&u(e,["expireTime"],i);let s=a(t,["displayName"]);e!==void 0&&s!=null&&u(e,["displayName"],s);let o=a(t,["contents"]);if(e!==void 0&&o!=null){let p=Xe(o);Array.isArray(p)&&(p=p.map(h=>UA(h))),u(e,["contents"],p)}let l=a(t,["systemInstruction"]);e!==void 0&&l!=null&&u(e,["systemInstruction"],UA(Ne(l)));let d=a(t,["tools"]);if(e!==void 0&&d!=null){let p=d;Array.isArray(p)&&(p=p.map(h=>hx(h))),u(e,["tools"],p)}let c=a(t,["toolConfig"]);e!==void 0&&c!=null&&u(e,["toolConfig"],fx(c));let f=a(t,["kmsKeyName"]);return e!==void 0&&f!=null&&u(e,["encryption_spec","kmsKeyName"],f),n}function VR(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["model"],oE(t,r));let i=a(e,["config"]);return i!=null&&BR(i,n),n}function HR(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["model"],oE(t,r));let i=a(e,["config"]);return i!=null&&$R(i,n),n}function KR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],mn(t,r)),n}function WR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],mn(t,r)),n}function JR(t){let e={},n=a(t,["sdkHttpResponse"]);return n!=null&&u(e,["sdkHttpResponse"],n),e}function zR(t){let e={},n=a(t,["sdkHttpResponse"]);return n!=null&&u(e,["sdkHttpResponse"],n),e}function YR(t){let e={};if(a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let n=a(t,["fileUri"]);n!=null&&u(e,["fileUri"],n);let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function XR(t){let e={},n=a(t,["id"]);n!=null&&u(e,["id"],n);let r=a(t,["args"]);r!=null&&u(e,["args"],r);let i=a(t,["name"]);if(i!=null&&u(e,["name"],i),a(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(a(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function QR(t){let e={},n=a(t,["allowedFunctionNames"]);n!=null&&u(e,["allowedFunctionNames"],n);let r=a(t,["mode"]);if(r!=null&&u(e,["mode"],r),a(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function ZR(t){let e={},n=a(t,["description"]);n!=null&&u(e,["description"],n);let r=a(t,["name"]);r!=null&&u(e,["name"],r);let i=a(t,["parameters"]);i!=null&&u(e,["parameters"],i);let s=a(t,["parametersJsonSchema"]);s!=null&&u(e,["parametersJsonSchema"],s);let o=a(t,["response"]);o!=null&&u(e,["response"],o);let l=a(t,["responseJsonSchema"]);if(l!=null&&u(e,["responseJsonSchema"],l),a(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function jR(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],mn(t,r)),n}function ex(t,e){let n={},r=a(e,["name"]);return r!=null&&u(n,["_url","name"],mn(t,r)),n}function tx(t){let e={},n=a(t,["authConfig"]);n!=null&&u(e,["authConfig"],GR(n));let r=a(t,["enableWidget"]);return r!=null&&u(e,["enableWidget"],r),e}function nx(t){let e={},n=a(t,["searchTypes"]);if(n!=null&&u(e,["searchTypes"],n),a(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(a(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");let r=a(t,["timeRangeFilter"]);return r!=null&&u(e,["timeRangeFilter"],r),e}function rx(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);return e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),n}function ix(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);return e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),n}function sx(t){let e={},n=a(t,["config"]);return n!=null&&rx(n,e),e}function ox(t){let e={},n=a(t,["config"]);return n!=null&&ix(n,e),e}function ax(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["cachedContents"],s)}return e}function lx(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["cachedContents"],s)}return e}function ux(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],YR(s));let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],XR(o));let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],qR(d));let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);h!=null&&u(e,["videoMetadata"],h);let m=a(t,["toolCall"]);m!=null&&u(e,["toolCall"],m);let g=a(t,["toolResponse"]);g!=null&&u(e,["toolResponse"],g);let _=a(t,["partMetadata"]);return _!=null&&u(e,["partMetadata"],_),e}function cx(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],s);let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],o);let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],d);let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);if(h!=null&&u(e,["videoMetadata"],h),a(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function dx(t){let e={},n=a(t,["retrievalConfig"]);n!=null&&u(e,["retrievalConfig"],n);let r=a(t,["functionCallingConfig"]);r!=null&&u(e,["functionCallingConfig"],QR(r));let i=a(t,["includeServerSideToolInvocations"]);return i!=null&&u(e,["includeServerSideToolInvocations"],i),e}function fx(t){let e={},n=a(t,["retrievalConfig"]);n!=null&&u(e,["retrievalConfig"],n);let r=a(t,["functionCallingConfig"]);if(r!=null&&u(e,["functionCallingConfig"],r),a(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function px(t){let e={};if(a(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let n=a(t,["computerUse"]);n!=null&&u(e,["computerUse"],n);let r=a(t,["fileSearch"]);r!=null&&u(e,["fileSearch"],r);let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],nx(i));let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],tx(s));let o=a(t,["codeExecution"]);if(o!=null&&u(e,["codeExecution"],o),a(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let l=a(t,["functionDeclarations"]);if(l!=null){let p=l;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["functionDeclarations"],p)}let d=a(t,["googleSearchRetrieval"]);if(d!=null&&u(e,["googleSearchRetrieval"],d),a(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");let c=a(t,["urlContext"]);c!=null&&u(e,["urlContext"],c);let f=a(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["mcpServers"],p)}return e}function hx(t){let e={},n=a(t,["retrieval"]);n!=null&&u(e,["retrieval"],n);let r=a(t,["computerUse"]);if(r!=null&&u(e,["computerUse"],r),a(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],i);let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],s);let o=a(t,["codeExecution"]);o!=null&&u(e,["codeExecution"],o);let l=a(t,["enterpriseWebSearch"]);l!=null&&u(e,["enterpriseWebSearch"],l);let d=a(t,["functionDeclarations"]);if(d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>ZR(m))),u(e,["functionDeclarations"],h)}let c=a(t,["googleSearchRetrieval"]);c!=null&&u(e,["googleSearchRetrieval"],c);let f=a(t,["parallelAiSearch"]);f!=null&&u(e,["parallelAiSearch"],f);let p=a(t,["urlContext"]);if(p!=null&&u(e,["urlContext"],p),a(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function mx(t,e){let n={},r=a(t,["ttl"]);e!==void 0&&r!=null&&u(e,["ttl"],r);let i=a(t,["expireTime"]);return e!==void 0&&i!=null&&u(e,["expireTime"],i),n}function gx(t,e){let n={},r=a(t,["ttl"]);e!==void 0&&r!=null&&u(e,["ttl"],r);let i=a(t,["expireTime"]);return e!==void 0&&i!=null&&u(e,["expireTime"],i),n}function _x(t,e){let n={},r=a(e,["name"]);r!=null&&u(n,["_url","name"],mn(t,r));let i=a(e,["config"]);return i!=null&&mx(i,n),n}function yx(t,e){let n={},r=a(e,["name"]);r!=null&&u(n,["_url","name"],mn(t,r));let i=a(e,["config"]);return i!=null&&gx(i,n),n}var Jf=class extends Ot{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hn(pn.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=HR(this.apiClient,e);return l=z("cachedContents",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json()),o.then(f=>f)}else{let c=VR(this.apiClient,e);return l=z("cachedContents",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json()),o.then(f=>f)}}async get(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=ex(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o.then(f=>f)}else{let c=jR(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o.then(f=>f)}}async delete(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=WR(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=zR(f),h=new Ol;return Object.assign(h,p),h})}else{let c=KR(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=JR(f),h=new Ol;return Object.assign(h,p),h})}}async update(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=yx(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o.then(f=>f)}else{let c=_x(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o.then(f=>f)}}async listInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=ox(e);return l=z("cachedContents",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=lx(f),h=new Ul;return Object.assign(h,p),h})}else{let c=sx(e);return l=z("cachedContents",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=ax(f),h=new Ul;return Object.assign(h,p),h})}}};function Dn(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 LA(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function se(t){return this instanceof se?(this.v=t,this):new se(t)}function Mt(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),l("next"),l("throw"),l("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(m){return function(g){return Promise.resolve(g).then(m,p)}}function l(m,g){r[m]&&(i[m]=function(_){return new Promise(function(y,T){s.push([m,_,y,T])>1||d(m,_)})},g&&(i[m]=g(i[m])))}function d(m,g){try{c(r[m](g))}catch(_){h(s[0][3],_)}}function c(m){m.value instanceof se?Promise.resolve(m.value.v).then(f,p):h(s[0][2],m)}function f(m){d("next",m)}function p(m){d("throw",m)}function h(m,g){m(g),s.shift(),s.length&&d(s[0][0],s[0][1])}}function Dt(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 LA=="function"?LA(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(l,d){o=t[s](o),i(l,d,o.done,o.value)})}}function i(s,o,l,d){Promise.resolve(d).then(function(c){s({value:c,done:l})},o)}}function Ax(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:EE(n)}function EE(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 Ex(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 FA(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&&!EE(t[r])&&(s=!1),r++;s?e.push(...i):e.pop()}return e}var zf=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new Yf(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},Yf=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(),Ex(s)}async sendMessage(e){var n;await this.sendPromise;let r=Ne(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,l;let d=await i,c=(o=(s=d.candidates)===null||s===void 0?void 0:s[0])===null||o===void 0?void 0:o.content,f=d.automaticFunctionCallingHistory,p=this.getHistory(!0).length,h=[];f!=null&&(h=(l=f.slice(p))!==null&&l!==void 0?l:[]);let m=c?[c]:[];this.recordHistory(r,m,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let r=Ne(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?FA(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Mt(this,arguments,function*(){var i,s,o,l,d,c;let f=[];try{for(var p=!0,h=Dt(e),m;m=yield se(h.next()),i=m.done,!i;p=!0){l=m.value,p=!1;let g=l;if(Ax(g)){let _=(c=(d=g.candidates)===null||d===void 0?void 0:d[0])===null||c===void 0?void 0:c.content;_!==void 0&&f.push(_)}yield yield se(g)}}catch(g){s={error:g}}finally{try{!p&&!i&&(o=h.return)&&(yield se(o.call(h)))}finally{if(s)throw s.error}}this.recordHistory(n,f)})}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(...FA(r)):this.history.push(e),this.history.push(...i)}};var ql=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}};function Tx(t){let e={},n=a(t,["file"]);return n!=null&&u(e,["file"],n),e}function wx(t){let e={},n=a(t,["sdkHttpResponse"]);return n!=null&&u(e,["sdkHttpResponse"],n),e}function Cx(t){let e={},n=a(t,["name"]);return n!=null&&u(e,["_url","file"],Np(n)),e}function Ix(t){let e={},n=a(t,["sdkHttpResponse"]);return n!=null&&u(e,["sdkHttpResponse"],n),e}function Sx(t){let e={},n=a(t,["name"]);return n!=null&&u(e,["_url","file"],Np(n)),e}function vx(t){let e={},n=a(t,["uris"]);return n!=null&&u(e,["uris"],n),e}function Px(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);return e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),n}function Rx(t){let e={},n=a(t,["config"]);return n!=null&&Px(n,e),e}function xx(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["files"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["files"],s)}return e}function bx(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["files"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),u(e,["files"],i)}return e}var Xf=class extends Ot{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hn(pn.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 l=Rx(e);return s=z("files",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json().then(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=xx(d),f=new Ff;return Object.assign(f,c),f})}}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 l=Tx(e);return s=z("upload/v1beta/files",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=wx(d),f=new Gf;return Object.assign(f,c),f})}}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 l=Sx(e);return s=z("files/{file}",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json()),i.then(d=>d)}}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 l=Cx(e);return s=z("files/{file}",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json().then(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=Ix(d),f=new qf;return Object.assign(f,c),f})}}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 l=vx(e);return s=z("files:register",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=bx(d),f=new Bf;return Object.assign(f,c),f})}}};function GA(t){let e={};if(a(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is not supported in Gemini API.");return e}function kx(t){let e={},n=a(t,["apiKey"]);if(n!=null&&u(e,["apiKey"],n),a(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(a(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(a(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(a(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(a(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(a(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function Sl(t){let e={},n=a(t,["data"]);if(n!=null&&u(e,["data"],n),a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function Nx(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Yx(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function Mx(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Xx(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function Dx(t){let e={};if(a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let n=a(t,["fileUri"]);n!=null&&u(e,["fileUri"],n);let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function Ox(t){let e={},n=a(t,["id"]);n!=null&&u(e,["id"],n);let r=a(t,["args"]);r!=null&&u(e,["args"],r);let i=a(t,["name"]);if(i!=null&&u(e,["name"],i),a(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(a(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Ux(t){let e={},n=a(t,["description"]);n!=null&&u(e,["description"],n);let r=a(t,["name"]);r!=null&&u(e,["name"],r);let i=a(t,["parameters"]);i!=null&&u(e,["parameters"],i);let s=a(t,["parametersJsonSchema"]);s!=null&&u(e,["parametersJsonSchema"],s);let o=a(t,["response"]);o!=null&&u(e,["response"],o);let l=a(t,["responseJsonSchema"]);if(l!=null&&u(e,["responseJsonSchema"],l),a(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Lx(t){let e={},n=a(t,["modelSelectionConfig"]);n!=null&&u(e,["modelConfig"],n);let r=a(t,["responseJsonSchema"]);r!=null&&u(e,["responseJsonSchema"],r);let i=a(t,["audioTimestamp"]);i!=null&&u(e,["audioTimestamp"],i);let s=a(t,["candidateCount"]);s!=null&&u(e,["candidateCount"],s);let o=a(t,["enableAffectiveDialog"]);o!=null&&u(e,["enableAffectiveDialog"],o);let l=a(t,["frequencyPenalty"]);l!=null&&u(e,["frequencyPenalty"],l);let d=a(t,["logprobs"]);d!=null&&u(e,["logprobs"],d);let c=a(t,["maxOutputTokens"]);c!=null&&u(e,["maxOutputTokens"],c);let f=a(t,["mediaResolution"]);f!=null&&u(e,["mediaResolution"],f);let p=a(t,["presencePenalty"]);p!=null&&u(e,["presencePenalty"],p);let h=a(t,["responseLogprobs"]);h!=null&&u(e,["responseLogprobs"],h);let m=a(t,["responseMimeType"]);m!=null&&u(e,["responseMimeType"],m);let g=a(t,["responseModalities"]);g!=null&&u(e,["responseModalities"],g);let _=a(t,["responseSchema"]);_!=null&&u(e,["responseSchema"],_);let y=a(t,["routingConfig"]);y!=null&&u(e,["routingConfig"],y);let T=a(t,["seed"]);T!=null&&u(e,["seed"],T);let C=a(t,["speechConfig"]);C!=null&&u(e,["speechConfig"],C);let R=a(t,["stopSequences"]);R!=null&&u(e,["stopSequences"],R);let x=a(t,["temperature"]);x!=null&&u(e,["temperature"],x);let G=a(t,["thinkingConfig"]);G!=null&&u(e,["thinkingConfig"],G);let S=a(t,["topK"]);S!=null&&u(e,["topK"],S);let q=a(t,["topP"]);if(q!=null&&u(e,["topP"],q),a(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Fx(t){let e={},n=a(t,["authConfig"]);n!=null&&u(e,["authConfig"],kx(n));let r=a(t,["enableWidget"]);return r!=null&&u(e,["enableWidget"],r),e}function Gx(t){let e={},n=a(t,["searchTypes"]);if(n!=null&&u(e,["searchTypes"],n),a(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(a(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");let r=a(t,["timeRangeFilter"]);return r!=null&&u(e,["timeRangeFilter"],r),e}function qx(t,e){let n={},r=a(t,["generationConfig"]);e!==void 0&&r!=null&&u(e,["setup","generationConfig"],r);let i=a(t,["responseModalities"]);e!==void 0&&i!=null&&u(e,["setup","generationConfig","responseModalities"],i);let s=a(t,["temperature"]);e!==void 0&&s!=null&&u(e,["setup","generationConfig","temperature"],s);let o=a(t,["topP"]);e!==void 0&&o!=null&&u(e,["setup","generationConfig","topP"],o);let l=a(t,["topK"]);e!==void 0&&l!=null&&u(e,["setup","generationConfig","topK"],l);let d=a(t,["maxOutputTokens"]);e!==void 0&&d!=null&&u(e,["setup","generationConfig","maxOutputTokens"],d);let c=a(t,["mediaResolution"]);e!==void 0&&c!=null&&u(e,["setup","generationConfig","mediaResolution"],c);let f=a(t,["seed"]);e!==void 0&&f!=null&&u(e,["setup","generationConfig","seed"],f);let p=a(t,["speechConfig"]);e!==void 0&&p!=null&&u(e,["setup","generationConfig","speechConfig"],kp(p));let h=a(t,["thinkingConfig"]);e!==void 0&&h!=null&&u(e,["setup","generationConfig","thinkingConfig"],h);let m=a(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&u(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=a(t,["systemInstruction"]);e!==void 0&&g!=null&&u(e,["setup","systemInstruction"],Nx(Ne(g)));let _=a(t,["tools"]);if(e!==void 0&&_!=null){let $=ki(_);Array.isArray($)&&($=$.map(N=>jx(bi(N)))),u(e,["setup","tools"],$)}let y=a(t,["sessionResumption"]);e!==void 0&&y!=null&&u(e,["setup","sessionResumption"],Zx(y));let T=a(t,["inputAudioTranscription"]);e!==void 0&&T!=null&&u(e,["setup","inputAudioTranscription"],GA(T));let C=a(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&u(e,["setup","outputAudioTranscription"],GA(C));let R=a(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&u(e,["setup","realtimeInputConfig"],R);let x=a(t,["contextWindowCompression"]);e!==void 0&&x!=null&&u(e,["setup","contextWindowCompression"],x);let G=a(t,["proactivity"]);if(e!==void 0&&G!=null&&u(e,["setup","proactivity"],G),a(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");let S=a(t,["avatarConfig"]);e!==void 0&&S!=null&&u(e,["setup","avatarConfig"],S);let q=a(t,["safetySettings"]);if(e!==void 0&&q!=null){let $=q;Array.isArray($)&&($=$.map(N=>Qx(N))),u(e,["setup","safetySettings"],$)}return n}function Bx(t,e){let n={},r=a(t,["generationConfig"]);e!==void 0&&r!=null&&u(e,["setup","generationConfig"],Lx(r));let i=a(t,["responseModalities"]);e!==void 0&&i!=null&&u(e,["setup","generationConfig","responseModalities"],i);let s=a(t,["temperature"]);e!==void 0&&s!=null&&u(e,["setup","generationConfig","temperature"],s);let o=a(t,["topP"]);e!==void 0&&o!=null&&u(e,["setup","generationConfig","topP"],o);let l=a(t,["topK"]);e!==void 0&&l!=null&&u(e,["setup","generationConfig","topK"],l);let d=a(t,["maxOutputTokens"]);e!==void 0&&d!=null&&u(e,["setup","generationConfig","maxOutputTokens"],d);let c=a(t,["mediaResolution"]);e!==void 0&&c!=null&&u(e,["setup","generationConfig","mediaResolution"],c);let f=a(t,["seed"]);e!==void 0&&f!=null&&u(e,["setup","generationConfig","seed"],f);let p=a(t,["speechConfig"]);e!==void 0&&p!=null&&u(e,["setup","generationConfig","speechConfig"],kp(p));let h=a(t,["thinkingConfig"]);e!==void 0&&h!=null&&u(e,["setup","generationConfig","thinkingConfig"],h);let m=a(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&u(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=a(t,["systemInstruction"]);e!==void 0&&g!=null&&u(e,["setup","systemInstruction"],Mx(Ne(g)));let _=a(t,["tools"]);if(e!==void 0&&_!=null){let N=ki(_);Array.isArray(N)&&(N=N.map(K=>eb(bi(K)))),u(e,["setup","tools"],N)}let y=a(t,["sessionResumption"]);e!==void 0&&y!=null&&u(e,["setup","sessionResumption"],y);let T=a(t,["inputAudioTranscription"]);e!==void 0&&T!=null&&u(e,["setup","inputAudioTranscription"],T);let C=a(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&u(e,["setup","outputAudioTranscription"],C);let R=a(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&u(e,["setup","realtimeInputConfig"],R);let x=a(t,["contextWindowCompression"]);e!==void 0&&x!=null&&u(e,["setup","contextWindowCompression"],x);let G=a(t,["proactivity"]);e!==void 0&&G!=null&&u(e,["setup","proactivity"],G);let S=a(t,["explicitVadSignal"]);e!==void 0&&S!=null&&u(e,["setup","explicitVadSignal"],S);let q=a(t,["avatarConfig"]);e!==void 0&&q!=null&&u(e,["setup","avatarConfig"],q);let $=a(t,["safetySettings"]);if(e!==void 0&&$!=null){let N=$;Array.isArray(N)&&(N=N.map(K=>K)),u(e,["setup","safetySettings"],N)}return n}function $x(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["setup","model"],de(t,r));let i=a(e,["config"]);return i!=null&&u(n,["config"],qx(i,n)),n}function Vx(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["setup","model"],de(t,r));let i=a(e,["config"]);return i!=null&&u(n,["config"],Bx(i,n)),n}function Hx(t){let e={},n=a(t,["musicGenerationConfig"]);return n!=null&&u(e,["musicGenerationConfig"],n),e}function Kx(t){let e={},n=a(t,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),u(e,["weightedPrompts"],r)}return e}function Wx(t){let e={},n=a(t,["media"]);if(n!=null){let c=aE(n);Array.isArray(c)&&(c=c.map(f=>Sl(f))),u(e,["mediaChunks"],c)}let r=a(t,["audio"]);r!=null&&u(e,["audio"],Sl(uE(r)));let i=a(t,["audioStreamEnd"]);i!=null&&u(e,["audioStreamEnd"],i);let s=a(t,["video"]);s!=null&&u(e,["video"],Sl(lE(s)));let o=a(t,["text"]);o!=null&&u(e,["text"],o);let l=a(t,["activityStart"]);l!=null&&u(e,["activityStart"],l);let d=a(t,["activityEnd"]);return d!=null&&u(e,["activityEnd"],d),e}function Jx(t){let e={},n=a(t,["media"]);if(n!=null){let c=aE(n);Array.isArray(c)&&(c=c.map(f=>f)),u(e,["mediaChunks"],c)}let r=a(t,["audio"]);r!=null&&u(e,["audio"],uE(r));let i=a(t,["audioStreamEnd"]);i!=null&&u(e,["audioStreamEnd"],i);let s=a(t,["video"]);s!=null&&u(e,["video"],lE(s));let o=a(t,["text"]);o!=null&&u(e,["text"],o);let l=a(t,["activityStart"]);l!=null&&u(e,["activityStart"],l);let d=a(t,["activityEnd"]);return d!=null&&u(e,["activityEnd"],d),e}function zx(t){let e={},n=a(t,["setupComplete"]);n!=null&&u(e,["setupComplete"],n);let r=a(t,["serverContent"]);r!=null&&u(e,["serverContent"],r);let i=a(t,["toolCall"]);i!=null&&u(e,["toolCall"],i);let s=a(t,["toolCallCancellation"]);s!=null&&u(e,["toolCallCancellation"],s);let o=a(t,["usageMetadata"]);o!=null&&u(e,["usageMetadata"],tb(o));let l=a(t,["goAway"]);l!=null&&u(e,["goAway"],l);let d=a(t,["sessionResumptionUpdate"]);d!=null&&u(e,["sessionResumptionUpdate"],d);let c=a(t,["voiceActivityDetectionSignal"]);c!=null&&u(e,["voiceActivityDetectionSignal"],c);let f=a(t,["voiceActivity"]);return f!=null&&u(e,["voiceActivity"],nb(f)),e}function Yx(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],Dx(s));let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],Ox(o));let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],Sl(d));let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);h!=null&&u(e,["videoMetadata"],h);let m=a(t,["toolCall"]);m!=null&&u(e,["toolCall"],m);let g=a(t,["toolResponse"]);g!=null&&u(e,["toolResponse"],g);let _=a(t,["partMetadata"]);return _!=null&&u(e,["partMetadata"],_),e}function Xx(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],s);let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],o);let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],d);let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);if(h!=null&&u(e,["videoMetadata"],h),a(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Qx(t){let e={},n=a(t,["category"]);if(n!=null&&u(e,["category"],n),a(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let r=a(t,["threshold"]);return r!=null&&u(e,["threshold"],r),e}function Zx(t){let e={},n=a(t,["handle"]);if(n!=null&&u(e,["handle"],n),a(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function jx(t){let e={};if(a(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let n=a(t,["computerUse"]);n!=null&&u(e,["computerUse"],n);let r=a(t,["fileSearch"]);r!=null&&u(e,["fileSearch"],r);let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],Gx(i));let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],Fx(s));let o=a(t,["codeExecution"]);if(o!=null&&u(e,["codeExecution"],o),a(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let l=a(t,["functionDeclarations"]);if(l!=null){let p=l;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["functionDeclarations"],p)}let d=a(t,["googleSearchRetrieval"]);if(d!=null&&u(e,["googleSearchRetrieval"],d),a(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");let c=a(t,["urlContext"]);c!=null&&u(e,["urlContext"],c);let f=a(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["mcpServers"],p)}return e}function eb(t){let e={},n=a(t,["retrieval"]);n!=null&&u(e,["retrieval"],n);let r=a(t,["computerUse"]);if(r!=null&&u(e,["computerUse"],r),a(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],i);let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],s);let o=a(t,["codeExecution"]);o!=null&&u(e,["codeExecution"],o);let l=a(t,["enterpriseWebSearch"]);l!=null&&u(e,["enterpriseWebSearch"],l);let d=a(t,["functionDeclarations"]);if(d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>Ux(m))),u(e,["functionDeclarations"],h)}let c=a(t,["googleSearchRetrieval"]);c!=null&&u(e,["googleSearchRetrieval"],c);let f=a(t,["parallelAiSearch"]);f!=null&&u(e,["parallelAiSearch"],f);let p=a(t,["urlContext"]);if(p!=null&&u(e,["urlContext"],p),a(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function tb(t){let e={},n=a(t,["promptTokenCount"]);n!=null&&u(e,["promptTokenCount"],n);let r=a(t,["cachedContentTokenCount"]);r!=null&&u(e,["cachedContentTokenCount"],r);let i=a(t,["candidatesTokenCount"]);i!=null&&u(e,["responseTokenCount"],i);let s=a(t,["toolUsePromptTokenCount"]);s!=null&&u(e,["toolUsePromptTokenCount"],s);let o=a(t,["thoughtsTokenCount"]);o!=null&&u(e,["thoughtsTokenCount"],o);let l=a(t,["totalTokenCount"]);l!=null&&u(e,["totalTokenCount"],l);let d=a(t,["promptTokensDetails"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(g=>g)),u(e,["promptTokensDetails"],m)}let c=a(t,["cacheTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(g=>g)),u(e,["cacheTokensDetails"],m)}let f=a(t,["candidatesTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),u(e,["responseTokensDetails"],m)}let p=a(t,["toolUsePromptTokensDetails"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(g=>g)),u(e,["toolUsePromptTokensDetails"],m)}let h=a(t,["trafficType"]);return h!=null&&u(e,["trafficType"],h),e}function nb(t){let e={},n=a(t,["type"]);return n!=null&&u(e,["voiceActivityType"],n),e}function rb(t,e){let n={},r=a(t,["apiKey"]);if(r!=null&&u(n,["apiKey"],r),a(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(a(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(a(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(a(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(a(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(a(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return n}function ib(t,e){let n={},r=a(t,["data"]);if(r!=null&&u(n,["data"],r),a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=a(t,["mimeType"]);return i!=null&&u(n,["mimeType"],i),n}function sb(t,e){let n={},r=a(t,["content"]);r!=null&&u(n,["content"],r);let i=a(t,["citationMetadata"]);i!=null&&u(n,["citationMetadata"],ob(i));let s=a(t,["tokenCount"]);s!=null&&u(n,["tokenCount"],s);let o=a(t,["finishReason"]);o!=null&&u(n,["finishReason"],o);let l=a(t,["groundingMetadata"]);l!=null&&u(n,["groundingMetadata"],l);let d=a(t,["avgLogprobs"]);d!=null&&u(n,["avgLogprobs"],d);let c=a(t,["index"]);c!=null&&u(n,["index"],c);let f=a(t,["logprobsResult"]);f!=null&&u(n,["logprobsResult"],f);let p=a(t,["safetyRatings"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(g=>g)),u(n,["safetyRatings"],m)}let h=a(t,["urlContextMetadata"]);return h!=null&&u(n,["urlContextMetadata"],h),n}function ob(t,e){let n={},r=a(t,["citationSources"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),u(n,["citations"],i)}return n}function ab(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let o=Xe(s);Array.isArray(o)&&(o=o.map(l=>Mi(l))),u(r,["contents"],o)}return r}function lb(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["tokensInfo"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(n,["tokensInfo"],s)}return n}function ub(t,e){let n={},r=a(t,["values"]);r!=null&&u(n,["values"],r);let i=a(t,["statistics"]);return i!=null&&u(n,["statistics"],cb(i)),n}function cb(t,e){let n={},r=a(t,["truncated"]);r!=null&&u(n,["truncated"],r);let i=a(t,["token_count"]);return i!=null&&u(n,["tokenCount"],i),n}function bo(t,e){let n={},r=a(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Ak(o))),u(n,["parts"],s)}let i=a(t,["role"]);return i!=null&&u(n,["role"],i),n}function Mi(t,e){let n={},r=a(t,["parts"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Ek(o))),u(n,["parts"],s)}let i=a(t,["role"]);return i!=null&&u(n,["role"],i),n}function db(t,e){let n={},r=a(t,["controlType"]);r!=null&&u(n,["controlType"],r);let i=a(t,["enableControlImageComputation"]);return i!=null&&u(n,["computeControl"],i),n}function fb(t,e){let n={};if(a(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(a(t,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(a(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return n}function pb(t,e,n){let r={},i=a(t,["systemInstruction"]);e!==void 0&&i!=null&&u(e,["systemInstruction"],Mi(Ne(i)));let s=a(t,["tools"]);if(e!==void 0&&s!=null){let l=s;Array.isArray(l)&&(l=l.map(d=>IE(d))),u(e,["tools"],l)}let o=a(t,["generationConfig"]);return e!==void 0&&o!=null&&u(e,["generationConfig"],ik(o)),r}function hb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let l=Xe(s);Array.isArray(l)&&(l=l.map(d=>bo(d))),u(r,["contents"],l)}let o=a(e,["config"]);return o!=null&&fb(o),r}function mb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let l=Xe(s);Array.isArray(l)&&(l=l.map(d=>Mi(d))),u(r,["contents"],l)}let o=a(e,["config"]);return o!=null&&pb(o,r),r}function gb(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["totalTokens"]);i!=null&&u(n,["totalTokens"],i);let s=a(t,["cachedContentTokenCount"]);return s!=null&&u(n,["cachedContentTokenCount"],s),n}function _b(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["totalTokens"]);return i!=null&&u(n,["totalTokens"],i),n}function yb(t,e,n){let r={},i=a(e,["model"]);return i!=null&&u(r,["_url","name"],de(t,i)),r}function Ab(t,e,n){let r={},i=a(e,["model"]);return i!=null&&u(r,["_url","name"],de(t,i)),r}function Eb(t,e){let n={},r=a(t,["sdkHttpResponse"]);return r!=null&&u(n,["sdkHttpResponse"],r),n}function Tb(t,e){let n={},r=a(t,["sdkHttpResponse"]);return r!=null&&u(n,["sdkHttpResponse"],r),n}function wb(t,e,n){let r={},i=a(t,["outputGcsUri"]);e!==void 0&&i!=null&&u(e,["parameters","storageUri"],i);let s=a(t,["negativePrompt"]);e!==void 0&&s!=null&&u(e,["parameters","negativePrompt"],s);let o=a(t,["numberOfImages"]);e!==void 0&&o!=null&&u(e,["parameters","sampleCount"],o);let l=a(t,["aspectRatio"]);e!==void 0&&l!=null&&u(e,["parameters","aspectRatio"],l);let d=a(t,["guidanceScale"]);e!==void 0&&d!=null&&u(e,["parameters","guidanceScale"],d);let c=a(t,["seed"]);e!==void 0&&c!=null&&u(e,["parameters","seed"],c);let f=a(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&u(e,["parameters","safetySetting"],f);let p=a(t,["personGeneration"]);e!==void 0&&p!=null&&u(e,["parameters","personGeneration"],p);let h=a(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&u(e,["parameters","includeSafetyAttributes"],h);let m=a(t,["includeRaiReason"]);e!==void 0&&m!=null&&u(e,["parameters","includeRaiReason"],m);let g=a(t,["language"]);e!==void 0&&g!=null&&u(e,["parameters","language"],g);let _=a(t,["outputMimeType"]);e!==void 0&&_!=null&&u(e,["parameters","outputOptions","mimeType"],_);let y=a(t,["outputCompressionQuality"]);e!==void 0&&y!=null&&u(e,["parameters","outputOptions","compressionQuality"],y);let T=a(t,["addWatermark"]);e!==void 0&&T!=null&&u(e,["parameters","addWatermark"],T);let C=a(t,["labels"]);e!==void 0&&C!=null&&u(e,["labels"],C);let R=a(t,["editMode"]);e!==void 0&&R!=null&&u(e,["parameters","editMode"],R);let x=a(t,["baseSteps"]);return e!==void 0&&x!=null&&u(e,["parameters","editConfig","baseSteps"],x),r}function Cb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["prompt"]);s!=null&&u(r,["instances[0]","prompt"],s);let o=a(e,["referenceImages"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(c=>vk(c))),u(r,["instances[0]","referenceImages"],d)}let l=a(e,["config"]);return l!=null&&wb(l,r),r}function Ib(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>iu(o))),u(n,["generatedImages"],s)}return n}function Sb(t,e,n){let r={},i=a(t,["taskType"]);e!==void 0&&i!=null&&u(e,["requests[]","taskType"],i);let s=a(t,["title"]);e!==void 0&&s!=null&&u(e,["requests[]","title"],s);let o=a(t,["outputDimensionality"]);if(e!==void 0&&o!=null&&u(e,["requests[]","outputDimensionality"],o),a(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(a(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");if(a(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is not supported in Gemini API.");if(a(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is not supported in Gemini API.");return r}function vb(t,e,n){let r={},i=a(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let p=a(t,["taskType"]);e!==void 0&&p!=null&&u(e,["instances[]","task_type"],p)}else if(i==="EMBED_CONTENT"){let p=a(t,["taskType"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","taskType"],p)}let s=a(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let p=a(t,["title"]);e!==void 0&&p!=null&&u(e,["instances[]","title"],p)}else if(s==="EMBED_CONTENT"){let p=a(t,["title"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","title"],p)}let o=a(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let p=a(t,["outputDimensionality"]);e!==void 0&&p!=null&&u(e,["parameters","outputDimensionality"],p)}else if(o==="EMBED_CONTENT"){let p=a(t,["outputDimensionality"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","outputDimensionality"],p)}let l=a(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="PREDICT"){let p=a(t,["mimeType"]);e!==void 0&&p!=null&&u(e,["instances[]","mimeType"],p)}let d=a(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="PREDICT"){let p=a(t,["autoTruncate"]);e!==void 0&&p!=null&&u(e,["parameters","autoTruncate"],p)}else if(d==="EMBED_CONTENT"){let p=a(t,["autoTruncate"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","autoTruncate"],p)}let c=a(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="EMBED_CONTENT"){let p=a(t,["documentOcr"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","documentOcr"],p)}let f=a(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=a(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&u(e,["embedContentConfig","audioTrackExtraction"],p)}return r}function Pb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let c=Rp(t,s);Array.isArray(c)&&(c=c.map(f=>f)),u(r,["requests[]","content"],c)}let o=a(e,["content"]);o!=null&&bo(Ne(o));let l=a(e,["config"]);l!=null&&Sb(l,r);let d=a(e,["model"]);return d!==void 0&&u(r,["requests[]","model"],de(t,d)),r}function Rb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let d=a(e,["contents"]);if(d!=null){let c=Rp(t,d);Array.isArray(c)&&(c=c.map(f=>f)),u(r,["instances[]","content"],c)}}let o=a(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="EMBED_CONTENT"){let d=a(e,["content"]);d!=null&&u(r,["content"],Mi(Ne(d)))}let l=a(e,["config"]);return l!=null&&vb(l,r,n),r}function xb(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(l=>l)),u(n,["embeddings"],o)}let s=a(t,["metadata"]);return s!=null&&u(n,["metadata"],s),n}function bb(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["predictions[]","embeddings"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(l=>ub(l))),u(n,["embeddings"],o)}let s=a(t,["metadata"]);if(s!=null&&u(n,["metadata"],s),e&&a(e,["embeddingApiType"])==="EMBED_CONTENT"){let o=a(t,["embedding"]),l=a(t,["usageMetadata"]),d=a(t,["truncated"]);if(o){let c={};l&&l.promptTokenCount&&(c.tokenCount=l.promptTokenCount),d&&(c.truncated=d),o.statistics=c,u(n,["embeddings"],[o])}}return n}function kb(t,e){let n={},r=a(t,["endpoint"]);r!=null&&u(n,["name"],r);let i=a(t,["deployedModelId"]);return i!=null&&u(n,["deployedModelId"],i),n}function Nb(t,e){let n={};if(a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let r=a(t,["fileUri"]);r!=null&&u(n,["fileUri"],r);let i=a(t,["mimeType"]);return i!=null&&u(n,["mimeType"],i),n}function Mb(t,e){let n={},r=a(t,["id"]);r!=null&&u(n,["id"],r);let i=a(t,["args"]);i!=null&&u(n,["args"],i);let s=a(t,["name"]);if(s!=null&&u(n,["name"],s),a(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(a(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return n}function Db(t,e){let n={},r=a(t,["allowedFunctionNames"]);r!=null&&u(n,["allowedFunctionNames"],r);let i=a(t,["mode"]);if(i!=null&&u(n,["mode"],i),a(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return n}function Ob(t,e){let n={},r=a(t,["description"]);r!=null&&u(n,["description"],r);let i=a(t,["name"]);i!=null&&u(n,["name"],i);let s=a(t,["parameters"]);s!=null&&u(n,["parameters"],s);let o=a(t,["parametersJsonSchema"]);o!=null&&u(n,["parametersJsonSchema"],o);let l=a(t,["response"]);l!=null&&u(n,["response"],l);let d=a(t,["responseJsonSchema"]);if(d!=null&&u(n,["responseJsonSchema"],d),a(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Ub(t,e,n,r){let i={},s=a(e,["systemInstruction"]);n!==void 0&&s!=null&&u(n,["systemInstruction"],bo(Ne(s)));let o=a(e,["temperature"]);o!=null&&u(i,["temperature"],o);let l=a(e,["topP"]);l!=null&&u(i,["topP"],l);let d=a(e,["topK"]);d!=null&&u(i,["topK"],d);let c=a(e,["candidateCount"]);c!=null&&u(i,["candidateCount"],c);let f=a(e,["maxOutputTokens"]);f!=null&&u(i,["maxOutputTokens"],f);let p=a(e,["stopSequences"]);p!=null&&u(i,["stopSequences"],p);let h=a(e,["responseLogprobs"]);h!=null&&u(i,["responseLogprobs"],h);let m=a(e,["logprobs"]);m!=null&&u(i,["logprobs"],m);let g=a(e,["presencePenalty"]);g!=null&&u(i,["presencePenalty"],g);let _=a(e,["frequencyPenalty"]);_!=null&&u(i,["frequencyPenalty"],_);let y=a(e,["seed"]);y!=null&&u(i,["seed"],y);let T=a(e,["responseMimeType"]);T!=null&&u(i,["responseMimeType"],T);let C=a(e,["responseSchema"]);C!=null&&u(i,["responseSchema"],xp(C));let R=a(e,["responseJsonSchema"]);if(R!=null&&u(i,["responseJsonSchema"],R),a(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(a(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let x=a(e,["safetySettings"]);if(n!==void 0&&x!=null){let fe=x;Array.isArray(fe)&&(fe=fe.map(Ee=>Pk(Ee))),u(n,["safetySettings"],fe)}let G=a(e,["tools"]);if(n!==void 0&&G!=null){let fe=ki(G);Array.isArray(fe)&&(fe=fe.map(Ee=>Ok(bi(Ee)))),u(n,["tools"],fe)}let S=a(e,["toolConfig"]);if(n!==void 0&&S!=null&&u(n,["toolConfig"],Mk(S)),a(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let q=a(e,["cachedContent"]);n!==void 0&&q!=null&&u(n,["cachedContent"],mn(t,q));let $=a(e,["responseModalities"]);$!=null&&u(i,["responseModalities"],$);let N=a(e,["mediaResolution"]);N!=null&&u(i,["mediaResolution"],N);let K=a(e,["speechConfig"]);if(K!=null&&u(i,["speechConfig"],bp(K)),a(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let Q=a(e,["thinkingConfig"]);Q!=null&&u(i,["thinkingConfig"],Q);let oe=a(e,["imageConfig"]);oe!=null&&u(i,["imageConfig"],uk(oe));let ie=a(e,["enableEnhancedCivicAnswers"]);if(ie!=null&&u(i,["enableEnhancedCivicAnswers"],ie),a(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");let ae=a(e,["serviceTier"]);return n!==void 0&&ae!=null&&u(n,["serviceTier"],ae),i}function Lb(t,e,n,r){let i={},s=a(e,["systemInstruction"]);n!==void 0&&s!=null&&u(n,["systemInstruction"],Mi(Ne(s)));let o=a(e,["temperature"]);o!=null&&u(i,["temperature"],o);let l=a(e,["topP"]);l!=null&&u(i,["topP"],l);let d=a(e,["topK"]);d!=null&&u(i,["topK"],d);let c=a(e,["candidateCount"]);c!=null&&u(i,["candidateCount"],c);let f=a(e,["maxOutputTokens"]);f!=null&&u(i,["maxOutputTokens"],f);let p=a(e,["stopSequences"]);p!=null&&u(i,["stopSequences"],p);let h=a(e,["responseLogprobs"]);h!=null&&u(i,["responseLogprobs"],h);let m=a(e,["logprobs"]);m!=null&&u(i,["logprobs"],m);let g=a(e,["presencePenalty"]);g!=null&&u(i,["presencePenalty"],g);let _=a(e,["frequencyPenalty"]);_!=null&&u(i,["frequencyPenalty"],_);let y=a(e,["seed"]);y!=null&&u(i,["seed"],y);let T=a(e,["responseMimeType"]);T!=null&&u(i,["responseMimeType"],T);let C=a(e,["responseSchema"]);C!=null&&u(i,["responseSchema"],xp(C));let R=a(e,["responseJsonSchema"]);R!=null&&u(i,["responseJsonSchema"],R);let x=a(e,["routingConfig"]);x!=null&&u(i,["routingConfig"],x);let G=a(e,["modelSelectionConfig"]);G!=null&&u(i,["modelConfig"],G);let S=a(e,["safetySettings"]);if(n!==void 0&&S!=null){let Se=S;Array.isArray(Se)&&(Se=Se.map(sr=>sr)),u(n,["safetySettings"],Se)}let q=a(e,["tools"]);if(n!==void 0&&q!=null){let Se=ki(q);Array.isArray(Se)&&(Se=Se.map(sr=>IE(bi(sr)))),u(n,["tools"],Se)}let $=a(e,["toolConfig"]);n!==void 0&&$!=null&&u(n,["toolConfig"],Dk($));let N=a(e,["labels"]);n!==void 0&&N!=null&&u(n,["labels"],N);let K=a(e,["cachedContent"]);n!==void 0&&K!=null&&u(n,["cachedContent"],mn(t,K));let Q=a(e,["responseModalities"]);Q!=null&&u(i,["responseModalities"],Q);let oe=a(e,["mediaResolution"]);oe!=null&&u(i,["mediaResolution"],oe);let ie=a(e,["speechConfig"]);ie!=null&&u(i,["speechConfig"],bp(ie));let ae=a(e,["audioTimestamp"]);ae!=null&&u(i,["audioTimestamp"],ae);let fe=a(e,["thinkingConfig"]);fe!=null&&u(i,["thinkingConfig"],fe);let Ee=a(e,["imageConfig"]);if(Ee!=null&&u(i,["imageConfig"],ck(Ee)),a(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let tt=a(e,["modelArmorConfig"]);n!==void 0&&tt!=null&&u(n,["modelArmorConfig"],tt);let nt=a(e,["serviceTier"]);return n!==void 0&&nt!=null&&u(n,["serviceTier"],nt),i}function qA(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let l=Xe(s);Array.isArray(l)&&(l=l.map(d=>bo(d))),u(r,["contents"],l)}let o=a(e,["config"]);return o!=null&&u(r,["generationConfig"],Ub(t,o,r)),r}function BA(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["contents"]);if(s!=null){let l=Xe(s);Array.isArray(l)&&(l=l.map(d=>Mi(d))),u(r,["contents"],l)}let o=a(e,["config"]);return o!=null&&u(r,["generationConfig"],Lb(t,o,r)),r}function $A(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>sb(p))),u(n,["candidates"],f)}let s=a(t,["modelVersion"]);s!=null&&u(n,["modelVersion"],s);let o=a(t,["promptFeedback"]);o!=null&&u(n,["promptFeedback"],o);let l=a(t,["responseId"]);l!=null&&u(n,["responseId"],l);let d=a(t,["usageMetadata"]);d!=null&&u(n,["usageMetadata"],d);let c=a(t,["modelStatus"]);return c!=null&&u(n,["modelStatus"],c),n}function VA(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>p)),u(n,["candidates"],f)}let s=a(t,["createTime"]);s!=null&&u(n,["createTime"],s);let o=a(t,["modelVersion"]);o!=null&&u(n,["modelVersion"],o);let l=a(t,["promptFeedback"]);l!=null&&u(n,["promptFeedback"],l);let d=a(t,["responseId"]);d!=null&&u(n,["responseId"],d);let c=a(t,["usageMetadata"]);return c!=null&&u(n,["usageMetadata"],c),n}function Fb(t,e,n){let r={};if(a(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(a(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");let i=a(t,["numberOfImages"]);e!==void 0&&i!=null&&u(e,["parameters","sampleCount"],i);let s=a(t,["aspectRatio"]);e!==void 0&&s!=null&&u(e,["parameters","aspectRatio"],s);let o=a(t,["guidanceScale"]);if(e!==void 0&&o!=null&&u(e,["parameters","guidanceScale"],o),a(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let l=a(t,["safetyFilterLevel"]);e!==void 0&&l!=null&&u(e,["parameters","safetySetting"],l);let d=a(t,["personGeneration"]);e!==void 0&&d!=null&&u(e,["parameters","personGeneration"],d);let c=a(t,["includeSafetyAttributes"]);e!==void 0&&c!=null&&u(e,["parameters","includeSafetyAttributes"],c);let f=a(t,["includeRaiReason"]);e!==void 0&&f!=null&&u(e,["parameters","includeRaiReason"],f);let p=a(t,["language"]);e!==void 0&&p!=null&&u(e,["parameters","language"],p);let h=a(t,["outputMimeType"]);e!==void 0&&h!=null&&u(e,["parameters","outputOptions","mimeType"],h);let m=a(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&u(e,["parameters","outputOptions","compressionQuality"],m),a(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(a(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let g=a(t,["imageSize"]);if(e!==void 0&&g!=null&&u(e,["parameters","sampleImageSize"],g),a(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return r}function Gb(t,e,n){let r={},i=a(t,["outputGcsUri"]);e!==void 0&&i!=null&&u(e,["parameters","storageUri"],i);let s=a(t,["negativePrompt"]);e!==void 0&&s!=null&&u(e,["parameters","negativePrompt"],s);let o=a(t,["numberOfImages"]);e!==void 0&&o!=null&&u(e,["parameters","sampleCount"],o);let l=a(t,["aspectRatio"]);e!==void 0&&l!=null&&u(e,["parameters","aspectRatio"],l);let d=a(t,["guidanceScale"]);e!==void 0&&d!=null&&u(e,["parameters","guidanceScale"],d);let c=a(t,["seed"]);e!==void 0&&c!=null&&u(e,["parameters","seed"],c);let f=a(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&u(e,["parameters","safetySetting"],f);let p=a(t,["personGeneration"]);e!==void 0&&p!=null&&u(e,["parameters","personGeneration"],p);let h=a(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&u(e,["parameters","includeSafetyAttributes"],h);let m=a(t,["includeRaiReason"]);e!==void 0&&m!=null&&u(e,["parameters","includeRaiReason"],m);let g=a(t,["language"]);e!==void 0&&g!=null&&u(e,["parameters","language"],g);let _=a(t,["outputMimeType"]);e!==void 0&&_!=null&&u(e,["parameters","outputOptions","mimeType"],_);let y=a(t,["outputCompressionQuality"]);e!==void 0&&y!=null&&u(e,["parameters","outputOptions","compressionQuality"],y);let T=a(t,["addWatermark"]);e!==void 0&&T!=null&&u(e,["parameters","addWatermark"],T);let C=a(t,["labels"]);e!==void 0&&C!=null&&u(e,["labels"],C);let R=a(t,["imageSize"]);e!==void 0&&R!=null&&u(e,["parameters","sampleImageSize"],R);let x=a(t,["enhancePrompt"]);return e!==void 0&&x!=null&&u(e,["parameters","enhancePrompt"],x),r}function qb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["prompt"]);s!=null&&u(r,["instances[0]","prompt"],s);let o=a(e,["config"]);return o!=null&&Fb(o,r),r}function Bb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["prompt"]);s!=null&&u(r,["instances[0]","prompt"],s);let o=a(e,["config"]);return o!=null&&Gb(o,r),r}function $b(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(l=>ek(l))),u(n,["generatedImages"],o)}let s=a(t,["positivePromptSafetyAttributes"]);return s!=null&&u(n,["positivePromptSafetyAttributes"],wE(s)),n}function Vb(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(l=>iu(l))),u(n,["generatedImages"],o)}let s=a(t,["positivePromptSafetyAttributes"]);return s!=null&&u(n,["positivePromptSafetyAttributes"],CE(s)),n}function Hb(t,e,n){let r={},i=a(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&u(e,["parameters","sampleCount"],i),a(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(a(t,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");let s=a(t,["durationSeconds"]);if(e!==void 0&&s!=null&&u(e,["parameters","durationSeconds"],s),a(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let o=a(t,["aspectRatio"]);e!==void 0&&o!=null&&u(e,["parameters","aspectRatio"],o);let l=a(t,["resolution"]);e!==void 0&&l!=null&&u(e,["parameters","resolution"],l);let d=a(t,["personGeneration"]);if(e!==void 0&&d!=null&&u(e,["parameters","personGeneration"],d),a(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let c=a(t,["negativePrompt"]);e!==void 0&&c!=null&&u(e,["parameters","negativePrompt"],c);let f=a(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&u(e,["parameters","enhancePrompt"],f),a(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");let p=a(t,["lastFrame"]);e!==void 0&&p!=null&&u(e,["instances[0]","lastFrame"],su(p));let h=a(t,["referenceImages"]);if(e!==void 0&&h!=null){let g=h;Array.isArray(g)&&(g=g.map(_=>zk(_))),u(e,["instances[0]","referenceImages"],g)}if(a(t,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(a(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");if(a(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let m=a(t,["webhookConfig"]);if(e!==void 0&&m!=null&&u(e,["webhookConfig"],m),a(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is not supported in Gemini API.");return r}function Kb(t,e,n){let r={},i=a(t,["numberOfVideos"]);e!==void 0&&i!=null&&u(e,["parameters","sampleCount"],i);let s=a(t,["outputGcsUri"]);e!==void 0&&s!=null&&u(e,["parameters","storageUri"],s);let o=a(t,["fps"]);e!==void 0&&o!=null&&u(e,["parameters","fps"],o);let l=a(t,["durationSeconds"]);e!==void 0&&l!=null&&u(e,["parameters","durationSeconds"],l);let d=a(t,["seed"]);e!==void 0&&d!=null&&u(e,["parameters","seed"],d);let c=a(t,["aspectRatio"]);e!==void 0&&c!=null&&u(e,["parameters","aspectRatio"],c);let f=a(t,["resolution"]);e!==void 0&&f!=null&&u(e,["parameters","resolution"],f);let p=a(t,["personGeneration"]);e!==void 0&&p!=null&&u(e,["parameters","personGeneration"],p);let h=a(t,["pubsubTopic"]);e!==void 0&&h!=null&&u(e,["parameters","pubsubTopic"],h);let m=a(t,["negativePrompt"]);e!==void 0&&m!=null&&u(e,["parameters","negativePrompt"],m);let g=a(t,["enhancePrompt"]);e!==void 0&&g!=null&&u(e,["parameters","enhancePrompt"],g);let _=a(t,["generateAudio"]);e!==void 0&&_!=null&&u(e,["parameters","generateAudio"],_);let y=a(t,["lastFrame"]);e!==void 0&&y!=null&&u(e,["instances[0]","lastFrame"],Ut(y));let T=a(t,["referenceImages"]);if(e!==void 0&&T!=null){let S=T;Array.isArray(S)&&(S=S.map(q=>Yk(q))),u(e,["instances[0]","referenceImages"],S)}let C=a(t,["mask"]);e!==void 0&&C!=null&&u(e,["instances[0]","mask"],Jk(C));let R=a(t,["compressionQuality"]);e!==void 0&&R!=null&&u(e,["parameters","compressionQuality"],R);let x=a(t,["labels"]);if(e!==void 0&&x!=null&&u(e,["labels"],x),a(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let G=a(t,["resizeMode"]);return e!==void 0&&G!=null&&u(e,["parameters","resizeMode"],G),r}function Wb(t,e){let n={},r=a(t,["name"]);r!=null&&u(n,["name"],r);let i=a(t,["metadata"]);i!=null&&u(n,["metadata"],i);let s=a(t,["done"]);s!=null&&u(n,["done"],s);let o=a(t,["error"]);o!=null&&u(n,["error"],o);let l=a(t,["response","generateVideoResponse"]);return l!=null&&u(n,["response"],Xb(l)),n}function Jb(t,e){let n={},r=a(t,["name"]);r!=null&&u(n,["name"],r);let i=a(t,["metadata"]);i!=null&&u(n,["metadata"],i);let s=a(t,["done"]);s!=null&&u(n,["done"],s);let o=a(t,["error"]);o!=null&&u(n,["error"],o);let l=a(t,["response"]);return l!=null&&u(n,["response"],Qb(l)),n}function zb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["prompt"]);s!=null&&u(r,["instances[0]","prompt"],s);let o=a(e,["image"]);o!=null&&u(r,["instances[0]","image"],su(o));let l=a(e,["video"]);l!=null&&u(r,["instances[0]","video"],SE(l));let d=a(e,["source"]);d!=null&&Zb(d,r);let c=a(e,["config"]);return c!=null&&Hb(c,r),r}function Yb(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["prompt"]);s!=null&&u(r,["instances[0]","prompt"],s);let o=a(e,["image"]);o!=null&&u(r,["instances[0]","image"],Ut(o));let l=a(e,["video"]);l!=null&&u(r,["instances[0]","video"],vE(l));let d=a(e,["source"]);d!=null&&jb(d,r);let c=a(e,["config"]);return c!=null&&Kb(c,r),r}function Xb(t,e){let n={},r=a(t,["generatedSamples"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(l=>nk(l))),u(n,["generatedVideos"],o)}let i=a(t,["raiMediaFilteredCount"]);i!=null&&u(n,["raiMediaFilteredCount"],i);let s=a(t,["raiMediaFilteredReasons"]);return s!=null&&u(n,["raiMediaFilteredReasons"],s),n}function Qb(t,e){let n={},r=a(t,["videos"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(l=>rk(l))),u(n,["generatedVideos"],o)}let i=a(t,["raiMediaFilteredCount"]);i!=null&&u(n,["raiMediaFilteredCount"],i);let s=a(t,["raiMediaFilteredReasons"]);return s!=null&&u(n,["raiMediaFilteredReasons"],s),n}function Zb(t,e,n){let r={},i=a(t,["prompt"]);e!==void 0&&i!=null&&u(e,["instances[0]","prompt"],i);let s=a(t,["image"]);e!==void 0&&s!=null&&u(e,["instances[0]","image"],su(s));let o=a(t,["video"]);return e!==void 0&&o!=null&&u(e,["instances[0]","video"],SE(o)),r}function jb(t,e,n){let r={},i=a(t,["prompt"]);e!==void 0&&i!=null&&u(e,["instances[0]","prompt"],i);let s=a(t,["image"]);e!==void 0&&s!=null&&u(e,["instances[0]","image"],Ut(s));let o=a(t,["video"]);return e!==void 0&&o!=null&&u(e,["instances[0]","video"],vE(o)),r}function ek(t,e){let n={},r=a(t,["_self"]);r!=null&&u(n,["image"],dk(r));let i=a(t,["raiFilteredReason"]);i!=null&&u(n,["raiFilteredReason"],i);let s=a(t,["_self"]);return s!=null&&u(n,["safetyAttributes"],wE(s)),n}function iu(t,e){let n={},r=a(t,["_self"]);r!=null&&u(n,["image"],TE(r));let i=a(t,["raiFilteredReason"]);i!=null&&u(n,["raiFilteredReason"],i);let s=a(t,["_self"]);s!=null&&u(n,["safetyAttributes"],CE(s));let o=a(t,["prompt"]);return o!=null&&u(n,["enhancedPrompt"],o),n}function tk(t,e){let n={},r=a(t,["_self"]);r!=null&&u(n,["mask"],TE(r));let i=a(t,["labels"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(n,["labels"],s)}return n}function nk(t,e){let n={},r=a(t,["video"]);return r!=null&&u(n,["video"],Kk(r)),n}function rk(t,e){let n={},r=a(t,["_self"]);return r!=null&&u(n,["video"],Wk(r)),n}function ik(t,e){let n={},r=a(t,["modelSelectionConfig"]);r!=null&&u(n,["modelConfig"],r);let i=a(t,["responseJsonSchema"]);i!=null&&u(n,["responseJsonSchema"],i);let s=a(t,["audioTimestamp"]);s!=null&&u(n,["audioTimestamp"],s);let o=a(t,["candidateCount"]);o!=null&&u(n,["candidateCount"],o);let l=a(t,["enableAffectiveDialog"]);l!=null&&u(n,["enableAffectiveDialog"],l);let d=a(t,["frequencyPenalty"]);d!=null&&u(n,["frequencyPenalty"],d);let c=a(t,["logprobs"]);c!=null&&u(n,["logprobs"],c);let f=a(t,["maxOutputTokens"]);f!=null&&u(n,["maxOutputTokens"],f);let p=a(t,["mediaResolution"]);p!=null&&u(n,["mediaResolution"],p);let h=a(t,["presencePenalty"]);h!=null&&u(n,["presencePenalty"],h);let m=a(t,["responseLogprobs"]);m!=null&&u(n,["responseLogprobs"],m);let g=a(t,["responseMimeType"]);g!=null&&u(n,["responseMimeType"],g);let _=a(t,["responseModalities"]);_!=null&&u(n,["responseModalities"],_);let y=a(t,["responseSchema"]);y!=null&&u(n,["responseSchema"],y);let T=a(t,["routingConfig"]);T!=null&&u(n,["routingConfig"],T);let C=a(t,["seed"]);C!=null&&u(n,["seed"],C);let R=a(t,["speechConfig"]);R!=null&&u(n,["speechConfig"],R);let x=a(t,["stopSequences"]);x!=null&&u(n,["stopSequences"],x);let G=a(t,["temperature"]);G!=null&&u(n,["temperature"],G);let S=a(t,["thinkingConfig"]);S!=null&&u(n,["thinkingConfig"],S);let q=a(t,["topK"]);q!=null&&u(n,["topK"],q);let $=a(t,["topP"]);if($!=null&&u(n,["topP"],$),a(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function sk(t,e,n){let r={},i=a(e,["model"]);return i!=null&&u(r,["_url","name"],de(t,i)),r}function ok(t,e,n){let r={},i=a(e,["model"]);return i!=null&&u(r,["_url","name"],de(t,i)),r}function ak(t,e){let n={},r=a(t,["authConfig"]);r!=null&&u(n,["authConfig"],rb(r));let i=a(t,["enableWidget"]);return i!=null&&u(n,["enableWidget"],i),n}function lk(t,e){let n={},r=a(t,["searchTypes"]);if(r!=null&&u(n,["searchTypes"],r),a(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(a(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");let i=a(t,["timeRangeFilter"]);return i!=null&&u(n,["timeRangeFilter"],i),n}function uk(t,e){let n={},r=a(t,["aspectRatio"]);r!=null&&u(n,["aspectRatio"],r);let i=a(t,["imageSize"]);if(i!=null&&u(n,["imageSize"],i),a(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(a(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is not supported in Gemini API.");if(a(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(a(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(a(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return n}function ck(t,e){let n={},r=a(t,["aspectRatio"]);r!=null&&u(n,["aspectRatio"],r);let i=a(t,["imageSize"]);i!=null&&u(n,["imageSize"],i);let s=a(t,["personGeneration"]);s!=null&&u(n,["personGeneration"],s);let o=a(t,["prominentPeople"]);o!=null&&u(n,["prominentPeople"],o);let l=a(t,["outputMimeType"]);l!=null&&u(n,["imageOutputOptions","mimeType"],l);let d=a(t,["outputCompressionQuality"]);d!=null&&u(n,["imageOutputOptions","compressionQuality"],d);let c=a(t,["imageOutputOptions"]);return c!=null&&u(n,["imageOutputOptions"],c),n}function dk(t,e){let n={},r=a(t,["bytesBase64Encoded"]);r!=null&&u(n,["imageBytes"],Fn(r));let i=a(t,["mimeType"]);return i!=null&&u(n,["mimeType"],i),n}function TE(t,e){let n={},r=a(t,["gcsUri"]);r!=null&&u(n,["gcsUri"],r);let i=a(t,["bytesBase64Encoded"]);i!=null&&u(n,["imageBytes"],Fn(i));let s=a(t,["mimeType"]);return s!=null&&u(n,["mimeType"],s),n}function su(t,e){let n={};if(a(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");let r=a(t,["imageBytes"]);r!=null&&u(n,["bytesBase64Encoded"],Fn(r));let i=a(t,["mimeType"]);return i!=null&&u(n,["mimeType"],i),n}function Ut(t,e){let n={},r=a(t,["gcsUri"]);r!=null&&u(n,["gcsUri"],r);let i=a(t,["imageBytes"]);i!=null&&u(n,["bytesBase64Encoded"],Fn(i));let s=a(t,["mimeType"]);return s!=null&&u(n,["mimeType"],s),n}function fk(t,e,n,r){let i={},s=a(e,["pageSize"]);n!==void 0&&s!=null&&u(n,["_query","pageSize"],s);let o=a(e,["pageToken"]);n!==void 0&&o!=null&&u(n,["_query","pageToken"],o);let l=a(e,["filter"]);n!==void 0&&l!=null&&u(n,["_query","filter"],l);let d=a(e,["queryBase"]);return n!==void 0&&d!=null&&u(n,["_url","models_url"],hE(t,d)),i}function pk(t,e,n,r){let i={},s=a(e,["pageSize"]);n!==void 0&&s!=null&&u(n,["_query","pageSize"],s);let o=a(e,["pageToken"]);n!==void 0&&o!=null&&u(n,["_query","pageToken"],o);let l=a(e,["filter"]);n!==void 0&&l!=null&&u(n,["_query","filter"],l);let d=a(e,["queryBase"]);return n!==void 0&&d!=null&&u(n,["_url","models_url"],hE(t,d)),i}function hk(t,e,n){let r={},i=a(e,["config"]);return i!=null&&fk(t,i,r),r}function mk(t,e,n){let r={},i=a(e,["config"]);return i!=null&&pk(t,i,r),r}function gk(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["nextPageToken"]);i!=null&&u(n,["nextPageToken"],i);let s=a(t,["_self"]);if(s!=null){let o=mE(s);Array.isArray(o)&&(o=o.map(l=>Qf(l))),u(n,["models"],o)}return n}function _k(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["nextPageToken"]);i!=null&&u(n,["nextPageToken"],i);let s=a(t,["_self"]);if(s!=null){let o=mE(s);Array.isArray(o)&&(o=o.map(l=>Zf(l))),u(n,["models"],o)}return n}function yk(t,e){let n={},r=a(t,["maskMode"]);r!=null&&u(n,["maskMode"],r);let i=a(t,["segmentationClasses"]);i!=null&&u(n,["maskClasses"],i);let s=a(t,["maskDilation"]);return s!=null&&u(n,["dilation"],s),n}function Qf(t,e){let n={},r=a(t,["name"]);r!=null&&u(n,["name"],r);let i=a(t,["displayName"]);i!=null&&u(n,["displayName"],i);let s=a(t,["description"]);s!=null&&u(n,["description"],s);let o=a(t,["version"]);o!=null&&u(n,["version"],o);let l=a(t,["_self"]);l!=null&&u(n,["tunedModelInfo"],Uk(l));let d=a(t,["inputTokenLimit"]);d!=null&&u(n,["inputTokenLimit"],d);let c=a(t,["outputTokenLimit"]);c!=null&&u(n,["outputTokenLimit"],c);let f=a(t,["supportedGenerationMethods"]);f!=null&&u(n,["supportedActions"],f);let p=a(t,["temperature"]);p!=null&&u(n,["temperature"],p);let h=a(t,["maxTemperature"]);h!=null&&u(n,["maxTemperature"],h);let m=a(t,["topP"]);m!=null&&u(n,["topP"],m);let g=a(t,["topK"]);g!=null&&u(n,["topK"],g);let _=a(t,["thinking"]);return _!=null&&u(n,["thinking"],_),n}function Zf(t,e){let n={},r=a(t,["name"]);r!=null&&u(n,["name"],r);let i=a(t,["displayName"]);i!=null&&u(n,["displayName"],i);let s=a(t,["description"]);s!=null&&u(n,["description"],s);let o=a(t,["versionId"]);o!=null&&u(n,["version"],o);let l=a(t,["deployedModels"]);if(l!=null){let h=l;Array.isArray(h)&&(h=h.map(m=>kb(m))),u(n,["endpoints"],h)}let d=a(t,["labels"]);d!=null&&u(n,["labels"],d);let c=a(t,["_self"]);c!=null&&u(n,["tunedModelInfo"],Lk(c));let f=a(t,["defaultCheckpointId"]);f!=null&&u(n,["defaultCheckpointId"],f);let p=a(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),u(n,["checkpoints"],h)}return n}function Ak(t,e){let n={},r=a(t,["mediaResolution"]);r!=null&&u(n,["mediaResolution"],r);let i=a(t,["codeExecutionResult"]);i!=null&&u(n,["codeExecutionResult"],i);let s=a(t,["executableCode"]);s!=null&&u(n,["executableCode"],s);let o=a(t,["fileData"]);o!=null&&u(n,["fileData"],Nb(o));let l=a(t,["functionCall"]);l!=null&&u(n,["functionCall"],Mb(l));let d=a(t,["functionResponse"]);d!=null&&u(n,["functionResponse"],d);let c=a(t,["inlineData"]);c!=null&&u(n,["inlineData"],ib(c));let f=a(t,["text"]);f!=null&&u(n,["text"],f);let p=a(t,["thought"]);p!=null&&u(n,["thought"],p);let h=a(t,["thoughtSignature"]);h!=null&&u(n,["thoughtSignature"],h);let m=a(t,["videoMetadata"]);m!=null&&u(n,["videoMetadata"],m);let g=a(t,["toolCall"]);g!=null&&u(n,["toolCall"],g);let _=a(t,["toolResponse"]);_!=null&&u(n,["toolResponse"],_);let y=a(t,["partMetadata"]);return y!=null&&u(n,["partMetadata"],y),n}function Ek(t,e){let n={},r=a(t,["mediaResolution"]);r!=null&&u(n,["mediaResolution"],r);let i=a(t,["codeExecutionResult"]);i!=null&&u(n,["codeExecutionResult"],i);let s=a(t,["executableCode"]);s!=null&&u(n,["executableCode"],s);let o=a(t,["fileData"]);o!=null&&u(n,["fileData"],o);let l=a(t,["functionCall"]);l!=null&&u(n,["functionCall"],l);let d=a(t,["functionResponse"]);d!=null&&u(n,["functionResponse"],d);let c=a(t,["inlineData"]);c!=null&&u(n,["inlineData"],c);let f=a(t,["text"]);f!=null&&u(n,["text"],f);let p=a(t,["thought"]);p!=null&&u(n,["thought"],p);let h=a(t,["thoughtSignature"]);h!=null&&u(n,["thoughtSignature"],h);let m=a(t,["videoMetadata"]);if(m!=null&&u(n,["videoMetadata"],m),a(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(a(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Tk(t,e){let n={},r=a(t,["productImage"]);return r!=null&&u(n,["image"],Ut(r)),n}function wk(t,e,n){let r={},i=a(t,["numberOfImages"]);e!==void 0&&i!=null&&u(e,["parameters","sampleCount"],i);let s=a(t,["baseSteps"]);e!==void 0&&s!=null&&u(e,["parameters","baseSteps"],s);let o=a(t,["outputGcsUri"]);e!==void 0&&o!=null&&u(e,["parameters","storageUri"],o);let l=a(t,["seed"]);e!==void 0&&l!=null&&u(e,["parameters","seed"],l);let d=a(t,["safetyFilterLevel"]);e!==void 0&&d!=null&&u(e,["parameters","safetySetting"],d);let c=a(t,["personGeneration"]);e!==void 0&&c!=null&&u(e,["parameters","personGeneration"],c);let f=a(t,["addWatermark"]);e!==void 0&&f!=null&&u(e,["parameters","addWatermark"],f);let p=a(t,["outputMimeType"]);e!==void 0&&p!=null&&u(e,["parameters","outputOptions","mimeType"],p);let h=a(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&u(e,["parameters","outputOptions","compressionQuality"],h);let m=a(t,["enhancePrompt"]);e!==void 0&&m!=null&&u(e,["parameters","enhancePrompt"],m);let g=a(t,["labels"]);return e!==void 0&&g!=null&&u(e,["labels"],g),r}function Ck(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["source"]);s!=null&&Sk(s,r);let o=a(e,["config"]);return o!=null&&wk(o,r),r}function Ik(t,e){let n={},r=a(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>iu(s))),u(n,["generatedImages"],i)}return n}function Sk(t,e,n){let r={},i=a(t,["prompt"]);e!==void 0&&i!=null&&u(e,["instances[0]","prompt"],i);let s=a(t,["personImage"]);e!==void 0&&s!=null&&u(e,["instances[0]","personImage","image"],Ut(s));let o=a(t,["productImages"]);if(e!==void 0&&o!=null){let l=o;Array.isArray(l)&&(l=l.map(d=>Tk(d))),u(e,["instances[0]","productImages"],l)}return r}function vk(t,e){let n={},r=a(t,["referenceImage"]);r!=null&&u(n,["referenceImage"],Ut(r));let i=a(t,["referenceId"]);i!=null&&u(n,["referenceId"],i);let s=a(t,["referenceType"]);s!=null&&u(n,["referenceType"],s);let o=a(t,["maskImageConfig"]);o!=null&&u(n,["maskImageConfig"],yk(o));let l=a(t,["controlImageConfig"]);l!=null&&u(n,["controlImageConfig"],db(l));let d=a(t,["styleImageConfig"]);d!=null&&u(n,["styleImageConfig"],d);let c=a(t,["subjectImageConfig"]);return c!=null&&u(n,["subjectImageConfig"],c),n}function wE(t,e){let n={},r=a(t,["safetyAttributes","categories"]);r!=null&&u(n,["categories"],r);let i=a(t,["safetyAttributes","scores"]);i!=null&&u(n,["scores"],i);let s=a(t,["contentType"]);return s!=null&&u(n,["contentType"],s),n}function CE(t,e){let n={},r=a(t,["safetyAttributes","categories"]);r!=null&&u(n,["categories"],r);let i=a(t,["safetyAttributes","scores"]);i!=null&&u(n,["scores"],i);let s=a(t,["contentType"]);return s!=null&&u(n,["contentType"],s),n}function Pk(t,e){let n={},r=a(t,["category"]);if(r!=null&&u(n,["category"],r),a(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let i=a(t,["threshold"]);return i!=null&&u(n,["threshold"],i),n}function Rk(t,e){let n={},r=a(t,["image"]);return r!=null&&u(n,["image"],Ut(r)),n}function xk(t,e,n){let r={},i=a(t,["mode"]);e!==void 0&&i!=null&&u(e,["parameters","mode"],i);let s=a(t,["maxPredictions"]);e!==void 0&&s!=null&&u(e,["parameters","maxPredictions"],s);let o=a(t,["confidenceThreshold"]);e!==void 0&&o!=null&&u(e,["parameters","confidenceThreshold"],o);let l=a(t,["maskDilation"]);e!==void 0&&l!=null&&u(e,["parameters","maskDilation"],l);let d=a(t,["binaryColorThreshold"]);e!==void 0&&d!=null&&u(e,["parameters","binaryColorThreshold"],d);let c=a(t,["labels"]);return e!==void 0&&c!=null&&u(e,["labels"],c),r}function bk(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["source"]);s!=null&&Nk(s,r);let o=a(e,["config"]);return o!=null&&xk(o,r),r}function kk(t,e){let n={},r=a(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>tk(s))),u(n,["generatedMasks"],i)}return n}function Nk(t,e,n){let r={},i=a(t,["prompt"]);e!==void 0&&i!=null&&u(e,["instances[0]","prompt"],i);let s=a(t,["image"]);e!==void 0&&s!=null&&u(e,["instances[0]","image"],Ut(s));let o=a(t,["scribbleImage"]);return e!==void 0&&o!=null&&u(e,["instances[0]","scribble"],Rk(o)),r}function Mk(t,e){let n={},r=a(t,["retrievalConfig"]);r!=null&&u(n,["retrievalConfig"],r);let i=a(t,["functionCallingConfig"]);i!=null&&u(n,["functionCallingConfig"],Db(i));let s=a(t,["includeServerSideToolInvocations"]);return s!=null&&u(n,["includeServerSideToolInvocations"],s),n}function Dk(t,e){let n={},r=a(t,["retrievalConfig"]);r!=null&&u(n,["retrievalConfig"],r);let i=a(t,["functionCallingConfig"]);if(i!=null&&u(n,["functionCallingConfig"],i),a(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Ok(t,e){let n={};if(a(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let r=a(t,["computerUse"]);r!=null&&u(n,["computerUse"],r);let i=a(t,["fileSearch"]);i!=null&&u(n,["fileSearch"],i);let s=a(t,["googleSearch"]);s!=null&&u(n,["googleSearch"],lk(s));let o=a(t,["googleMaps"]);o!=null&&u(n,["googleMaps"],ak(o));let l=a(t,["codeExecution"]);if(l!=null&&u(n,["codeExecution"],l),a(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let d=a(t,["functionDeclarations"]);if(d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>m)),u(n,["functionDeclarations"],h)}let c=a(t,["googleSearchRetrieval"]);if(c!=null&&u(n,["googleSearchRetrieval"],c),a(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");let f=a(t,["urlContext"]);f!=null&&u(n,["urlContext"],f);let p=a(t,["mcpServers"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),u(n,["mcpServers"],h)}return n}function IE(t,e){let n={},r=a(t,["retrieval"]);r!=null&&u(n,["retrieval"],r);let i=a(t,["computerUse"]);if(i!=null&&u(n,["computerUse"],i),a(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let s=a(t,["googleSearch"]);s!=null&&u(n,["googleSearch"],s);let o=a(t,["googleMaps"]);o!=null&&u(n,["googleMaps"],o);let l=a(t,["codeExecution"]);l!=null&&u(n,["codeExecution"],l);let d=a(t,["enterpriseWebSearch"]);d!=null&&u(n,["enterpriseWebSearch"],d);let c=a(t,["functionDeclarations"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(g=>Ob(g))),u(n,["functionDeclarations"],m)}let f=a(t,["googleSearchRetrieval"]);f!=null&&u(n,["googleSearchRetrieval"],f);let p=a(t,["parallelAiSearch"]);p!=null&&u(n,["parallelAiSearch"],p);let h=a(t,["urlContext"]);if(h!=null&&u(n,["urlContext"],h),a(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Uk(t,e){let n={},r=a(t,["baseModel"]);r!=null&&u(n,["baseModel"],r);let i=a(t,["createTime"]);i!=null&&u(n,["createTime"],i);let s=a(t,["updateTime"]);return s!=null&&u(n,["updateTime"],s),n}function Lk(t,e){let n={},r=a(t,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&u(n,["baseModel"],r);let i=a(t,["createTime"]);i!=null&&u(n,["createTime"],i);let s=a(t,["updateTime"]);return s!=null&&u(n,["updateTime"],s),n}function Fk(t,e,n){let r={},i=a(t,["displayName"]);e!==void 0&&i!=null&&u(e,["displayName"],i);let s=a(t,["description"]);e!==void 0&&s!=null&&u(e,["description"],s);let o=a(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&u(e,["defaultCheckpointId"],o),r}function Gk(t,e,n){let r={},i=a(t,["displayName"]);e!==void 0&&i!=null&&u(e,["displayName"],i);let s=a(t,["description"]);e!==void 0&&s!=null&&u(e,["description"],s);let o=a(t,["defaultCheckpointId"]);return e!==void 0&&o!=null&&u(e,["defaultCheckpointId"],o),r}function qk(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","name"],de(t,i));let s=a(e,["config"]);return s!=null&&Fk(s,r),r}function Bk(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["config"]);return s!=null&&Gk(s,r),r}function $k(t,e,n){let r={},i=a(t,["outputGcsUri"]);e!==void 0&&i!=null&&u(e,["parameters","storageUri"],i);let s=a(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&u(e,["parameters","safetySetting"],s);let o=a(t,["personGeneration"]);e!==void 0&&o!=null&&u(e,["parameters","personGeneration"],o);let l=a(t,["includeRaiReason"]);e!==void 0&&l!=null&&u(e,["parameters","includeRaiReason"],l);let d=a(t,["outputMimeType"]);e!==void 0&&d!=null&&u(e,["parameters","outputOptions","mimeType"],d);let c=a(t,["outputCompressionQuality"]);e!==void 0&&c!=null&&u(e,["parameters","outputOptions","compressionQuality"],c);let f=a(t,["enhanceInputImage"]);e!==void 0&&f!=null&&u(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=a(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&u(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=a(t,["labels"]);e!==void 0&&h!=null&&u(e,["labels"],h);let m=a(t,["numberOfImages"]);e!==void 0&&m!=null&&u(e,["parameters","sampleCount"],m);let g=a(t,["mode"]);return e!==void 0&&g!=null&&u(e,["parameters","mode"],g),r}function Vk(t,e,n){let r={},i=a(e,["model"]);i!=null&&u(r,["_url","model"],de(t,i));let s=a(e,["image"]);s!=null&&u(r,["instances[0]","image"],Ut(s));let o=a(e,["upscaleFactor"]);o!=null&&u(r,["parameters","upscaleConfig","upscaleFactor"],o);let l=a(e,["config"]);return l!=null&&$k(l,r),r}function Hk(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>iu(o))),u(n,["generatedImages"],s)}return n}function Kk(t,e){let n={},r=a(t,["uri"]);r!=null&&u(n,["uri"],r);let i=a(t,["encodedVideo"]);i!=null&&u(n,["videoBytes"],Fn(i));let s=a(t,["encoding"]);return s!=null&&u(n,["mimeType"],s),n}function Wk(t,e){let n={},r=a(t,["gcsUri"]);r!=null&&u(n,["uri"],r);let i=a(t,["bytesBase64Encoded"]);i!=null&&u(n,["videoBytes"],Fn(i));let s=a(t,["mimeType"]);return s!=null&&u(n,["mimeType"],s),n}function Jk(t,e){let n={},r=a(t,["image"]);r!=null&&u(n,["_self"],Ut(r));let i=a(t,["maskMode"]);return i!=null&&u(n,["maskMode"],i),n}function zk(t,e){let n={},r=a(t,["image"]);r!=null&&u(n,["image"],su(r));let i=a(t,["referenceType"]);return i!=null&&u(n,["referenceType"],i),n}function Yk(t,e){let n={},r=a(t,["image"]);r!=null&&u(n,["image"],Ut(r));let i=a(t,["referenceType"]);return i!=null&&u(n,["referenceType"],i),n}function SE(t,e){let n={},r=a(t,["uri"]);r!=null&&u(n,["uri"],r);let i=a(t,["videoBytes"]);i!=null&&u(n,["encodedVideo"],Fn(i));let s=a(t,["mimeType"]);return s!=null&&u(n,["encoding"],s),n}function vE(t,e){let n={},r=a(t,["uri"]);r!=null&&u(n,["gcsUri"],r);let i=a(t,["videoBytes"]);i!=null&&u(n,["bytesBase64Encoded"],Fn(i));let s=a(t,["mimeType"]);return s!=null&&u(n,["mimeType"],s),n}function Xk(t,e,n){let r={},i=a(e,["displayName"]);n!==void 0&&i!=null&&u(n,["displayName"],i);let s=a(e,["embeddingModel"]);return n!==void 0&&s!=null&&u(n,["embeddingModel"],de(t,s)),r}function Qk(t,e){let n={},r=a(e,["config"]);return r!=null&&Xk(t,r,n),n}function Zk(t,e){let n={},r=a(t,["force"]);return e!==void 0&&r!=null&&u(e,["_query","force"],r),n}function jk(t){let e={},n=a(t,["name"]);n!=null&&u(e,["_url","name"],n);let r=a(t,["config"]);return r!=null&&Zk(r,e),e}function eN(t){let e={},n=a(t,["name"]);return n!=null&&u(e,["_url","name"],n),e}function tN(t,e){let n={},r=a(t,["customMetadata"]);if(e!==void 0&&r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["customMetadata"],s)}let i=a(t,["chunkingConfig"]);return e!==void 0&&i!=null&&u(e,["chunkingConfig"],i),n}function nN(t){let e={},n=a(t,["name"]);n!=null&&u(e,["name"],n);let r=a(t,["metadata"]);r!=null&&u(e,["metadata"],r);let i=a(t,["done"]);i!=null&&u(e,["done"],i);let s=a(t,["error"]);s!=null&&u(e,["error"],s);let o=a(t,["response"]);return o!=null&&u(e,["response"],iN(o)),e}function rN(t){let e={},n=a(t,["fileSearchStoreName"]);n!=null&&u(e,["_url","file_search_store_name"],n);let r=a(t,["fileName"]);r!=null&&u(e,["fileName"],r);let i=a(t,["config"]);return i!=null&&tN(i,e),e}function iN(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["parent"]);r!=null&&u(e,["parent"],r);let i=a(t,["documentName"]);return i!=null&&u(e,["documentName"],i),e}function sN(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);return e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),n}function oN(t){let e={},n=a(t,["config"]);return n!=null&&sN(n,e),e}function aN(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["fileSearchStores"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["fileSearchStores"],s)}return e}function PE(t,e){let n={},r=a(t,["mimeType"]);e!==void 0&&r!=null&&u(e,["mimeType"],r);let i=a(t,["displayName"]);e!==void 0&&i!=null&&u(e,["displayName"],i);let s=a(t,["customMetadata"]);if(e!==void 0&&s!=null){let l=s;Array.isArray(l)&&(l=l.map(d=>d)),u(e,["customMetadata"],l)}let o=a(t,["chunkingConfig"]);return e!==void 0&&o!=null&&u(e,["chunkingConfig"],o),n}function lN(t){let e={},n=a(t,["fileSearchStoreName"]);n!=null&&u(e,["_url","file_search_store_name"],n);let r=a(t,["config"]);return r!=null&&PE(r,e),e}function uN(t){let e={},n=a(t,["sdkHttpResponse"]);return n!=null&&u(e,["sdkHttpResponse"],n),e}var cN="Content-Type",dN="X-Server-Timeout",fN="User-Agent",jf="x-goog-api-client",pN="1.52.0",hN=`google-genai-sdk/${pN}`,mN="v1beta1",gN="v1beta",_N=new Set(["us","eu"]),yN=5,AN=[408,429,500,502,503,504],ep=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,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));let s={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let l=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!l?(s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location==="global"?s.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&_N.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:mN}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:gN,s.baseUrl="https://generativelanguage.googleapis.com/";s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let 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===Pf.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,r);if(e.queryParams)for(let[o,l]of Object.entries(e.queryParams))i.searchParams.append(o,String(l));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(),e.abortSignal),this.unaryApiCall(i,s,e.httpMethod)}patchHttpOptions(e,n){let r=JSON.parse(JSON.stringify(e));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(),e.abortSignal),this.streamApiCall(i,s,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,r,i){if(n&&n.timeout||i){let s=new AbortController,o=s.signal;if(n.timeout&&n?.timeout>0){let l=setTimeout(()=>s.abort(),n.timeout);l&&typeof l.unref=="function"&&l.unref()}i&&i.addEventListener("abort",()=>{s.abort()}),e.signal=o}return n&&n.extraBody!==null&&EN(e,n.extraBody),e.headers=await this.getHeadersInternal(n,r),e}async unaryApiCall(e,n,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r})).then(async i=>(await HA(i),new Ln(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}async streamApiCall(e,n,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r})).then(async i=>(await HA(i),this.processStreamResponse(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}processStreamResponse(e){return Mt(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="",l="data:",d=[`
39
+
40
+ `,"\r\r",`\r
41
+ \r
42
+ `];for(;;){let{done:c,value:f}=yield se(i.read());if(c){if(o.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=s.decode(f,{stream:!0});try{let g=JSON.parse(p);if("error"in g){let _=JSON.parse(JSON.stringify(g.error)),y=_.status,T=_.code,C=`got status: ${y}. ${JSON.stringify(g)}`;if(T>=400&&T<600)throw new ql({message:C,status:T})}}catch(g){if(g.name==="ApiError")throw g}o+=p;let h=-1,m=0;for(;;){h=-1,m=0;for(let y of d){let T=o.indexOf(y);T!==-1&&(h===-1||T<h)&&(h=T,m=y.length)}if(h===-1)break;let g=o.substring(0,h);o=o.substring(h+m);let _=g.trim();if(_.startsWith(l)){let y=_.substring(l.length).trim();try{let T=new Response(y,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield se(new Ln(T))}catch(T){throw new Error(`exception parsing stream chunk ${y}. ${T}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n){var r;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,n);let i=this.clientOptions.httpOptions.retryOptions;return(0,nu.default)(async()=>{let o=await fetch(e,n);if(o.ok)return o;throw AN.includes(o.status)?new Error(`Retryable HTTP Error: ${o.statusText}`):new nu.AbortError(`Non-retryable exception ${o.statusText} sending request`)},{retries:((r=i.attempts)!==null&&r!==void 0?r:yN)-1})}getDefaultHeaders(){let e={},n=hN+" "+this.clientOptions.userAgentExtra;return e[fN]=n,e[jf]=n,e[cN]="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);e.timeout&&e.timeout>0&&r.append(dN,String(Math.ceil(e.timeout/1e3)))}return 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 l=(r=n?.mimeType)!==null&&r!==void 0?r:o.type;if(l===void 0||l==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=l;let d={file:i},c=this.getFileName(e),f=z("upload/v1beta/files",d._url),p=await this.fetchUploadUrl(f,i.sizeBytes,i.mimeType,c,d,n?.httpOptions);return s.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,r){var i;let s=this.clientOptions.uploader,o=await s.stat(n),l=String(o.size),d=(i=r?.mimeType)!==null&&i!==void 0?i:o.type;if(d===void 0||d==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let c=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};r!=null&&PE(r,p);let h=await this.fetchUploadUrl(c,l,d,f,p,r?.httpOptions);return s.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,r,i,s,o){var l;let d={};o?d=o:d={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`},i?{"X-Goog-Upload-File-Name":i}:{})};let c=await this.request({path:e,body:JSON.stringify(s),httpMethod:"POST",httpOptions:d});if(!c||!c?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(l=c?.headers)===null||l===void 0?void 0:l["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};async function HA(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 ql({message:i,status:n}):new Error(i)}}function EN(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 l=Object.assign({},s);for(let d in o)if(Object.prototype.hasOwnProperty.call(o,d)){let c=o[d],f=l[d];c&&typeof c=="object"&&!Array.isArray(c)&&f&&typeof f=="object"&&!Array.isArray(f)?l[d]=r(f,c):(f&&c&&typeof f!=typeof c&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${d}". Original type: ${typeof f}, New type: ${typeof c}. Overwriting.`),l[d]=c)}return l}let i=r(n,e);t.body=JSON.stringify(i)}var TN="mcp_used/unknown",wN=!1;function RE(t){for(let e of t)if(CN(e)||typeof e=="object"&&"inputSchema"in e)return!0;return wN}function xE(t){var e;let n=(e=t[jf])!==null&&e!==void 0?e:"";t[jf]=(n+` ${TN}`).trimStart()}function CN(t){return t!==null&&typeof t=="object"&&t instanceof tp}function IN(t){return Mt(this,arguments,function*(n,r=100){let i,s=0;for(;s<r;){let o=yield se(n.listTools({cursor:i}));for(let l of o.tools)yield yield se(l),s++;if(!o.nextCursor)break;i=o.nextCursor}})}var tp=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 f of this.mcpClients)try{for(var l=!0,d=(n=void 0,Dt(IN(f))),c;c=await d.next(),e=c.done,!e;l=!0){i=c.value,l=!1;let p=i;o.push(p);let h=p.name;if(s[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);s[h]=f}}catch(p){n={error:p}}finally{try{!l&&!e&&(r=d.return)&&await r.call(d)}finally{if(n)throw n.error}}this.mcpTools=o,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),$0(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}};async function SN(t,e,n){let r=new Vf,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(r,i),e(r)}var np=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=PN(this.apiClient.getDefaultHeaders()),l=this.apiClient.getApiKey(),d=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${l}`,c=()=>{},f=new Promise(R=>{c=R}),p=e.callbacks,h=function(){c({})},m=this.apiClient,g={onopen:h,onmessage:R=>{SN(m,p.onmessage,R)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(R){},onclose:(r=p?.onclose)!==null&&r!==void 0?r:function(R){}},_=this.webSocketFactory.create(d,vN(o),g);_.connect(),await f;let C={setup:{model:de(this.apiClient,e.model)}};return _.send(JSON.stringify(C)),new rp(_,this.apiClient)}},rp=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=Kx(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=Hx(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(Si.PLAY)}pause(){this.sendPlaybackControl(Si.PAUSE)}stop(){this.sendPlaybackControl(Si.STOP)}resetContext(){this.sendPlaybackControl(Si.RESET_CONTEXT)}close(){this.conn.close()}};function vN(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function PN(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var RN="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function xN(t,e,n){let r=new $f,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=zx(s);Object.assign(r,o)}else Object.assign(r,s);e(r)}var ip=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r,this.music=new np(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,r,i,s,o,l;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 d=this.apiClient.getWebsocketBaseUrl(),c=this.apiClient.getApiVersion(),f,p=this.apiClient.getHeaders();e.config&&e.config.tools&&RE(e.config.tools)&&xE(p);let h=NN(p);if(this.apiClient.isVertexAI()){let N=this.apiClient.getProject(),K=this.apiClient.getLocation(),Q=this.apiClient.getApiKey(),oe=!!N&&!!K||!!Q;this.apiClient.getCustomBaseUrl()&&!oe?f=d:(f=`${d}/ws/google.cloud.aiplatform.${c}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{let N=this.apiClient.getApiKey(),K="BidiGenerateContent",Q="key";N?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),c!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),K="BidiGenerateContentConstrained",Q="access_token"),f=`${d}/ws/google.ai.generativelanguage.${c}.GenerativeService.${K}?${Q}=${N}`}let m=()=>{},g=new Promise(N=>{m=N}),_=e.callbacks,y=function(){var N;(N=_?.onopen)===null||N===void 0||N.call(_),m({})},T=this.apiClient,C={onopen:y,onmessage:N=>{xN(T,_.onmessage,N)},onerror:(n=_?.onerror)!==null&&n!==void 0?n:function(N){},onclose:(r=_?.onclose)!==null&&r!==void 0?r:function(N){}},R=this.webSocketFactory.create(f,kN(h),C);R.connect(),await g;let x=de(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&x.startsWith("publishers/")){let N=this.apiClient.getProject(),K=this.apiClient.getLocation();N&&K&&(x=`projects/${N}/locations/${K}/`+x)}let G={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[vl.AUDIO]}:e.config.responseModalities=[vl.AUDIO]),!((s=e.config)===null||s===void 0)&&s.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let S=(l=(o=e.config)===null||o===void 0?void 0:o.tools)!==null&&l!==void 0?l:[],q=[];for(let N of S)if(this.isCallableTool(N)){let K=N;q.push(await K.tool())}else q.push(N);q.length>0&&(e.config.tools=q);let $={model:x,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?G=Vx(this.apiClient,$):G=$x(this.apiClient,$),delete G.config,R.send(JSON.stringify(G)),new sp(R,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},bN={turnComplete:!0},sp=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=Xe(n.turns),e.isVertexAI()||(r=r.map(i=>bo(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(RN)}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},bN),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:Jx(e)}:n={realtimeInput:Wx(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function kN(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function NN(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var KA=10;function WA(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(Pi(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 Pi(t){return"callTool"in t&&typeof t.callTool=="function"}function MN(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=>Pi(i)))!==null&&r!==void 0?r:!1}function JA(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((r,i)=>{if(Pi(r))return;let s=r;s.functionDeclarations&&s.functionDeclarations.length>0&&n.push(i)}),n}function zA(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}var op=class extends Ot{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Xe(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=Xe(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:Pl.EMBED_CONTENT});return await this.embedContentInternal(s)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:Pl.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var r,i,s,o,l;let d=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!MN(n)||WA(n.config))return await this.generateContentInternal(d);let c=JA(n);if(c.length>0){let _=c.map(y=>`tools[${y}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${_}.`)}let f,p,h=Xe(d.contents),m=(s=(i=(r=d.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&s!==void 0?s:KA,g=0;for(;g<m&&(f=await this.generateContentInternal(d),!(!f.functionCalls||f.functionCalls.length===0));){let _=f.candidates[0].content,y=[];for(let T of(l=(o=n.config)===null||o===void 0?void 0:o.tools)!==null&&l!==void 0?l:[])if(Pi(T)){let R=await T.callTool(f.functionCalls);y.push(...R)}g++,p={role:"user",parts:y},d.contents=Xe(d.contents),d.contents.push(_),d.contents.push(p),zA(d.config)&&(h.push(_),h.push(p))}return zA(d.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var r,i,s,o,l;if(this.maybeMoveToResponseJsonSchem(n),WA(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}let d=JA(n);if(d.length>0){let p=d.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let c=(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,f=(l=(o=n?.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||l===void 0?void 0:l.disable;if(c&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(r=>{var i;let s,o=[];if(r?.generatedImages)for(let d of r.generatedImages)d&&d?.safetyAttributes&&((i=d?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?s=d?.safetyAttributes:o.push(d);let l;return s?l={generatedImages:o,positivePromptSafetyAttributes:s,sdkHttpResponse:r.sdkHttpResponse}:l={generatedImages:o,sdkHttpResponse:r.sdkHttpResponse},l}),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 for Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported");o.config.filter="labels.tune-type:*"}return new hn(pn.PAGED_ITEM_MODELS,l=>this.listInternal(l),await this.listInternal(o),o)},this.editImage=async n=>{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,l,d;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((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&&(!((d=(l=n.source)===null||l===void 0?void 0:l.video)===null||d===void 0)&&d.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,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 d=>Pi(d)?await d.tool():d)),l={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:o})};if(l.config.tools=o,e.config&&e.config.tools&&RE(e.config.tools)){let d=(i=(r=e.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&i!==void 0?i:{},c=Object.assign({},d);Object.keys(c).length===0&&(c=this.apiClient.getDefaultHeaders()),xE(c),l.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:c})}return l}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(Pi(o)){let l=o,d=await l.tool();for(let c of(i=d.functionDeclarations)!==null&&i!==void 0?i:[]){if(!c.name)throw new Error("Function declaration name is required.");if(s.has(c.name))throw new Error(`Duplicate tool declaration name: ${c.name}`);s.set(c.name,l)}}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:KA,o=!1,l=0,d=await this.initAfcToolsMap(e);return(function(c,f,p){return Mt(this,arguments,function*(){for(var h,m,g,_,y,T;l<s;){o&&(l++,o=!1);let G=yield se(c.processParamsMaybeAddMcpUsage(p)),S=yield se(c.generateContentStreamInternal(G)),q=[],$=[];try{for(var C=!0,R=(m=void 0,Dt(S)),x;x=yield se(R.next()),h=x.done,!h;C=!0){_=x.value,C=!1;let N=_;if(yield yield se(N),N.candidates&&(!((y=N.candidates[0])===null||y===void 0)&&y.content)){$.push(N.candidates[0].content);for(let K of(T=N.candidates[0].content.parts)!==null&&T!==void 0?T:[])if(l<s&&K.functionCall){if(!K.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(K.functionCall.name)){let Q=yield se(f.get(K.functionCall.name).callTool([K.functionCall]));q.push(...Q)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, mising tool: ${K.functionCall.name}`)}}}}catch(N){m={error:N}}finally{try{!C&&!h&&(g=R.return)&&(yield se(g.call(R)))}finally{if(m)throw m.error}}if(q.length>0){o=!0;let N=new Ar;N.candidates=[{content:{role:"user",parts:q}}],yield yield se(N);let K=[];K.push(...$),K.push({role:"user",parts:q});let Q=Xe(p.contents).concat(K);p.contents=Q}else break}})})(this,d,e)}async generateContentInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=BA(this.apiClient,e);return l=z("{model}:generateContent",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=VA(f),h=new Ar;return Object.assign(h,p),h})}else{let c=qA(this.apiClient,e);return l=z("{model}:generateContent",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=$A(f),h=new Ar;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=BA(this.apiClient,e);return l=z("{model}:streamGenerateContent?alt=sse",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.requestStream({path:l,queryParams:d,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}),o.then(function(p){return Mt(this,arguments,function*(){var h,m,g,_;try{for(var y=!0,T=Dt(p),C;C=yield se(T.next()),h=C.done,!h;y=!0){_=C.value,y=!1;let R=_,x=VA(yield se(R.json()),e);x.sdkHttpResponse={headers:R.headers};let G=new Ar;Object.assign(G,x),yield yield se(G)}}catch(R){m={error:R}}finally{try{!y&&!h&&(g=T.return)&&(yield se(g.call(T)))}finally{if(m)throw m.error}}})})}else{let c=qA(this.apiClient,e);return l=z("{model}:streamGenerateContent?alt=sse",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.requestStream({path:l,queryParams:d,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}),o.then(function(p){return Mt(this,arguments,function*(){var h,m,g,_;try{for(var y=!0,T=Dt(p),C;C=yield se(T.next()),h=C.done,!h;y=!0){_=C.value,y=!1;let R=_,x=$A(yield se(R.json()),e);x.sdkHttpResponse={headers:R.headers};let G=new Ar;Object.assign(G,x),yield yield se(G)}}catch(R){m={error:R}}finally{try{!y&&!h&&(g=T.return)&&(yield se(g.call(T)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=Rb(this.apiClient,e,e),f=H0(e.model)?"{model}:embedContent":"{model}:predict";return l=z(f,c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(p=>p.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:p.headers},m})),o.then(p=>{let h=bb(p,e),m=new Rl;return Object.assign(m,h),m})}else{let c=Pb(this.apiClient,e);return l=z("{model}:batchEmbedContents",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=xb(f),h=new Rl;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=Bb(this.apiClient,e);return l=z("{model}:predict",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=Vb(f),h=new xl;return Object.assign(h,p),h})}else{let c=qb(this.apiClient,e);return l=z("{model}:predict",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=$b(f),h=new xl;return Object.assign(h,p),h})}}async editImageInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=Cb(this.apiClient,e);return s=z("{model}:predict",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=Ib(d),f=new Rf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=Vk(this.apiClient,e);return s=z("{model}:predict",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=Hk(d),f=new xf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=Ck(this.apiClient,e);return s=z("{model}:predict",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=Ik(d),f=new bf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=bk(this.apiClient,e);return s=z("{model}:predict",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=kk(d),f=new kf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=ok(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o.then(f=>Zf(f))}else{let c=sk(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o.then(f=>Qf(f))}}async listInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=mk(this.apiClient,e);return l=z("{models_url}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=_k(f),h=new bl;return Object.assign(h,p),h})}else{let c=hk(this.apiClient,e);return l=z("{models_url}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=gk(f),h=new bl;return Object.assign(h,p),h})}}async update(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=Bk(this.apiClient,e);return l=z("{model}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o.then(f=>Zf(f))}else{let c=qk(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o.then(f=>Qf(f))}}async delete(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=Ab(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=Tb(f),h=new kl;return Object.assign(h,p),h})}else{let c=yb(this.apiClient,e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=Eb(f),h=new kl;return Object.assign(h,p),h})}}async countTokens(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=mb(this.apiClient,e);return l=z("{model}:countTokens",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=_b(f),h=new Nl;return Object.assign(h,p),h})}else{let c=hb(this.apiClient,e);return l=z("{model}:countTokens",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=gb(f),h=new Nl;return Object.assign(h,p),h})}}async computeTokens(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=ab(this.apiClient,e);return s=z("{model}:computeTokens",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=lb(d),f=new Nf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=Yb(this.apiClient,e);return l=z("{model}:predictLongRunning",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json()),o.then(f=>{let p=Jb(f),h=new Ml;return Object.assign(h,p),h})}else{let c=zb(this.apiClient,e);return l=z("{model}:predictLongRunning",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json()),o.then(f=>{let p=Wb(f),h=new Ml;return Object.assign(h,p),h})}}};var ap=class extends Ot{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,l="",d={};if(this.apiClient.isVertexAI()){let c=k0(e);return l=z("{operationName}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),o}else{let c=b0(e);return l=z("{operationName}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json()),o}}async fetchPredictVideosOperationInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=C0(e);return s=z("{resourceName}:fetchPredictOperation",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function YA(t){let e={};if(a(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is not supported in Gemini API.");return e}function DN(t){let e={},n=a(t,["apiKey"]);if(n!=null&&u(e,["apiKey"],n),a(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(a(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(a(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(a(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(a(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(a(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function ON(t){let e={},n=a(t,["data"]);if(n!=null&&u(e,["data"],n),a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function UN(t){let e={},n=a(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>KN(s))),u(e,["parts"],i)}let r=a(t,["role"]);return r!=null&&u(e,["role"],r),e}function LN(t,e,n){let r={},i=a(e,["expireTime"]);n!==void 0&&i!=null&&u(n,["expireTime"],i);let s=a(e,["newSessionExpireTime"]);n!==void 0&&s!=null&&u(n,["newSessionExpireTime"],s);let o=a(e,["uses"]);n!==void 0&&o!=null&&u(n,["uses"],o);let l=a(e,["liveConnectConstraints"]);n!==void 0&&l!=null&&u(n,["bidiGenerateContentSetup"],HN(t,l));let d=a(e,["lockAdditionalFields"]);return n!==void 0&&d!=null&&u(n,["fieldMask"],d),r}function FN(t,e){let n={},r=a(e,["config"]);return r!=null&&u(n,["config"],LN(t,r,n)),n}function GN(t){let e={};if(a(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let n=a(t,["fileUri"]);n!=null&&u(e,["fileUri"],n);let r=a(t,["mimeType"]);return r!=null&&u(e,["mimeType"],r),e}function qN(t){let e={},n=a(t,["id"]);n!=null&&u(e,["id"],n);let r=a(t,["args"]);r!=null&&u(e,["args"],r);let i=a(t,["name"]);if(i!=null&&u(e,["name"],i),a(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(a(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function BN(t){let e={},n=a(t,["authConfig"]);n!=null&&u(e,["authConfig"],DN(n));let r=a(t,["enableWidget"]);return r!=null&&u(e,["enableWidget"],r),e}function $N(t){let e={},n=a(t,["searchTypes"]);if(n!=null&&u(e,["searchTypes"],n),a(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(a(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");let r=a(t,["timeRangeFilter"]);return r!=null&&u(e,["timeRangeFilter"],r),e}function VN(t,e){let n={},r=a(t,["generationConfig"]);e!==void 0&&r!=null&&u(e,["setup","generationConfig"],r);let i=a(t,["responseModalities"]);e!==void 0&&i!=null&&u(e,["setup","generationConfig","responseModalities"],i);let s=a(t,["temperature"]);e!==void 0&&s!=null&&u(e,["setup","generationConfig","temperature"],s);let o=a(t,["topP"]);e!==void 0&&o!=null&&u(e,["setup","generationConfig","topP"],o);let l=a(t,["topK"]);e!==void 0&&l!=null&&u(e,["setup","generationConfig","topK"],l);let d=a(t,["maxOutputTokens"]);e!==void 0&&d!=null&&u(e,["setup","generationConfig","maxOutputTokens"],d);let c=a(t,["mediaResolution"]);e!==void 0&&c!=null&&u(e,["setup","generationConfig","mediaResolution"],c);let f=a(t,["seed"]);e!==void 0&&f!=null&&u(e,["setup","generationConfig","seed"],f);let p=a(t,["speechConfig"]);e!==void 0&&p!=null&&u(e,["setup","generationConfig","speechConfig"],kp(p));let h=a(t,["thinkingConfig"]);e!==void 0&&h!=null&&u(e,["setup","generationConfig","thinkingConfig"],h);let m=a(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&u(e,["setup","generationConfig","enableAffectiveDialog"],m);let g=a(t,["systemInstruction"]);e!==void 0&&g!=null&&u(e,["setup","systemInstruction"],UN(Ne(g)));let _=a(t,["tools"]);if(e!==void 0&&_!=null){let $=ki(_);Array.isArray($)&&($=$.map(N=>zN(bi(N)))),u(e,["setup","tools"],$)}let y=a(t,["sessionResumption"]);e!==void 0&&y!=null&&u(e,["setup","sessionResumption"],JN(y));let T=a(t,["inputAudioTranscription"]);e!==void 0&&T!=null&&u(e,["setup","inputAudioTranscription"],YA(T));let C=a(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&u(e,["setup","outputAudioTranscription"],YA(C));let R=a(t,["realtimeInputConfig"]);e!==void 0&&R!=null&&u(e,["setup","realtimeInputConfig"],R);let x=a(t,["contextWindowCompression"]);e!==void 0&&x!=null&&u(e,["setup","contextWindowCompression"],x);let G=a(t,["proactivity"]);if(e!==void 0&&G!=null&&u(e,["setup","proactivity"],G),a(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");let S=a(t,["avatarConfig"]);e!==void 0&&S!=null&&u(e,["setup","avatarConfig"],S);let q=a(t,["safetySettings"]);if(e!==void 0&&q!=null){let $=q;Array.isArray($)&&($=$.map(N=>WN(N))),u(e,["setup","safetySettings"],$)}return n}function HN(t,e){let n={},r=a(e,["model"]);r!=null&&u(n,["setup","model"],de(t,r));let i=a(e,["config"]);return i!=null&&u(n,["config"],VN(i,n)),n}function KN(t){let e={},n=a(t,["mediaResolution"]);n!=null&&u(e,["mediaResolution"],n);let r=a(t,["codeExecutionResult"]);r!=null&&u(e,["codeExecutionResult"],r);let i=a(t,["executableCode"]);i!=null&&u(e,["executableCode"],i);let s=a(t,["fileData"]);s!=null&&u(e,["fileData"],GN(s));let o=a(t,["functionCall"]);o!=null&&u(e,["functionCall"],qN(o));let l=a(t,["functionResponse"]);l!=null&&u(e,["functionResponse"],l);let d=a(t,["inlineData"]);d!=null&&u(e,["inlineData"],ON(d));let c=a(t,["text"]);c!=null&&u(e,["text"],c);let f=a(t,["thought"]);f!=null&&u(e,["thought"],f);let p=a(t,["thoughtSignature"]);p!=null&&u(e,["thoughtSignature"],p);let h=a(t,["videoMetadata"]);h!=null&&u(e,["videoMetadata"],h);let m=a(t,["toolCall"]);m!=null&&u(e,["toolCall"],m);let g=a(t,["toolResponse"]);g!=null&&u(e,["toolResponse"],g);let _=a(t,["partMetadata"]);return _!=null&&u(e,["partMetadata"],_),e}function WN(t){let e={},n=a(t,["category"]);if(n!=null&&u(e,["category"],n),a(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let r=a(t,["threshold"]);return r!=null&&u(e,["threshold"],r),e}function JN(t){let e={},n=a(t,["handle"]);if(n!=null&&u(e,["handle"],n),a(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function zN(t){let e={};if(a(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let n=a(t,["computerUse"]);n!=null&&u(e,["computerUse"],n);let r=a(t,["fileSearch"]);r!=null&&u(e,["fileSearch"],r);let i=a(t,["googleSearch"]);i!=null&&u(e,["googleSearch"],$N(i));let s=a(t,["googleMaps"]);s!=null&&u(e,["googleMaps"],BN(s));let o=a(t,["codeExecution"]);if(o!=null&&u(e,["codeExecution"],o),a(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let l=a(t,["functionDeclarations"]);if(l!=null){let p=l;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["functionDeclarations"],p)}let d=a(t,["googleSearchRetrieval"]);if(d!=null&&u(e,["googleSearchRetrieval"],d),a(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");let c=a(t,["urlContext"]);c!=null&&u(e,["urlContext"],c);let f=a(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),u(e,["mcpServers"],p)}return e}function YN(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 XN(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=YN(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"],l=[];i.length>0&&(l=i.map(c=>o.includes(c)?`generationConfig.${c}`:c));let d=[];s&&d.push(s),l.length>0&&d.push(...l),d.length>0?t.fieldMask=d.join(","):delete t.fieldMask}else delete t.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?t.fieldMask=i.join(","):delete t.fieldMask;return t}var lp=class extends Ot{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 l=FN(this.apiClient,e);s=z("auth_tokens",l._url),o=l._query,delete l.config,delete l._url,delete l._query;let d=XN(l,e.config);return i=this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}};function QN(t,e){let n={},r=a(t,["force"]);return e!==void 0&&r!=null&&u(e,["_query","force"],r),n}function ZN(t){let e={},n=a(t,["name"]);n!=null&&u(e,["_url","name"],n);let r=a(t,["config"]);return r!=null&&QN(r,e),e}function jN(t){let e={},n=a(t,["name"]);return n!=null&&u(e,["_url","name"],n),e}function eM(t,e){let n={},r=a(t,["pageSize"]);e!==void 0&&r!=null&&u(e,["_query","pageSize"],r);let i=a(t,["pageToken"]);return e!==void 0&&i!=null&&u(e,["_query","pageToken"],i),n}function tM(t){let e={},n=a(t,["parent"]);n!=null&&u(e,["_url","parent"],n);let r=a(t,["config"]);return r!=null&&eM(r,e),e}function nM(t){let e={},n=a(t,["sdkHttpResponse"]);n!=null&&u(e,["sdkHttpResponse"],n);let r=a(t,["nextPageToken"]);r!=null&&u(e,["nextPageToken"],r);let i=a(t,["documents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(o=>o)),u(e,["documents"],s)}return e}var up=class extends Ot{constructor(e){super(),this.apiClient=e,this.list=async n=>new hn(pn.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 l=jN(e);return s=z("{name}",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json()),i.then(d=>d)}}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=ZN(e);i=z("{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 l=tM(e);return s=z("{parent}/documents",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json()),i.then(d=>{let c=nM(d),f=new Df;return Object.assign(f,c),f})}}};var cp=class extends Ot{constructor(e,n=new up(e)){super(),this.apiClient=e,this.documents=n,this.list=async(r={})=>new hn(pn.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((d,c)=>{s[c]=d}),s.alt="media";let o=Object.assign({},n?.httpOptions),l=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:s,httpOptions:o});if(l instanceof Ln){let d=await l.responseInternal.arrayBuffer();return new Uint8Array(d)}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 l=Qk(this.apiClient,e);return s=z("fileSearchStores",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>d)}}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 l=eN(e);return s=z("{name}",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json()),i.then(d=>d)}}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=jk(e);i=z("{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 l=oN(e);return s=z("fileSearchStores",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json()),i.then(d=>{let c=aN(d),f=new Of;return Object.assign(f,c),f})}}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 l=lN(e);return s=z("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=uN(d),f=new Uf;return Object.assign(f,c),f})}}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 l=rN(e);return s=z("{file_search_store_name}:importFile",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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()),i.then(d=>{let c=nN(d),f=new Lf;return Object.assign(f,c),f})}}};var bE=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return bE=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))},rM=()=>bE();function dp(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var fp=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var Qe=class extends Error{},Ze=class t extends Qe{constructor(e,n,r,i){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=i,this.error=n}static makeMessage(e,n,r){let i=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,n,r,i){if(!e||!i)return new Ri({message:r,cause:fp(n)});let s=n;return e===400?new $l(e,s,r,i):e===401?new Vl(e,s,r,i):e===403?new Hl(e,s,r,i):e===404?new Kl(e,s,r,i):e===409?new Wl(e,s,r,i):e===422?new Jl(e,s,r,i):e===429?new zl(e,s,r,i):e>=500?new Yl(e,s,r,i):new t(e,s,r,i)}},Po=class extends Ze{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ri=class extends Ze{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},Bl=class extends Ri{constructor({message:e}={}){super({message:e??"Request timed out."})}},$l=class extends Ze{},Vl=class extends Ze{},Hl=class extends Ze{},Kl=class extends Ze{},Wl=class extends Ze{},Jl=class extends Ze{},zl=class extends Ze{},Yl=class extends Ze{};var iM=/^[a-z][a-z0-9+.-]*:/i,sM=t=>iM.test(t),pp=t=>(pp=Array.isArray,pp(t)),oM=pp,aM=oM,XA=aM;function QA(t){if(!t)return!0;for(let e in t)return!1;return!0}function lM(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var uM=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Qe(`${t} must be an integer`);if(e<0)throw new Qe(`${t} must be a positive integer`);return e},cM=t=>{try{return JSON.parse(t)}catch{return}};var dM=t=>new Promise(e=>setTimeout(e,t));function fM(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function kE(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function pM(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return kE({start(){},async pull(n){let{done:r,value:i}=await e.next();r?n.close():n.enqueue(i)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function NE(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function hM(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}let r=t.getReader(),i=r.cancel();r.releaseLock(),await i}var mM=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function gM(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new Qe(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var _M="0.0.1";var ME=()=>{var t;if(typeof File>"u"){let{process:e}=globalThis,n=typeof((t=e?.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function wf(t,e,n){return ME(),new File(t,e??"unknown_file",n)}function yM(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var AM=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var DE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",EM=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&DE(t),TM=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function wM(t,e,n){if(ME(),t=await t,EM(t))return t instanceof File?t:wf([await t.arrayBuffer()],t.name);if(TM(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),wf(await hp(i),e,n)}let r=await hp(t);if(e||(e=yM(t)),!n?.type){let i=r.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(n=Object.assign(Object.assign({},n),{type:i}))}return wf(r,e,n)}async function hp(t){var e,n,r,i,s;let o=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)o.push(t);else if(DE(t))o.push(t instanceof Blob?t:await t.arrayBuffer());else if(AM(t))try{for(var l=!0,d=Dt(t),c;c=await d.next(),e=c.done,!e;l=!0){i=c.value,l=!1;let f=i;o.push(...await hp(f))}}catch(f){n={error:f}}finally{try{!l&&!e&&(r=d.return)&&await r.call(d)}finally{if(n)throw n.error}}else{let f=(s=t?.constructor)===null||s===void 0?void 0:s.name;throw new Error(`Unexpected data type: ${typeof t}${f?`; constructor: ${f}`:""}${CM(t)}`)}return o}function CM(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var Ro=class{constructor(e){this._client=e}};Ro._key=[];function OE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ZA=Object.freeze(Object.create(null)),IM=(t=OE)=>(function(n,...r){if(n.length===1)return n[0];let i=!1,s=[],o=n.reduce((f,p,h)=>{var m,g,_;/[?#]/.test(p)&&(i=!0);let y=r[h],T=(i?encodeURIComponent:t)(""+y);return h!==r.length&&(y==null||typeof y=="object"&&y.toString===((_=Object.getPrototypeOf((g=Object.getPrototypeOf((m=y.hasOwnProperty)!==null&&m!==void 0?m:ZA))!==null&&g!==void 0?g:ZA))===null||_===void 0?void 0:_.toString))&&(T=y+"",s.push({start:f.length+p.length,length:T.length,error:`Value of type ${Object.prototype.toString.call(y).slice(8,-1)} is not a valid path parameter`})),f+p+(h===r.length?"":T)},""),l=o.split(/[?#]/,1)[0],d=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=d.exec(l))!==null;){let f=c[0].startsWith("/"),p=f?1:0,h=f?c[0].slice(1):c[0];s.push({start:c.index+p,length:h.length,error:`Value "${h}" can't be safely passed as a path parameter`})}if(s.sort((f,p)=>f.start-p.start),s.length>0){let f=0,p=s.reduce((h,m)=>{let g=" ".repeat(m.start-f),_="^".repeat(m.length);return f=m.start+m.length,h+g+_},"");throw new Qe(`Path parameters result in path with invalid segments:
43
+ ${s.map(h=>h.error).join(`
44
+ `)}
45
+ ${o}
46
+ ${p}`)}return o}),Nt=IM(OE);var Xl=class extends Ro{create(e,n){var r;let{api_version:i=this._client.apiVersion}=e,s=Dn(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new Qe("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new Qe("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Nt`/${i}/interactions`,Object.assign(Object.assign({body:s},n),{stream:(r=e.stream)!==null&&r!==void 0?r:!1}))}delete(e,n={},r){let{api_version:i=this._client.apiVersion}=n??{};return this._client.delete(Nt`/${i}/interactions/${e}`,r)}cancel(e,n={},r){let{api_version:i=this._client.apiVersion}=n??{};return this._client.post(Nt`/${i}/interactions/${e}/cancel`,r)}get(e,n={},r){var i;let s=n??{},{api_version:o=this._client.apiVersion}=s,l=Dn(s,["api_version"]);return this._client.get(Nt`/${o}/interactions/${e}`,Object.assign(Object.assign({query:l},r),{stream:(i=n?.stream)!==null&&i!==void 0?i:!1}))}};Xl._key=Object.freeze(["interactions"]);var Ql=class extends Xl{};var Zl=class extends Ro{create(e,n){let{api_version:r=this._client.apiVersion}=e,i=Dn(e,["api_version"]);return this._client.post(Nt`/${r}/webhooks`,Object.assign({body:i},n))}update(e,n={},r){let i=n??{},{api_version:s=this._client.apiVersion,update_mask:o}=i,l=Dn(i,["api_version","update_mask"]);return this._client.patch(Nt`/${s}/webhooks/${e}`,Object.assign({query:{update_mask:o},body:l},r))}list(e={},n){let r=e??{},{api_version:i=this._client.apiVersion}=r,s=Dn(r,["api_version"]);return this._client.get(Nt`/${i}/webhooks`,Object.assign({query:s},n))}delete(e,n={},r){let{api_version:i=this._client.apiVersion}=n??{};return this._client.delete(Nt`/${i}/webhooks/${e}`,r)}get(e,n={},r){let{api_version:i=this._client.apiVersion}=n??{};return this._client.get(Nt`/${i}/webhooks/${e}`,r)}ping(e,n=void 0,r){let{api_version:i=this._client.apiVersion,body:s}=n??{};return this._client.post(Nt`/${i}/webhooks/${e}:ping`,Object.assign({body:s},r))}rotateSigningSecret(e,n={},r){let i=n??{},{api_version:s=this._client.apiVersion}=i,o=Dn(i,["api_version"]);return this._client.post(Nt`/${s}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:o},r))}};Zl._key=Object.freeze(["webhooks"]);var jl=class extends Zl{};function SM(t){let e=0;for(let i of t)e+=i.length;let n=new Uint8Array(e),r=0;for(let i of t)n.set(i,r),r+=i.length;return n}var Tl;function Mp(t){let e;return(Tl??(e=new globalThis.TextEncoder,Tl=e.encode.bind(e)))(t)}var wl;function jA(t){let e;return(wl??(e=new globalThis.TextDecoder,wl=e.decode.bind(e)))(t)}var xi=class{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var n;if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Mp(e):e;this.buffer=SM([this.buffer,r]);let i=[],s;for(;(s=vM(this.buffer,(n=this.carriageReturnIndex)!==null&&n!==void 0?n:this.searchIndex))!=null;){if(s.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=s.index;continue}if(this.carriageReturnIndex!=null&&(s.index!==this.carriageReturnIndex+1||s.carriage)){i.push(jA(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}let o=this.carriageReturnIndex!==null?s.preceding-1:s.preceding,l=jA(this.buffer.subarray(0,o));i.push(l),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),i}flush(){return this.buffer.length?this.decode(`
47
+ `):[]}};xi.NEWLINE_CHARS=new Set([`
48
+ `,"\r"]);xi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function vM(t,e){let i=e??0,s=t.indexOf(10,i),o=t.indexOf(13,i);if(s===-1&&o===-1)return null;let l;return s!==-1&&o!==-1?l=Math.min(s,o):l=s!==-1?s:o,t[l]===10?{preceding:l,index:l+1,carriage:!1}:{preceding:l,index:l+1,carriage:!0}}var eu={off:0,error:200,warn:300,info:400,debug:500},eE=(t,e,n)=>{if(t){if(lM(eu,t))return t;Je(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(eu))}`)}};function vo(){}function Cl(t,e,n){return!e||eu[t]>eu[n]?vo:e[t].bind(e)}var PM={error:vo,warn:vo,info:vo,debug:vo},tE=new WeakMap;function Je(t){var e;let n=t.logger,r=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return PM;let i=tE.get(n);if(i&&i[0]===r)return i[1];let s={error:Cl("error",n,r),warn:Cl("warn",n,r),info:Cl("info",n,r),debug:Cl("debug",n,r)};return tE.set(n,[r,s]),s}var yr=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var mp=class t{constructor(e,n,r){this.iterator=e,this.controller=n,this.client=r}static fromSSEResponse(e,n,r){let i=!1,s=r?Je(r):console;function o(){return Mt(this,arguments,function*(){var d,c,f,p;if(i)throw new Qe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var m=!0,g=Dt(RM(e,n)),_;_=yield se(g.next()),d=_.done,!d;m=!0){p=_.value,m=!1;let y=p;if(!h)if(y.data.startsWith("[DONE]")){h=!0;continue}else try{yield yield se(JSON.parse(y.data))}catch(T){throw s.error("Could not parse message into JSON:",y.data),s.error("From chunk:",y.raw),T}}}catch(y){c={error:y}}finally{try{!m&&!d&&(f=g.return)&&(yield se(f.call(g)))}finally{if(c)throw c.error}}h=!0}catch(y){if(dp(y))return yield se(void 0);throw y}finally{h||n.abort()}})}return new t(o,n,r)}static fromReadableStream(e,n,r){let i=!1;function s(){return Mt(this,arguments,function*(){var d,c,f,p;let h=new xi,m=NE(e);try{for(var g=!0,_=Dt(m),y;y=yield se(_.next()),d=y.done,!d;g=!0){p=y.value,g=!1;let T=p;for(let C of h.decode(T))yield yield se(C)}}catch(T){c={error:T}}finally{try{!g&&!d&&(f=_.return)&&(yield se(f.call(_)))}finally{if(c)throw c.error}}for(let T of h.flush())yield yield se(T)})}function o(){return Mt(this,arguments,function*(){var d,c,f,p;if(i)throw new Qe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var m=!0,g=Dt(s()),_;_=yield se(g.next()),d=_.done,!d;m=!0){p=_.value,m=!1;let y=p;h||y&&(yield yield se(JSON.parse(y)))}}catch(y){c={error:y}}finally{try{!m&&!d&&(f=g.return)&&(yield se(f.call(g)))}finally{if(c)throw c.error}}h=!0}catch(y){if(dp(y))return yield se(void 0);throw y}finally{h||n.abort()}})}return new t(o,n,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=r.next();e.push(o),n.push(o)}return s.shift()}});return[new t(()=>i(e),this.controller,this.client),new t(()=>i(n),this.controller,this.client)]}toReadableStream(){let e=this,n;return kE({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:i,done:s}=await n.next();if(s)return r.close();let o=Mp(JSON.stringify(i)+`
49
+ `);r.enqueue(o)}catch(i){r.error(i)}},async cancel(){var r;await((r=n.return)===null||r===void 0?void 0:r.call(n))}})}};function RM(t,e){return Mt(this,arguments,function*(){var r,i,s,o;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Qe("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Qe("Attempted to iterate over a response with no body");let l=new gp,d=new xi,c=NE(t.body);try{for(var f=!0,p=Dt(xM(c)),h;h=yield se(p.next()),r=h.done,!r;f=!0){o=h.value,f=!1;let m=o;for(let g of d.decode(m)){let _=l.decode(g);_&&(yield yield se(_))}}}catch(m){i={error:m}}finally{try{!f&&!r&&(s=p.return)&&(yield se(s.call(p)))}finally{if(i)throw i.error}}for(let m of d.flush()){let g=l.decode(m);g&&(yield yield se(g))}})}function xM(t){return Mt(this,arguments,function*(){var n,r,i,s;try{for(var o=!0,l=Dt(t),d;d=yield se(l.next()),n=d.done,!n;o=!0){s=d.value,o=!1;let c=s;if(c==null)continue;let f=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?Mp(c):c;yield yield se(f)}}catch(c){r={error:c}}finally{try{!o&&!n&&(i=l.return)&&(yield se(i.call(l)))}finally{if(r)throw r.error}}})}var gp=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
50
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,i]=bM(e,":");return i.startsWith(" ")&&(i=i.substring(1)),n==="event"?this.event=i:n==="data"&&this.data.push(i),null}};function bM(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function kM(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:s}=e,o=await(async()=>{var l;if(e.options.stream)return Je(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):mp.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let d=n.headers.get("content-type"),c=(l=d?.split(";")[0])===null||l===void 0?void 0:l.trim();return c?.includes("application/json")||c?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return Je(t).debug(`[${r}] response parsed`,yr({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-s})),o}var _p=class t extends Promise{constructor(e,n,r=kM){super(i=>{i(null)}),this.responsePromise=n,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new t(this.client,this.responsePromise,async(n,r)=>e(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};var UE=Symbol("brand.privateNullableHeaders");function*NM(t){if(!t)return;if(UE in t){let{values:r,nulls:i}=t;yield*r.entries();for(let s of i)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():XA(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=XA(r[1])?r[1]:[r[1]],o=!1;for(let l of s)l!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,l])}}var Io=t=>{let e=new Headers,n=new Set;for(let r of t){let i=new Set;for(let[s,o]of NM(r)){let l=s.toLowerCase();i.has(l)||(e.delete(s),i.add(l)),o===null?(e.delete(s),n.add(l)):(e.append(s,o),n.delete(l))}}return{[UE]:!0,values:e,nulls:n}};var Cf=t=>{var e,n,r,i,s;if(typeof globalThis.process<"u")return((n=(e=globalThis.process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(i=(r=globalThis.Deno.env)===null||r===void 0?void 0:r.get)===null||i===void 0?void 0:i.call(r,t))===null||s===void 0?void 0:s.trim())||void 0};var LE,tu=class t{constructor(e){var n,r,i,s,o,l,d,{baseURL:c=Cf("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:f=(n=Cf("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:p="v1beta"}=e,h=Dn(e,["baseURL","apiKey","apiVersion"]);let m=Object.assign(Object.assign({apiKey:f,apiVersion:p},h),{baseURL:c||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(r=m.timeout)!==null&&r!==void 0?r:t.DEFAULT_TIMEOUT,this.logger=(i=m.logger)!==null&&i!==void 0?i:console;let g="warn";this.logLevel=g,this.logLevel=(o=(s=eE(m.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:eE(Cf("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&o!==void 0?o:g,this.fetchOptions=m.fetchOptions,this.maxRetries=(l=m.maxRetries)!==null&&l!==void 0?l:2,this.fetch=(d=m.fetch)!==null&&d!==void 0?d:fM(),this.encoder=mM,this._options=m,this.apiKey=f,this.apiVersion=p,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let n=Io([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return Io([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return Io([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return gM(e)}getUserAgent(){return`${this.constructor.name}/JS ${_M}`}defaultIdempotencyKey(){return`stainless-node-retry-${rM()}`}makeStatusError(e,n,r,i){return Ze.generate(e,n,r,i)}buildURL(e,n,r){let i=!this.baseURLOverridden()&&r||this.baseURL,s=sM(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),l=Object.fromEntries(s.searchParams);return(!QA(o)||!QA(l))&&(n=Object.assign(Object.assign(Object.assign({},l),o),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(i=>Object.assign({method:e,path:n},i)))}request(e,n=null){return new _p(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var i,s,o;let l=await e,d=(i=l.maxRetries)!==null&&i!==void 0?i:this.maxRetries;n==null&&(n=d),await this.prepareOptions(l);let{req:c,url:f,timeout:p}=await this.buildRequest(l,{retryCount:d-n});await this.prepareRequest(c,{url:f,options:l});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(Je(this).debug(`[${h}] sending request`,yr({retryOfRequestLogID:r,method:l.method,url:f,options:l,headers:c.headers})),!((s=l.signal)===null||s===void 0)&&s.aborted)throw new Po;let _=new AbortController,y=await this.fetchWithTimeout(f,c,p,_).catch(fp),T=Date.now();if(y instanceof globalThis.Error){let R=`retrying, ${n} attempts remaining`;if(!((o=l.signal)===null||o===void 0)&&o.aborted)throw new Po;let x=dp(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(n)return Je(this).info(`[${h}] connection ${x?"timed out":"failed"} - ${R}`),Je(this).debug(`[${h}] connection ${x?"timed out":"failed"} (${R})`,yr({retryOfRequestLogID:r,url:f,durationMs:T-g,message:y.message})),this.retryRequest(l,n,r??h);throw Je(this).info(`[${h}] connection ${x?"timed out":"failed"} - error; no more retries left`),Je(this).debug(`[${h}] connection ${x?"timed out":"failed"} (error; no more retries left)`,yr({retryOfRequestLogID:r,url:f,durationMs:T-g,message:y.message})),x?new Bl:new Ri({cause:y})}let C=`[${h}${m}] ${c.method} ${f} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${T-g}ms`;if(!y.ok){let R=await this.shouldRetry(y);if(n&&R){let N=`retrying, ${n} attempts remaining`;return await hM(y.body),Je(this).info(`${C} - ${N}`),Je(this).debug(`[${h}] response error (${N})`,yr({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:T-g})),this.retryRequest(l,n,r??h,y.headers)}let x=R?"error; no more retries left":"error; not retryable";Je(this).info(`${C} - ${x}`);let G=await y.text().catch(N=>fp(N).message),S=cM(G),q=S?void 0:G;throw Je(this).debug(`[${h}] response error (${x})`,yr({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:q,durationMs:Date.now()-g})),this.makeStatusError(y.status,S,q,y.headers)}return Je(this).info(C),Je(this).debug(`[${h}] response start`,yr({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:T-g})),{response:y,options:l,controller:_,requestLogID:h,retryOfRequestLogID:r,startTime:g}}async fetchWithTimeout(e,n,r,i){let s=n||{},{signal:o,method:l}=s,d=Dn(s,["signal","method"]),c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let f=setTimeout(c,r),p=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,h=Object.assign(Object.assign(Object.assign({signal:i.signal},p?{duplex:"half"}:{}),{method:"GET"}),d);l&&(h.method=l.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(f)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,i){var s;let o,l=i?.get("retry-after-ms");if(l){let c=parseFloat(l);Number.isNaN(c)||(o=c)}let d=i?.get("retry-after");if(d&&!o){let c=parseFloat(d);Number.isNaN(c)?o=Date.parse(d)-Date.now():o=c*1e3}if(o===void 0){let c=(s=e.maxRetries)!==null&&s!==void 0?s:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,c)}return await dM(o),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let s=n-e,o=Math.min(.5*Math.pow(2,s),8),l=1-Math.random()*.25;return o*l*1e3}async buildRequest(e,{retryCount:n=0}={}){var r,i,s;let o=Object.assign({},e),{method:l,path:d,query:c,defaultBaseURL:f}=o,p=this.buildURL(d,c,f);"timeout"in o&&uM("timeout",o.timeout),o.timeout=(r=o.timeout)!==null&&r!==void 0?r:this.timeout;let{bodyHeaders:h,body:m}=this.buildBody({options:o}),g=await this.buildHeaders({options:e,method:l,bodyHeaders:h,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:l,headers:g},o.signal&&{signal:o.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(s=o.fetchOptions)!==null&&s!==void 0?s:{}),url:p,timeout:o.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=await this.authHeaders(e),l=Io([s,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,r,e.headers,o]);return this.validateHeaders(l),l.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=Io([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:pM(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}};tu.DEFAULT_TIMEOUT=6e4;var Te=class extends tu{constructor(){super(...arguments),this.interactions=new Ql(this),this.webhooks=new jl(this)}};LE=Te;Te.GeminiNextGenAPIClient=LE;Te.GeminiNextGenAPIClientError=Qe;Te.APIError=Ze;Te.APIConnectionError=Ri;Te.APIConnectionTimeoutError=Bl;Te.APIUserAbortError=Po;Te.NotFoundError=Kl;Te.ConflictError=Wl;Te.RateLimitError=zl;Te.BadRequestError=$l;Te.AuthenticationError=Vl;Te.InternalServerError=Yl;Te.PermissionDeniedError=Hl;Te.UnprocessableEntityError=Jl;Te.toFile=wM;Te.Interactions=Ql;Te.Webhooks=jl;var nE="x-goog-api-key",So="https://www.googleapis.com/auth/cloud-platform",yp=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=MM(e.googleAuthOptions);this.googleAuth=new iE.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(nE)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(nE,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)}};function MM(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==So||Array.isArray(e.scopes)&&e.scopes.indexOf(So)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${So}`)}else return e.scopes=[So],e;return e}else return e={scopes:[So]},e}var Ap=class{async download(e,n){if(e.downloadPath){let r=await DM(e,n);if(r instanceof Ln){let i=h0(e.downloadPath);g0.fromWeb(r.responseInternal.body).pipe(i),await _0(i)}else try{await m0(e.downloadPath,r,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};async function DM(t,e){var n,r,i;let s=Np(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(fE(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(pE(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")}var Ep=class{create(e,n,r){return new Tp(e,n,r)}},Tp=class{constructor(e,n,r){this.url=e,this.headers=n,this.callbacks=r}connect(){this.ws=new Tf.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function OM(t,e){let n={},r=a(t,["name"]);return r!=null&&u(n,["_url","name"],r),n}function UM(t,e){let n={},r=a(t,["name"]);return r!=null&&u(n,["_url","name"],r),n}function LM(t,e){let n={},r=a(t,["sdkHttpResponse"]);return r!=null&&u(n,["sdkHttpResponse"],r),n}function FM(t,e){let n={},r=a(t,["sdkHttpResponse"]);return r!=null&&u(n,["sdkHttpResponse"],r),n}function GM(t,e,n){let r={};if(a(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");let i=a(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&u(e,["displayName"],i),a(t,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");let s=a(t,["epochCount"]);e!==void 0&&s!=null&&u(e,["tuningTask","hyperparameters","epochCount"],s);let o=a(t,["learningRateMultiplier"]);if(o!=null&&u(r,["tuningTask","hyperparameters","learningRateMultiplier"],o),a(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(a(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(a(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");if(a(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is not supported in Gemini API.");if(a(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is not supported in Gemini API.");let l=a(t,["batchSize"]);e!==void 0&&l!=null&&u(e,["tuningTask","hyperparameters","batchSize"],l);let d=a(t,["learningRate"]);if(e!==void 0&&d!=null&&u(e,["tuningTask","hyperparameters","learningRate"],d),a(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(a(t,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");if(a(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is not supported in Gemini API.");if(a(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(a(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(a(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is not supported in Gemini API.");if(a(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is not supported in Gemini API.");return r}function qM(t,e,n){let r={},i=a(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let S=a(t,["validationDataset"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec"],If(S))}else if(i==="PREFERENCE_TUNING"){let S=a(t,["validationDataset"]);e!==void 0&&S!=null&&u(e,["preferenceOptimizationSpec"],If(S))}else if(i==="DISTILLATION"){let S=a(t,["validationDataset"]);e!==void 0&&S!=null&&u(e,["distillationSpec"],If(S))}let s=a(t,["tunedModelDisplayName"]);e!==void 0&&s!=null&&u(e,["tunedModelDisplayName"],s);let o=a(t,["description"]);e!==void 0&&o!=null&&u(e,["description"],o);let l=a(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){let S=a(t,["epochCount"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","hyperParameters","epochCount"],S)}else if(l==="PREFERENCE_TUNING"){let S=a(t,["epochCount"]);e!==void 0&&S!=null&&u(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],S)}else if(l==="DISTILLATION"){let S=a(t,["epochCount"]);e!==void 0&&S!=null&&u(e,["distillationSpec","hyperParameters","epochCount"],S)}let d=a(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let S=a(t,["learningRateMultiplier"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],S)}else if(d==="PREFERENCE_TUNING"){let S=a(t,["learningRateMultiplier"]);e!==void 0&&S!=null&&u(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],S)}else if(d==="DISTILLATION"){let S=a(t,["learningRateMultiplier"]);e!==void 0&&S!=null&&u(e,["distillationSpec","hyperParameters","learningRateMultiplier"],S)}let c=a(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let S=a(t,["exportLastCheckpointOnly"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","exportLastCheckpointOnly"],S)}else if(c==="PREFERENCE_TUNING"){let S=a(t,["exportLastCheckpointOnly"]);e!==void 0&&S!=null&&u(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],S)}else if(c==="DISTILLATION"){let S=a(t,["exportLastCheckpointOnly"]);e!==void 0&&S!=null&&u(e,["distillationSpec","exportLastCheckpointOnly"],S)}let f=a(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let S=a(t,["adapterSize"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","hyperParameters","adapterSize"],S)}else if(f==="PREFERENCE_TUNING"){let S=a(t,["adapterSize"]);e!==void 0&&S!=null&&u(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],S)}else if(f==="DISTILLATION"){let S=a(t,["adapterSize"]);e!==void 0&&S!=null&&u(e,["distillationSpec","hyperParameters","adapterSize"],S)}let p=a(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let S=a(t,["tuningMode"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","tuningMode"],S)}else if(p==="DISTILLATION"){let S=a(t,["tuningMode"]);e!==void 0&&S!=null&&u(e,["distillationSpec","tuningMode"],S)}let h=a(t,["customBaseModel"]);e!==void 0&&h!=null&&u(e,["customBaseModel"],h);let m=a(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let S=a(t,["batchSize"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","hyperParameters","batchSize"],S)}else if(m==="DISTILLATION"){let S=a(t,["batchSize"]);e!==void 0&&S!=null&&u(e,["distillationSpec","hyperParameters","batchSize"],S)}let g=a(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){let S=a(t,["learningRate"]);e!==void 0&&S!=null&&u(e,["supervisedTuningSpec","hyperParameters","learningRate"],S)}else if(g==="DISTILLATION"){let S=a(t,["learningRate"]);e!==void 0&&S!=null&&u(e,["distillationSpec","hyperParameters","learningRate"],S)}let _=a(t,["labels"]);e!==void 0&&_!=null&&u(e,["labels"],_);let y=a(t,["beta"]);e!==void 0&&y!=null&&u(e,["preferenceOptimizationSpec","hyperParameters","beta"],y);let T=a(t,["baseTeacherModel"]);e!==void 0&&T!=null&&u(e,["distillationSpec","baseTeacherModel"],T);let C=a(t,["tunedTeacherModelSource"]);e!==void 0&&C!=null&&u(e,["distillationSpec","tunedTeacherModelSource"],C);let R=a(t,["sftLossWeightMultiplier"]);e!==void 0&&R!=null&&u(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],R);let x=a(t,["outputUri"]);e!==void 0&&x!=null&&u(e,["outputUri"],x);let G=a(t,["encryptionSpec"]);return e!==void 0&&G!=null&&u(e,["encryptionSpec"],G),r}function BM(t,e){let n={},r=a(t,["baseModel"]);r!=null&&u(n,["baseModel"],r);let i=a(t,["preTunedModel"]);i!=null&&u(n,["preTunedModel"],i);let s=a(t,["trainingDataset"]);s!=null&&YM(s);let o=a(t,["config"]);return o!=null&&GM(o,n),n}function $M(t,e){let n={},r=a(t,["baseModel"]);r!=null&&u(n,["baseModel"],r);let i=a(t,["preTunedModel"]);i!=null&&u(n,["preTunedModel"],i);let s=a(t,["trainingDataset"]);s!=null&&XM(s,n,e);let o=a(t,["config"]);return o!=null&&qM(o,n,e),n}function VM(t,e){let n={},r=a(t,["name"]);return r!=null&&u(n,["_url","name"],r),n}function HM(t,e){let n={},r=a(t,["name"]);return r!=null&&u(n,["_url","name"],r),n}function KM(t,e,n){let r={},i=a(t,["pageSize"]);e!==void 0&&i!=null&&u(e,["_query","pageSize"],i);let s=a(t,["pageToken"]);e!==void 0&&s!=null&&u(e,["_query","pageToken"],s);let o=a(t,["filter"]);return e!==void 0&&o!=null&&u(e,["_query","filter"],o),r}function WM(t,e){let n={},r=a(t,["config"]);return r!=null&&KM(r,n),n}function JM(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["nextPageToken"]);i!=null&&u(n,["nextPageToken"],i);let s=a(t,["tuningJobs"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(l=>wp(l))),u(n,["tuningJobs"],o)}return n}function zM(t,e){let n={},r=a(t,["name"]);r!=null&&u(n,["model"],r);let i=a(t,["name"]);return i!=null&&u(n,["endpoint"],i),n}function YM(t,e){let n={};if(a(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(a(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");let r=a(t,["examples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(s=>s)),u(n,["examples","examples"],i)}return n}function XM(t,e,n){let r={},i=a(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let o=a(t,["gcsUri"]);e!==void 0&&o!=null&&u(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(i==="PREFERENCE_TUNING"){let o=a(t,["gcsUri"]);e!==void 0&&o!=null&&u(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(i==="DISTILLATION"){let o=a(t,["gcsUri"]);e!==void 0&&o!=null&&u(e,["distillationSpec","promptDatasetUri"],o)}let s=a(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let o=a(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&u(e,["supervisedTuningSpec","trainingDatasetUri"],o)}else if(s==="PREFERENCE_TUNING"){let o=a(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&u(e,["preferenceOptimizationSpec","trainingDatasetUri"],o)}else if(s==="DISTILLATION"){let o=a(t,["vertexDatasetResource"]);e!==void 0&&o!=null&&u(e,["distillationSpec","promptDatasetUri"],o)}if(a(t,["examples"])!==void 0)throw new Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return r}function QM(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["name"]);i!=null&&u(n,["name"],i);let s=a(t,["state"]);s!=null&&u(n,["state"],dE(s));let o=a(t,["createTime"]);o!=null&&u(n,["createTime"],o);let l=a(t,["tuningTask","startTime"]);l!=null&&u(n,["startTime"],l);let d=a(t,["tuningTask","completeTime"]);d!=null&&u(n,["endTime"],d);let c=a(t,["updateTime"]);c!=null&&u(n,["updateTime"],c);let f=a(t,["description"]);f!=null&&u(n,["description"],f);let p=a(t,["baseModel"]);p!=null&&u(n,["baseModel"],p);let h=a(t,["_self"]);return h!=null&&u(n,["tunedModel"],zM(h)),n}function wp(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["name"]);i!=null&&u(n,["name"],i);let s=a(t,["state"]);s!=null&&u(n,["state"],dE(s));let o=a(t,["createTime"]);o!=null&&u(n,["createTime"],o);let l=a(t,["startTime"]);l!=null&&u(n,["startTime"],l);let d=a(t,["endTime"]);d!=null&&u(n,["endTime"],d);let c=a(t,["updateTime"]);c!=null&&u(n,["updateTime"],c);let f=a(t,["error"]);f!=null&&u(n,["error"],f);let p=a(t,["description"]);p!=null&&u(n,["description"],p);let h=a(t,["baseModel"]);h!=null&&u(n,["baseModel"],h);let m=a(t,["tunedModel"]);m!=null&&u(n,["tunedModel"],m);let g=a(t,["preTunedModel"]);g!=null&&u(n,["preTunedModel"],g);let _=a(t,["supervisedTuningSpec"]);_!=null&&u(n,["supervisedTuningSpec"],_);let y=a(t,["preferenceOptimizationSpec"]);y!=null&&u(n,["preferenceOptimizationSpec"],y);let T=a(t,["distillationSpec"]);T!=null&&u(n,["distillationSpec"],T);let C=a(t,["tuningDataStats"]);C!=null&&u(n,["tuningDataStats"],C);let R=a(t,["encryptionSpec"]);R!=null&&u(n,["encryptionSpec"],R);let x=a(t,["partnerModelTuningSpec"]);x!=null&&u(n,["partnerModelTuningSpec"],x);let G=a(t,["customBaseModel"]);G!=null&&u(n,["customBaseModel"],G);let S=a(t,["evaluateDatasetRuns"]);if(S!=null){let nt=S;Array.isArray(nt)&&(nt=nt.map(Se=>Se)),u(n,["evaluateDatasetRuns"],nt)}let q=a(t,["experiment"]);q!=null&&u(n,["experiment"],q);let $=a(t,["fullFineTuningSpec"]);$!=null&&u(n,["fullFineTuningSpec"],$);let N=a(t,["labels"]);N!=null&&u(n,["labels"],N);let K=a(t,["outputUri"]);K!=null&&u(n,["outputUri"],K);let Q=a(t,["pipelineJob"]);Q!=null&&u(n,["pipelineJob"],Q);let oe=a(t,["serviceAccount"]);oe!=null&&u(n,["serviceAccount"],oe);let ie=a(t,["tunedModelDisplayName"]);ie!=null&&u(n,["tunedModelDisplayName"],ie);let ae=a(t,["tuningJobState"]);ae!=null&&u(n,["tuningJobState"],ae);let fe=a(t,["veoTuningSpec"]);fe!=null&&u(n,["veoTuningSpec"],fe);let Ee=a(t,["distillationSamplingSpec"]);Ee!=null&&u(n,["distillationSamplingSpec"],Ee);let tt=a(t,["tuningJobMetadata"]);return tt!=null&&u(n,["tuningJobMetadata"],tt),n}function ZM(t,e){let n={},r=a(t,["sdkHttpResponse"]);r!=null&&u(n,["sdkHttpResponse"],r);let i=a(t,["name"]);i!=null&&u(n,["name"],i);let s=a(t,["metadata"]);s!=null&&u(n,["metadata"],s);let o=a(t,["done"]);o!=null&&u(n,["done"],o);let l=a(t,["error"]);return l!=null&&u(n,["error"],l),n}function If(t,e){let n={},r=a(t,["gcsUri"]);r!=null&&u(n,["validationDatasetUri"],r);let i=a(t,["vertexDatasetResource"]);return i!=null&&u(n,["validationDatasetUri"],i),n}var Cp=class extends Ot{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new hn(pn.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:vf.JOB_STATE_QUEUED}}}}async getInternal(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=HM(e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>wp(f))}else{let c=VM(e);return l=z("{name}",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,body:JSON.stringify(c),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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>QM(f))}}async listInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=WM(e);return s=z("tuningJobs",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(d=>d.json().then(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>{let c=JM(d),f=new Mf;return Object.assign(f,c),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,r,i,s;let o,l="",d={};if(this.apiClient.isVertexAI()){let c=UM(e);return l=z("{name}:cancel",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=FM(f),h=new Dl;return Object.assign(h,p),h})}else{let c=OM(e);return l=z("{name}:cancel",c._url),d=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:l,queryParams:d,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}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),o.then(f=>{let p=LM(f),h=new Dl;return Object.assign(h,p),h})}}async tuneInternal(e){var n,r;let i,s="",o={};if(this.apiClient.isVertexAI()){let l=$M(e,e);return s=z("tuningJobs",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>wp(d))}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 l=BM(e);return s=z("tunedModels",l._url),o=l._query,delete l._url,delete l._query,i=this.apiClient.request({path:s,queryParams:o,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(c=>{let f=c;return f.sdkHttpResponse={headers:d.headers},f})),i.then(d=>ZM(d))}}},FE=1024*1024*8,GE=3,qE=1e3,BE=2,On="x-goog-upload-status";async function jM(t,e,n,r){var i;let s=await $E(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[On])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return o.file}async function eD(t,e,n,r){var i;let s=await $E(t,e,n,r),o=await s?.json();if(((i=s?.headers)===null||i===void 0?void 0:i[On])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let l=Pp(o),d=new Fl;return Object.assign(d,l),d}async function $E(t,e,n,r){var i,s,o;let l=e,d=r?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(d){let m=new URL(d),g=new URL(e);g.protocol=m.protocol,g.host=m.host,g.port=m.port,l=g.toString()}let c=0,f=0,p=new Ln(new Response),h="upload";for(c=t.size;f<c;){let m=Math.min(FE,c-f),g=t.slice(f,f+m);f+m>=c&&(h+=", finalize");let _=0,y=qE;for(;_<GE;){let T=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f),"Content-Length":String(m)});if(p=await n.request({path:"",body:g,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:l,headers:T})}),!((s=p?.headers)===null||s===void 0)&&s[On])break;_++,await VE(y),y=y*BE}if(f+=m,((o=p?.headers)===null||o===void 0?void 0:o[On])!=="active")break;if(c<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function tD(t){return{size:t.size,type:t.type}}function VE(t){return new Promise(e=>setTimeout(e,t))}var Ip=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let r=await ru.stat(e);return n.size=r.size,n.type=this.inferMimeType(e),n}else return await tD(e)}async upload(e,n,r,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,r,i):jM(e,n,r,i)}async uploadToFileSearchStore(e,n,r,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,r,i):eD(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),l=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[On])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return l.file}async uploadFileToFileSearchStoreFromPath(e,n,r,i){var s;let o=await this.uploadFileFromPathInternal(e,n,r,i),l=await o?.json();if(((s=o?.headers)===null||s===void 0?void 0:s[On])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let d=Pp(l),c=new Fl;return Object.assign(c,d),c}async uploadFileFromPathInternal(e,n,r,i){var s,o,l;let d=n,c=i?.baseUrl||((s=r.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(c){let y=new URL(c),T=new URL(n);T.protocol=y.protocol,T.host=y.host,T.port=y.port,d=T.toString()}let f=0,p=0,h=new Ln(new Response),m="upload",g,_=sE.basename(e);try{if(g=await ru.open(e,"r"),!g)throw new Error("Failed to open file");for(f=(await g.stat()).size;p<f;){let y=Math.min(FE,f-p);p+y>=f&&(m+=", finalize");let T=new Uint8Array(y),{bytesRead:C}=await g.read(T,0,y,p);if(C!==y)throw new Error(`Failed to read ${y} bytes from file at offset ${p}. bytes actually read: ${C}`);let R=new Blob([T]),x=0,G=qE;for(;x<GE;){let S=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(p),"Content-Length":String(C),"X-Goog-Upload-File-Name":_});if(h=await r.request({path:"",body:R,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:d,headers:S})}),!((o=h?.headers)===null||o===void 0)&&o[On])break;x++,await VE(G),G=G*BE}if(p+=C,((l=h?.headers)===null||l===void 0?void 0:l[On])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{g&&await g.close()}}};var Sp=class extends Xf{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[l,d]of r)o[l]=d;else for(let[l,d]of Object.entries(r))o[l]=d;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},s),{headers:o})})})}};var nD="gl-node/";function rD(t){var e;if(t.enterprise!==void 0||t.vertexai!==void 0){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}let n=Un("GOOGLE_GENAI_USE_ENTERPRISE"),r=Un("GOOGLE_GENAI_USE_VERTEXAI"),i=rE(n),s=rE(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}var xo=class{getNextGenClient(){var e;let n=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=new Te({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:n?.timeout,maxRetries:(e=n?.retryOptions)===null||e===void 0?void 0:e.attempts})),n?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions,this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=this.getNextGenClient().webhooks,this._webhooks)}constructor(e){var n,r,i,s;if((e.project||e.location)&&e.apiKey)throw new Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=rD(e);let o=iD(),l=Un("GOOGLE_CLOUD_PROJECT"),d=Un("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:o,this.project=(r=e.project)!==null&&r!==void 0?r:l,this.location=(i=e.location)!==null&&i!==void 0?i:d,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),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),(l||d)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&o?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(l||d)&&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 c=T0(e.httpOptions,this.vertexai,Un("GOOGLE_VERTEX_BASE_URL"),Un("GOOGLE_GEMINI_BASE_URL"));c&&(e.httpOptions?e.httpOptions.baseUrl=c:e.httpOptions={baseUrl:c}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let f=new yp({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new ep({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:nD+process.version,uploader:new Ip,downloader:new Ap}),this.models=new op(this.apiClient),this.live=new ip(this.apiClient,f,new Ep),this.batches=new Wf(this.apiClient),this.chats=new zf(this.models,this.apiClient),this.caches=new Jf(this.apiClient),this.files=new Sp(this.apiClient),this.operations=new ap(this.apiClient),this.authTokens=new lp(this.apiClient),this.tunings=new Cp(this.apiClient),this.fileSearchStores=new cp(this.apiClient)}};function Un(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 rE(t){return t===void 0?!1:t.toLowerCase()==="true"}function iD(){let t=Un("GOOGLE_API_KEY"),e=Un("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}function Z(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n}function b(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var Er=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Er=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function ko(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var No=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var W=class extends Error{},Ae=class t extends W{constructor(e,n,r,i){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=n;let s=n;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,n,r){let i=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,n,r,i){if(!e||!i)return new Gn({message:r,cause:No(n)});let s=n?.error;return e===400?new Di(e,s,r,i):e===401?new Oi(e,s,r,i):e===403?new Ui(e,s,r,i):e===404?new Li(e,s,r,i):e===409?new Fi(e,s,r,i):e===422?new Gi(e,s,r,i):e===429?new qi(e,s,r,i):e>=500?new Bi(e,s,r,i):new t(e,s,r,i)}},we=class extends Ae{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Gn=class extends Ae{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},qn=class extends Gn{constructor({message:e}={}){super({message:e??"Request timed out."})}},Di=class extends Ae{},Oi=class extends Ae{},Ui=class extends Ae{},Li=class extends Ae{},Fi=class extends Ae{},Gi=class extends Ae{},qi=class extends Ae{},Bi=class extends Ae{},$i=class extends W{constructor(){super("Could not parse response content as the length limit was reached")}},Vi=class extends W{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Qt=class extends Error{constructor(e){super(e)}},Tr=class extends Ae{constructor(e,n,r){let i="OAuth2 authentication error",s;if(n&&typeof n=="object"){let o=n;s=o.error;let l=o.error_description;l&&typeof l=="string"?i=l:s&&(i=s)}super(e,n,i,r),this.error_code=s}},Mo=class extends W{constructor(e,n,r){super(e),this.provider=n,this.cause=r}};var oD=/^[a-z][a-z0-9+.-]*:/i,HE=t=>oD.test(t),Be=t=>(Be=Array.isArray,Be(t)),Dp=Be;function ou(t){return typeof t!="object"?{}:t??{}}function Op(t){if(!t)return!0;for(let e in t)return!1;return!0}function KE(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Do(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var WE=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new W(`${t} must be an integer`);if(e<0)throw new W(`${t} must be a positive integer`);return e};var JE=t=>{try{return JSON.parse(t)}catch{return}};var Zt=t=>new Promise(e=>setTimeout(e,t));var Bn="6.49.0";var QE=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function aD(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var lD=()=>{let t=aD();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bn,"X-Stainless-OS":YE(Deno.build.os),"X-Stainless-Arch":zE(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bn,"X-Stainless-OS":YE(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zE(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=uD();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function uD(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let i=r[1]||0,s=r[2]||0,o=r[3]||0;return{browser:e,version:`${i}.${s}.${o}`}}}return null}var zE=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",YE=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),XE,ZE=()=>XE??(XE=lD());function au(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Up(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Oo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Up({start(){},async pull(n){let{done:r,value:i}=await e.next();r?n.close():n.enqueue(i)},async cancel(){await e.return?.()}})}function lu(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Lp(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var eT=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Fp="RFC3986",Gp=t=>String(t),qp={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Gp},tT="RFC1738";var uu=(t,e)=>(uu=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),uu(t,e)),jt=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Bp=1024,nT=(t,e,n,r,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),n==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let o="";for(let l=0;l<s.length;l+=Bp){let d=s.length>=Bp?s.slice(l,l+Bp):s,c=[];for(let f=0;f<d.length;++f){let p=d.charCodeAt(f);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===tT&&(p===40||p===41)){c[c.length]=d.charAt(f);continue}if(p<128){c[c.length]=jt[p];continue}if(p<2048){c[c.length]=jt[192|p>>6]+jt[128|p&63];continue}if(p<55296||p>=57344){c[c.length]=jt[224|p>>12]+jt[128|p>>6&63]+jt[128|p&63];continue}f+=1,p=65536+((p&1023)<<10|d.charCodeAt(f)&1023),c[c.length]=jt[240|p>>18]+jt[128|p>>12&63]+jt[128|p>>6&63]+jt[128|p&63]}o+=c.join("")}return o};function rT(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function $p(t,e){if(Be(t)){let n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}var sT={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},oT=function(t,e){Array.prototype.push.apply(t,Be(e)?e:[e])},iT,be={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:nT,encodeValuesOnly:!1,format:Fp,formatter:Gp,indices:!1,serializeDate(t){return(iT??(iT=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function dD(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Vp={};function aT(t,e,n,r,i,s,o,l,d,c,f,p,h,m,g,_,y,T){let C=t,R=T,x=0,G=!1;for(;(R=R.get(Vp))!==void 0&&!G;){let K=R.get(t);if(x+=1,typeof K<"u"){if(K===x)throw new RangeError("Cyclic object value");G=!0}typeof R.get(Vp)>"u"&&(x=0)}if(typeof c=="function"?C=c(e,C):C instanceof Date?C=h?.(C):n==="comma"&&Be(C)&&(C=$p(C,function(K){return K instanceof Date?h?.(K):K})),C===null){if(s)return d&&!_?d(e,be.encoder,y,"key",m):e;C=""}if(dD(C)||rT(C)){if(d){let K=_?e:d(e,be.encoder,y,"key",m);return[g?.(K)+"="+g?.(d(C,be.encoder,y,"value",m))]}return[g?.(e)+"="+g?.(String(C))]}let S=[];if(typeof C>"u")return S;let q;if(n==="comma"&&Be(C))_&&d&&(C=$p(C,d)),q=[{value:C.length>0?C.join(",")||null:void 0}];else if(Be(c))q=c;else{let K=Object.keys(C);q=f?K.sort(f):K}let $=l?String(e).replace(/\./g,"%2E"):String(e),N=r&&Be(C)&&C.length===1?$+"[]":$;if(i&&Be(C)&&C.length===0)return N+"[]";for(let K=0;K<q.length;++K){let Q=q[K],oe=typeof Q=="object"&&typeof Q.value<"u"?Q.value:C[Q];if(o&&oe===null)continue;let ie=p&&l?Q.replace(/\./g,"%2E"):Q,ae=Be(C)?typeof n=="function"?n(N,ie):N:N+(p?"."+ie:"["+ie+"]");T.set(t,x);let fe=new WeakMap;fe.set(Vp,T),oT(S,aT(oe,ae,n,r,i,s,o,l,n==="comma"&&_&&Be(C)?null:d,c,f,p,h,m,g,_,y,fe))}return S}function fD(t=be){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||be.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Fp;if(typeof t.format<"u"){if(!uu(qp,t.format))throw new TypeError("Unknown format option provided.");n=t.format}let r=qp[n],i=be.filter;(typeof t.filter=="function"||Be(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in sT?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=be.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:be.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:be.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:be.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:be.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?be.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:be.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:be.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:be.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:be.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:be.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:be.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:be.strictNullHandling}}function lT(t,e={}){let n=t,r=fD(e),i,s;typeof r.filter=="function"?(s=r.filter,n=s("",n)):Be(r.filter)&&(s=r.filter,i=s);let o=[];if(typeof n!="object"||n===null)return"";let l=sT[r.arrayFormat],d=l==="comma"&&r.commaRoundTrip;i||(i=Object.keys(n)),r.sort&&i.sort(r.sort);let c=new WeakMap;for(let h=0;h<i.length;++h){let m=i[h];r.skipNulls&&n[m]===null||oT(o,aT(n[m],m,l,d,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}let f=o.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),f.length>0?p+f:""}function uT(t){return lT(t,{arrayFormat:"brackets"})}function fT(t){let e=0;for(let i of t)e+=i.length;let n=new Uint8Array(e),r=0;for(let i of t)n.set(i,r),r+=i.length;return n}var cT;function lt(t){let e;return(cT??(e=new globalThis.TextEncoder,cT=e.encode.bind(e)))(t)}var dT;function Hp(t){let e;return(dT??(e=new globalThis.TextDecoder,dT=e.decode.bind(e)))(t)}var ut,ct,wr=class{constructor(){ut.set(this,void 0),ct.set(this,void 0),Z(this,ut,new Uint8Array,"f"),Z(this,ct,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?lt(e):e;Z(this,ut,fT([b(this,ut,"f"),n]),"f");let r=[],i;for(;(i=hD(b(this,ut,"f"),b(this,ct,"f")))!=null;){if(i.carriage&&b(this,ct,"f")==null){Z(this,ct,i.index,"f");continue}if(b(this,ct,"f")!=null&&(i.index!==b(this,ct,"f")+1||i.carriage)){r.push(Hp(b(this,ut,"f").subarray(0,b(this,ct,"f")-1))),Z(this,ut,b(this,ut,"f").subarray(b(this,ct,"f")),"f"),Z(this,ct,null,"f");continue}let s=b(this,ct,"f")!==null?i.preceding-1:i.preceding,o=Hp(b(this,ut,"f").subarray(0,s));r.push(o),Z(this,ut,b(this,ut,"f").subarray(i.index),"f"),Z(this,ct,null,"f")}return r}flush(){return b(this,ut,"f").length?this.decode(`
51
+ `):[]}};ut=new WeakMap,ct=new WeakMap;wr.NEWLINE_CHARS=new Set([`
52
+ `,"\r"]);wr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function hD(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function pT(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var du={off:0,error:200,warn:300,info:400,debug:500},Kp=(t,e,n)=>{if(t){if(KE(du,t))return t;Ce(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(du))}`)}};function Uo(){}function cu(t,e,n){return!e||du[t]>du[n]?Uo:e[t].bind(e)}var mD={error:Uo,warn:Uo,info:Uo,debug:Uo},hT=new WeakMap;function Ce(t){let e=t.logger,n=t.logLevel??"off";if(!e)return mD;let r=hT.get(e);if(r&&r[0]===n)return r[1];let i={error:cu("error",e,n),warn:cu("warn",e,n),info:cu("info",e,n),debug:cu("debug",e,n)};return hT.set(e,[n,i]),i}var gn=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Lo,je=class t{constructor(e,n,r){this.iterator=e,Lo.set(this,void 0),this.controller=n,Z(this,Lo,r,"f")}static fromSSEResponse(e,n,r,i){let s=!1,o=r?Ce(r):console;async function*l(){if(s)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let d=!1;try{for await(let c of gD(e,n))if(!d){if(c.data.startsWith("[DONE]")){d=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let f;try{f=JSON.parse(c.data)}catch(p){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),p}if(f&&f.error)throw new Ae(void 0,f.error,void 0,e.headers);yield i?{event:c.event,data:f}:f}else{let f;try{f=JSON.parse(c.data)}catch(p){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),p}if(c.event=="error")throw new Ae(void 0,f.error,f.message,void 0);yield{event:c.event,data:f}}}d=!0}catch(c){if(ko(c))return;throw c}finally{d||n.abort()}}return new t(l,n,r)}static fromReadableStream(e,n,r){let i=!1;async function*s(){let l=new wr,d=e.getReader(),c=!1,f,p=()=>{f??(f=d.cancel()),f.catch(()=>{})};n.signal.addEventListener("abort",p,{once:!0});try{if(n.signal.aborted){p();return}for(;;){let{value:h,done:m}=await d.read();if(m){c=!0;break}if(n.signal.aborted)return;for(let g of l.decode(h)){if(n.signal.aborted)return;yield g}}if(n.signal.aborted)return;for(let h of l.flush()){if(n.signal.aborted)return;yield h}}finally{n.signal.removeEventListener("abort",p),c||p(),d.releaseLock()}}async function*o(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{for await(let d of s())l||d&&(yield JSON.parse(d));l=!0}catch(d){if(n.signal.aborted||ko(d))return;throw d}finally{l||n.abort()}}return new t(o,n,r)}[(Lo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=r.next();e.push(o),n.push(o)}return s.shift()}});return[new t(()=>i(e),this.controller,b(this,Lo,"f")),new t(()=>i(n),this.controller,b(this,Lo,"f"))]}toReadableStream(){let e=this,n;return Up({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:i,done:s}=await n.next();if(s)return r.close();let o=lt(JSON.stringify(i)+`
53
+ `);r.enqueue(o)}catch(i){r.error(i)}},async cancel(){await n.return?.()}})}};async function*gD(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new W("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new W("Attempted to iterate over a response with no body");let n=new Wp,r=new wr,i=lu(t.body);for await(let s of _D(i))for(let o of r.decode(s)){let l=n.decode(o);l&&(yield l)}for(let s of r.flush()){let o=n.decode(s);o&&(yield o)}}async function*_D(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?lt(n):n,i=new Uint8Array(e.length+r.length);i.set(e),i.set(r,e.length),e=i;let s;for(;(s=pT(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Wp=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
54
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,i]=yD(e,":");return i.startsWith(" ")&&(i=i.substring(1)),n==="event"?this.event=i:n==="data"&&this.data.push(i),null}};function yD(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function fu(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:s}=e,o=await(async()=>{if(e.options.stream)return Ce(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):je.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let d=n.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let h=await n.json();return Jp(h,n)}return await n.text()})();return Ce(t).debug(`[${r}] response parsed`,gn({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-s})),o}function Jp(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Fo,Cr=class t extends Promise{constructor(e,n,r=fu){super(i=>{i(null)}),this.responsePromise=n,this.parseResponse=r,Fo.set(this,void 0),Z(this,Fo,e,"f")}_thenUnwrap(e){return new t(b(this,Fo,"f"),this.responsePromise,async(n,r)=>Jp(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(b(this,Fo,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Fo=new WeakMap;var pu,Hi=class{constructor(e,n,r,i){pu.set(this,void 0),Z(this,pu,e,"f"),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await b(this,pu,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(pu=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},Go=class extends Cr{constructor(e,n,r){super(e,n,async(i,s)=>new r(i,s.response,await fu(i,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},$e=class extends Hi{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},re=class extends Hi{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...ou(this.options.query),after:n}}:null}},ue=class extends Hi{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ou(this.options.query),after:e}}:null}},Pe=class extends Hi{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ou(this.options.query),after:e}}:null}};var ED={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},TD="urn:ietf:params:oauth:grant-type:token-exchange",hu=class{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??au()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),n={grant_type:TD,subject_token:e,subject_token_type:ED[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let d=await r.text(),c;try{c=JSON.parse(d)}catch{}throw r.status===400||r.status===401||r.status===403?new Tr(r.status,c,r.headers):Ae.generate(r.status,c,`Token exchange failed with status ${r.status}`,r.headers)}let i=await r.json();if(typeof i!="object"||i===null||!("access_token"in i)||typeof i.access_token!="string"||i.access_token.trim().length===0)throw new W("Token exchange response missing 'access_token' field");let s=i.access_token,o=i.expires_in??3600,l=Date.now()+o*1e3;return this.cachedToken={token:s,expiresAt:l},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var mT=Symbol("brand.privateNullableHeaders"),wD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*CD(t){if(!t)return;if(mT in t){let{values:r,nulls:i}=t;yield*r.entries();for(let s of i)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Dp(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=Dp(r[1])?r[1]:[r[1]],o=!1;for(let l of s)l!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,l])}}var B=t=>{let e=new Headers,n=new Set;for(let r of t){let i=new Set;for(let[s,o]of CD(r)){if(!wD.test(s))throw new TypeError(`Header name must be a valid HTTP token ["${s}"]`);let l=s.toLowerCase();i.has(l)||(e.delete(l),i.add(l)),o===null?(e.delete(l),n.add(l)):(e.append(l,o),n.delete(l))}}return{[mT]:!0,values:e,nulls:n}};var _T=Symbol("brand.privateStreamingFile");function gu(t,e,n){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[_T]:!0,data:t,name:e,...n?.type?{type:n.type}:{}}}var Zp=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ji(t,e,n){return Zp(),new File(t,e??"unknown_file",n)}function Wi(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var zi=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",$n=async(t,e)=>Yp(t.body)?mu(t.body)?AT(t):{...t,body:await yT(t.body,e)}:t,Ve=async(t,e)=>mu(t.body)?AT(t):{...t,body:await yT(t.body,e)},gT=new WeakMap;function ID(t){let e=typeof t=="function"?t:t.fetch,n=gT.get(e);if(n)return n;let r=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new i(s).text()}catch{return!0}})();return gT.set(e,r),r}var yT=async(t,e)=>{if(!await ID(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,i])=>Qp(n,r,i))),n},_u=t=>t instanceof Blob&&"name"in t,jp=t=>typeof t=="object"&&t!==null&&"getReader"in t&&typeof t.getReader=="function",qo=t=>typeof t=="object"&&t!==null&&_T in t,eh=t=>typeof t=="object"&&t!==null&&(t instanceof Response||zi(t)||jp(t)||qo(t)||_u(t)),mu=t=>{if(qo(t)||zi(t)||jp(t))return!0;if(Array.isArray(t))return t.some(mu);if(t&&typeof t=="object"&&!_u(t)&&!(t instanceof Response)){for(let e in t)if(mu(t[e]))return!0}return!1},Yp=t=>{if(eh(t))return!0;if(Array.isArray(t))return t.some(Yp);if(t&&typeof t=="object"){for(let e in t)if(Yp(t[e]))return!0}return!1},AT=t=>{let e=`openai-${Math.random().toString(36).slice(2)}`,n=Oo(SD(t.body,e));return{...t,body:n,headers:B([{"content-type":`multipart/form-data; boundary=${e}`},t.headers])}};async function*SD(t,e){for await(let{key:n,value:r}of vD(t)){if(yield lt(`--${e}\r
55
+ `),eh(r)){let i=PD(r),s=RD(r);yield lt(`Content-Disposition: form-data; name="${zp(n)}"; filename="${zp(i)}"\r
56
+ Content-Type: ${s}\r
57
+ \r
58
+ `),yield*Ki(xD(r))}else yield lt(`Content-Disposition: form-data; name="${zp(n)}"\r
59
+ \r
60
+ ${String(r)}`);yield lt(`\r
61
+ `)}yield lt(`--${e}--\r
62
+ `)}async function*vD(t){if(!(!t||typeof t!="object"))for(let[e,n]of Object.entries(t))yield*Xp(e,n)}async function*Xp(t,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||eh(e))yield{key:t,value:e};else if(Array.isArray(e))for(let n of e)yield*Xp(t+"[]",n);else if(typeof e=="object")for(let[n,r]of Object.entries(e))yield*Xp(`${t}[${n}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function PD(t){return qo(t)?t.name:Wi(t)??"unknown_file"}function RD(t){return qo(t)?t.type||"application/octet-stream":_u(t)&&t.type?t.type:t instanceof Response&&t.headers.get("content-type")||"application/octet-stream"}function xD(t){return qo(t)?t.data:t}async function*Ki(t){if(typeof t=="string")yield lt(t);else if(ArrayBuffer.isView(t))yield new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)yield new Uint8Array(t);else if(t instanceof Response)t.body?yield*Ki(t.body):yield*Ki(await t.blob());else if(t instanceof Blob)typeof t.stream=="function"?yield*Ki(t.stream()):yield new Uint8Array(await t.arrayBuffer());else if(jp(t))for await(let e of lu(t))yield*Ki(e);else if(zi(t))for await(let e of t)yield*Ki(e);else throw new TypeError(`Invalid streaming file chunk: ${String(t)}`)}function zp(t){return t.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var Qp=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,Ji([await n.blob()],Wi(n)));else if(zi(n))t.append(e,Ji([await new Response(Oo(n)).blob()],Wi(n)));else if(_u(n))t.append(e,n,Wi(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Qp(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,i])=>Qp(t,`${e}[${r}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}};var ET=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",bD=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&ET(t),kD=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function yu(t,e,n){if(Zp(),t=await t,bD(t))return t instanceof File?t:Ji([await t.arrayBuffer()],t.name);if(kD(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Ji(await th(i),e,n)}let r=await th(t);if(e||(e=Wi(t)),!n?.type){let i=r.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(n={...n,type:i})}return Ji(r,e,n)}async function th(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(ET(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(zi(t))for await(let n of t)e.push(...await th(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${ND(t)}`)}return e}function ND(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var v=class{constructor(e){this._client=e}};function wT(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var TT=Object.freeze(Object.create(null)),DD=(t=wT)=>function(n,...r){if(n.length===1)return n[0];let i=!1,s=[],o=n.reduce((f,p,h)=>{/[?#]/.test(p)&&(i=!0);let m=r[h],g=(i?encodeURIComponent:t)(""+m);return h!==r.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??TT)??TT)?.toString)&&(g=m+"",s.push({start:f.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),f+p+(h===r.length?"":g)},""),l=o.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=d.exec(l))!==null;)s.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(s.sort((f,p)=>f.start-p.start),s.length>0){let f=0,p=s.reduce((h,m)=>{let g=" ".repeat(m.start-f),_="^".repeat(m.length);return f=m.start+m.length,h+g+_},"");throw new W(`Path parameters result in path with invalid segments:
63
+ ${s.map(h=>h.error).join(`
64
+ `)}
65
+ ${o}
66
+ ${p}`)}return o},E=DD(wT);var Ir=class extends v{list(e,n={},r){return this._client.getAPIList(E`/chat/completions/${e}/messages`,re,{query:n,...r,__security:{bearerAuth:!0}})}};function Bo(t){return t!==void 0&&"function"in t&&t.function!==void 0}function $o(t){return t?.$brand==="auto-parseable-response-format"}function Sr(t){return t?.$brand==="auto-parseable-tool"}function IT(t,e){return!e||!nh(e)?{...t,choices:t.choices.map(n=>(vT(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:Vo(t,e)}function Vo(t,e){let n=t.choices.map(r=>{if(r.finish_reason==="length")throw new $i;if(r.finish_reason==="content_filter")throw new Vi;return vT(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(i=>LD(e,i))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?UD(e,r.message.content):null}}});return{...t,choices:n}}function UD(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function LD(t,e){let n=t.tools?.find(r=>Bo(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Sr(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function ST(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let n=t.tools?.find(r=>Bo(r)&&r.function?.name===e.function.name);return Bo(n)&&(Sr(n)||n?.function.strict||!1)}function nh(t){return $o(t.response_format)?!0:t.tools?.some(e=>Sr(e)||e.type==="function"&&e.function.strict===!0)??!1}function vT(t){for(let e of t||[])if(e.type!=="function")throw new W(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function PT(t){for(let e of t??[]){if(e.type!=="function")throw new W(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new W(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _n=t=>t?.role==="assistant",Ho=t=>t?.role==="tool";var Ko,Au,Eu,Wo,Jo,Tu,zo,yn,wu,Yo,Cu,Iu,Yi,RT,rh,Vn=class{constructor(){Ko.add(this),this.controller=new AbortController,Au.set(this,void 0),Eu.set(this,()=>{}),Wo.set(this,()=>{}),Jo.set(this,void 0),Tu.set(this,()=>{}),zo.set(this,()=>{}),yn.set(this,{}),wu.set(this,[]),Yo.set(this,!1),Cu.set(this,!1),Iu.set(this,!1),Yi.set(this,!1),Z(this,Au,new Promise((e,n)=>{Z(this,Eu,e,"f"),Z(this,Wo,n,"f")}),"f"),Z(this,Jo,new Promise((e,n)=>{Z(this,Tu,e,"f"),Z(this,zo,n,"f")}),"f"),b(this,Au,"f").catch(()=>{}),b(this,Jo,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(n){b(this,Ko,"m",rh).call(this,n);return}this._emit("end")},b(this,Ko,"m",rh).bind(this))},0)}_connected(){this.ended||(b(this,Eu,"f").call(this),this._emit("connect"))}get ended(){return b(this,Yo,"f")}get errored(){return b(this,Cu,"f")}get aborted(){return b(this,Iu,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let n=()=>this.controller.abort();e.addEventListener("abort",n,{once:!0}),b(this,wu,"f").push({signal:e,listener:n})}on(e,n){return(b(this,yn,"f")[e]||(b(this,yn,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=b(this,yn,"f")[e];if(!r)return this;let i=r.findIndex(s=>s.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(b(this,yn,"f")[e]||(b(this,yn,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Z(this,Yi,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}events(e){let n=[],r=[],i=this.ended,s,o=!1,l=()=>({value:void 0,done:!0}),d=()=>{for(;r.length;)r.shift().resolve(l())},c=()=>{!s||o||!r.length||(o=!0,r.shift().reject(s))},f=()=>{this.off(e,p),this.off("end",m),e!=="error"&&this.off("error",h),e!=="abort"&&this.off("abort",h)},p=(...g)=>{if(i)return;let _=r.shift();_?_.resolve({value:g,done:!1}):n.push(g)},h=g=>{s=g,n.length||c()},m=()=>{i=!0,f(),n.length||(c(),d())};return i||(this.on(e,p),this.on("end",m),e!=="error"&&this.on("error",h),e!=="abort"&&this.on("abort",h)),{next:()=>{let g=n.shift();return g?Promise.resolve({value:g,done:!1}):s&&!o?(o=!0,Promise.reject(s)):i?Promise.resolve(l()):new Promise((_,y)=>{r.push({resolve:_,reject:y})})},return:()=>(i=!0,n.length=0,f(),d(),Promise.resolve(l())),[Symbol.asyncIterator](){return this}}}async done(){Z(this,Yi,!0,"f"),await b(this,Jo,"f")}_emit(e,...n){if(b(this,Yo,"f"))return;e==="end"&&(b(this,Ko,"m",RT).call(this),Z(this,Yo,!0,"f"),b(this,Tu,"f").call(this));let r=b(this,yn,"f")[e];if(r&&(b(this,yn,"f")[e]=r.filter(i=>!i.once),r.forEach(({listener:i})=>i(...n))),e==="abort"){let i=n[0];!b(this,Yi,"f")&&!r?.length&&Promise.reject(i),b(this,Wo,"f").call(this,i),b(this,zo,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=n[0];!b(this,Yi,"f")&&!r?.length&&Promise.reject(i),b(this,Wo,"f").call(this,i),b(this,zo,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Au=new WeakMap,Eu=new WeakMap,Wo=new WeakMap,Jo=new WeakMap,Tu=new WeakMap,zo=new WeakMap,yn=new WeakMap,wu=new WeakMap,Yo=new WeakMap,Cu=new WeakMap,Iu=new WeakMap,Yi=new WeakMap,Ko=new WeakSet,RT=function(){for(let{signal:e,listener:n}of b(this,wu,"f").splice(0))e.removeEventListener("abort",n)},rh=function(e){if(Z(this,Cu,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new we),e instanceof we)return Z(this,Iu,!0,"f"),this._emit("abort",e);if(e instanceof W)return this._emit("error",e);if(e instanceof Error){let n=new W(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new W(String(e)))};function xT(t){return typeof t.parse=="function"}var ze,ih,Su,sh,oh,ah,bT,kT,FD=10;function GD(t){for(let e of t.choices)for(let n of e.message.tool_calls??[])n.id||(n.id=`call_${Er()}`)}function qD(t){if(!_n(t))return t;let e={role:"assistant"};return t.audio!=null&&(e.audio={id:t.audio.id}),t.content!==void 0&&(e.content=t.content),t.function_call!=null&&(e.function_call=t.function_call),t.name!==void 0&&(e.name=t.name),t.refusal!=null&&(e.refusal=t.refusal),t.tool_calls!==void 0&&(e.tool_calls=t.tool_calls.map(n=>n.type==="custom"?{id:n.id,type:n.type,custom:{input:n.custom.input,name:n.custom.name}}:{id:n.id,type:n.type,function:{arguments:n.function.arguments,name:n.function.name}})),e}var Xi=class extends Vn{constructor(){super(...arguments),ze.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){GD(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),Ho(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_n(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new W("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),b(this,ze,"m",ih).call(this)}async finalMessage(){return await this.done(),b(this,ze,"m",Su).call(this)}async finalFunctionToolCall(){return await this.done(),b(this,ze,"m",sh).call(this)}async finalFunctionToolCallResult(){return await this.done(),b(this,ze,"m",oh).call(this)}async totalUsage(){return await this.done(),b(this,ze,"m",ah).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let n=b(this,ze,"m",Su).call(this);n&&this._emit("finalMessage",n);let r=b(this,ze,"m",ih).call(this);r&&this._emit("finalContent",r);let i=b(this,ze,"m",sh).call(this);i&&this._emit("finalFunctionToolCall",i);let s=b(this,ze,"m",oh).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",b(this,ze,"m",ah).call(this))}async _createChatCompletion(e,n,r){this._listenForAbort(r?.signal),b(this,ze,"m",bT).call(this,n);let i=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vo(i,n))}async _runChatCompletion(e,n,r){for(let i of n.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r,i){let s="tool",{tool_choice:o="auto",stream:l,toolContext:d,...c}=n,f=d,p=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:h=FD,afterCompletion:m}=i||{},g=n.tools.map(C=>{if(Sr(C)){if(!C.$callback)throw new W("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:C.$callback,name:C.function.name,description:C.function.description||"",parameters:C.function.parameters,parse:C.$parseRaw,strict:!0}}}return C}),_={};for(let C of g)C.type==="function"&&(_[C.function.name||C.function.function.name]=C.function);let y="tools"in n?g.map(C=>C.type==="function"?{type:"function",function:{name:C.function.name||C.function.function.name,parameters:C.function.parameters,description:C.function.description,strict:C.function.strict}}:C):void 0;for(let C of n.messages)this._addMessage(C,!1);let T=async C=>{if(C.type!=="function")return{message:void 0,functionCalled:!1};let R=C.id,{name:x,arguments:G}=C.function,S=_[x];if(!S){let N=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(_).map(K=>JSON.stringify(K)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:R,content:N},functionCalled:!1}}if(p&&p!==x){let N=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:s,tool_call_id:R,content:N},functionCalled:!1}}let q;if(xT(S)){let N;try{N=await S.parse(G)}catch(K){let Q=K instanceof Error?K.message:String(K);return{message:{role:s,tool_call_id:R,content:Q},functionCalled:!1}}q=await S.function(N,r,f)}else q=await S.function(G,r,f);let $=b(this,ze,"m",kT).call(this,q);return{message:{role:s,tool_call_id:R,content:$},functionCalled:!0}};for(let C=0;C<h;++C){let R=await this._createChatCompletion(e,{...c,tool_choice:o,tools:y,messages:this.messages.map(qD)},i),x=R.choices[0]?.message;if(!x)throw new W("missing message in ChatCompletion response");if(!x.tool_calls?.length){await m?.(R,r);return}if(p||n.parallel_tool_calls===!1)for(let G of x.tool_calls){let S=await T(G);if(S.message&&this._addMessage(S.message),p&&S.functionCalled){await m?.(R,r);return}}else{let G=await Promise.allSettled(x.tool_calls.map(T));for(let S of G)if(S.status==="rejected")throw S.reason;for(let S of G)S.status==="fulfilled"&&S.value.message&&this._addMessage(S.value.message)}await m?.(R,r)}}};ze=new WeakSet,ih=function(){return b(this,ze,"m",Su).call(this).content??null},Su=function(){let e=this.messages.length;for(;e-- >0;){let n=this.messages[e];if(_n(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new W("stream ended without producing a ChatCompletionMessage with role=assistant")},sh=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(_n(n)&&n?.tool_calls?.length)for(let r=n.tool_calls.length-1;r>=0;r--){let i=n.tool_calls[r];if(i?.type==="function")return i.function}}},oh=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(Ho(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(i=>i.type==="function"&&i.id===n.tool_call_id)))return n.content}},ah=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},bT=function(e){if(e.n!=null&&e.n>1)throw new W("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},kT=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Xo=class t extends Xi{static runTools(e,n,r){let i=new t,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,n,i,s)),i}_addMessage(e,n=!0){super._addMessage(e,n),_n(e)&&e.content&&this._emit("content",e.content)}};var Me={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},lh=class extends Error{},uh=class extends Error{};function BD(t,e=Me.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return $D(t.trim(),e)}var $D=(t,e)=>{let n=t.length,r=0,i=h=>{throw new lh(`${h} at position ${r}`)},s=h=>{throw new uh(`${h} at position ${r}`)},o=()=>(p(),r>=n&&i("Unexpected end of input"),t[r]==='"'?l():t[r]==="{"?d():t[r]==="["?c():t.substring(r,r+4)==="null"||Me.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||Me.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||Me.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||Me.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||Me.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||Me.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):f()),l=()=>{let h=r,m=!1;for(r++;r<n&&(t[r]!=='"'||m&&t[r-1]==="\\");)m=t[r]==="\\"?!m:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(h,++r-Number(m)))}catch(g){s(String(g))}else if(Me.STR&e)try{return JSON.parse(t.substring(h,r-Number(m))+'"')}catch{return JSON.parse(t.substring(h,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},d=()=>{r++,p();let h={};try{for(;t[r]!=="}";){if(p(),r>=n&&Me.OBJ&e)return h;let m=l();p(),r++;try{let g=o();Object.defineProperty(h,m,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(Me.OBJ&e)return h;throw g}p(),t[r]===","&&r++}}catch{if(Me.OBJ&e)return h;i("Expected '}' at end of object")}return r++,h},c=()=>{r++;let h=[];try{for(;t[r]!=="]";)h.push(o()),p(),t[r]===","&&r++}catch{if(Me.ARR&e)return h;i("Expected ']' at end of array")}return r++,h},f=()=>{if(r===0){t==="-"&&Me.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t)}catch(m){if(Me.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(m))}}let h=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(Me.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(t.substring(h,r))}catch{t.substring(h,r)==="-"&&Me.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t.substring(h,t.lastIndexOf("e")))}catch(g){s(String(g))}}},p=()=>{for(;r<n&&`
67
+ \r `.includes(t[r]);)r++};return o()},ch=t=>BD(t,Me.ALL^Me.NUM);var Re,An,Hn,Qi,Lt,dh,vu,fh,ph,hh,Qo,mh,NT,_h="chat.completion.chunk.message:";function MT(t,e,n){let r={type:"message",message:e,...n?{tool_call_ids:n}:{}};return{id:t.id,choices:[],created:t.created,model:t.model,object:`${_h}${JSON.stringify(r)}`}}function VD(t){return"type"in t&&t.type==="message"&&"message"in t||"object"in t&&typeof t.object=="string"&&t.object.startsWith(_h)}function HD(t){return"type"in t?t:JSON.parse(t.object.slice(_h.length))}var vr=class t extends Xi{constructor(e){super(),Re.add(this),An.set(this,void 0),Hn.set(this,void 0),Qi.set(this,void 0),Lt.set(this,void 0),Z(this,An,e,"f"),Z(this,Hn,new Set,"f"),Z(this,Qi,[],"f")}get currentChatCompletionSnapshot(){return b(this,Lt,"f")}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){let i=new t(n);return i._run(()=>i._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion,this._listenForAbort(r?.signal),b(this,Re,"m",dh).call(this);let i=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let s of i)b(this,Re,"m",fh).call(this,s);if(i.controller.signal?.aborted)throw new we;return this._addChatCompletion(b(this,Re,"m",Qo).call(this))}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),b(this,Re,"m",dh).call(this),this._connected();let r=je.fromReadableStream(e,this.controller),i;for await(let o of r){if(VD(o)){let d=HD(o);if(b(this,Lt,"f")){let c=b(this,Lt,"f").choices[0]?.message.tool_calls;for(let[f,p]of d.tool_call_ids?.entries()??[]){let h=c?.[f];h&&p&&(h.id=p)}this._addChatCompletion(b(this,Re,"m",Qo).call(this)),i=void 0}this._addMessage(d.message);continue}let l=o;i&&l.id&&i!==l.id&&this._addChatCompletion(b(this,Re,"m",Qo).call(this)),b(this,Re,"m",fh).call(this,l),l.id&&(i=l.id)}if(r.controller.signal?.aborted)throw new we;if(b(this,Lt,"f"))return this._addChatCompletion(b(this,Re,"m",Qo).call(this));let s=this._chatCompletions[this._chatCompletions.length-1];if(s)return s;throw new W("request ended without sending any chunks")}[(An=new WeakMap,Hn=new WeakMap,Qi=new WeakMap,Lt=new WeakMap,Re=new WeakSet,dh=function(){this.ended||(Z(this,Hn,new Set,"f"),Z(this,Lt,void 0,"f"))},vu=function(n){let r=b(this,Qi,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},b(this,Qi,"f")[n.index]=r,r)},fh=function(n){if(this.ended)return;let r=b(this,Re,"m",NT).call(this,n);this._emit("chunk",n,r);for(let i of n.choices){let s=r.choices[i.index],{delta:o}=i;o?.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.content,s.message.content),this._emit("content.delta",{delta:o.content,snapshot:s.message.content,parsed:s.message.parsed})),o?.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.refusal,snapshot:s.message.refusal}),i.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:s.logprobs?.content??[]}),i.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let l=b(this,Re,"m",vu).call(this,s);s.finish_reason&&(b(this,Re,"m",hh).call(this,s),l.current_tool_call_index!=null&&b(this,Re,"m",ph).call(this,s,l.current_tool_call_index));for(let d of o?.tool_calls??[])l.current_tool_call_index!==d.index&&(b(this,Re,"m",hh).call(this,s),l.current_tool_call_index!=null&&b(this,Re,"m",ph).call(this,s,l.current_tool_call_index)),l.current_tool_call_index=d.index;for(let d of o?.tool_calls??[]){let c=s.message.tool_calls?.[d.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:d.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:d.function?.arguments??""}):(c?.type,void 0))}}},ph=function(n,r){if(b(this,Re,"m",vu).call(this,n).done_tool_calls.has(r))return;let s=n.message.tool_calls?.[r];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let o=b(this,An,"f")?.tools?.find(l=>Bo(l)&&l.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:r,arguments:s.function.arguments,parsed_arguments:Sr(o)?o.$parseRaw(s.function.arguments):o?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},hh=function(n){let r=b(this,Re,"m",vu).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;let i=b(this,Re,"m",mh).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Qo=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let n=b(this,Lt,"f");if(!n)throw new W("request ended without sending any chunks");let r=b(this,Hn,"f");return Z(this,Hn,new Set,"f"),Z(this,Lt,void 0,"f"),Z(this,Qi,[],"f"),KD(n,b(this,An,"f"),r)},mh=function(){let n=b(this,An,"f")?.response_format;return $o(n)?n:null},NT=function(n){var r,i,s,o,l;let d=b(this,Lt,"f"),{choices:c,...f}=n;d?n.id&&Object.assign(d,f):d=Z(this,Lt,{...f,choices:[]},"f");for(let{delta:p,finish_reason:h,index:m,logprobs:g=null,..._}of n.choices){let y=d.choices[m];if(y||(y=d.choices[m]={finish_reason:h,index:m,message:{},logprobs:g,..._}),g)if(!y.logprobs)y.logprobs=Object.assign({},g);else{let{content:$,refusal:N,...K}=g;Object.assign(y.logprobs,K),$&&((r=y.logprobs).content??(r.content=[]),y.logprobs.content.push(...$)),N&&((i=y.logprobs).refusal??(i.refusal=[]),y.logprobs.refusal.push(...N))}if(h&&(y.finish_reason=h,b(this,An,"f")&&nh(b(this,An,"f")))){if(h==="length")throw new $i;if(h==="content_filter")throw new Vi}if(Object.assign(y,_),!p)continue;b(this,Hn,"f").delete(m);let{audio:T,content:C,refusal:R,function_call:x,role:G,tool_calls:S,...q}=p;if(Object.assign(y.message,q),T?.expires_at!=null&&T.id==null&&T.data==null&&T.transcript==null&&C==null&&R==null&&x==null&&G==null&&S==null&&Object.keys(q).length===0&&b(this,Hn,"f").add(m),R&&(y.message.refusal=(y.message.refusal||"")+R),G&&(y.message.role=G),T){let $=(s=y.message).audio??(s.audio={});T.id!=null&&($.id=T.id),T.data!=null&&($.data=($.data??"")+T.data),T.transcript!=null&&($.transcript=($.transcript??"")+T.transcript),T.expires_at!=null&&($.expires_at=T.expires_at)}if(x&&(y.message.function_call?(x.name&&(y.message.function_call.name=x.name),x.arguments&&((o=y.message.function_call).arguments??(o.arguments=""),y.message.function_call.arguments+=x.arguments)):y.message.function_call=x),C&&(y.message.content=(y.message.content||"")+C,!y.message.refusal&&b(this,Re,"m",mh).call(this)&&(y.message.parsed=y.message.content.trim()?ch(y.message.content):null)),S){y.message.tool_calls||(y.message.tool_calls=[]);for(let{index:$,id:N,type:K,function:Q,...oe}of S){let ie=(l=y.message.tool_calls)[$]??(l[$]={});Object.assign(ie,oe),N&&(ie.id=N),K&&(ie.type=K),Q&&(ie.function??(ie.function={name:Q.name??"",arguments:""})),Q?.name&&(ie.function.name=Q.name),Q?.arguments&&(ie.function.arguments+=Q.arguments,ST(b(this,An,"f"),ie)&&(ie.function.parsed_arguments=ch(ie.function.arguments)))}}}return d},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("chunk",i=>{let s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(let i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,o)=>n.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function KD(t,e,n){let{id:r,choices:i,created:s,model:o,system_fingerprint:l,...d}=t,c={...d,id:r,choices:i.map(({message:f,finish_reason:p,index:h,logprobs:m,...g})=>{let{content:_=null,function_call:y,tool_calls:T,audio:C,...R}=f,x=p??(n.has(h)&&WD(C)?"stop":null);if(!x)throw new W(`missing finish_reason for choice ${h}`);let G=C?{audio:C}:{},S=f.role;if(!S)throw new W(`missing role for choice ${h}`);if(y){let{arguments:q,name:$}=y;if(q==null)throw new W(`missing function_call.arguments for choice ${h}`);if(!$)throw new W(`missing function_call.name for choice ${h}`);return{...g,message:{...G,content:_,function_call:{arguments:q,name:$},role:S,refusal:f.refusal??null},finish_reason:x,index:h,logprobs:m}}return T?{...g,index:h,finish_reason:x,logprobs:m,message:{...R,...G,role:S,content:_,refusal:f.refusal??null,tool_calls:T.map((q,$)=>{let{function:N,type:K,id:Q,...oe}=q,{arguments:ie,name:ae,...fe}=N||{};if(K==null)throw new W(`missing choices[${h}].tool_calls[${$}].type
68
+ ${gh(t)}`);if(ae==null)throw new W(`missing choices[${h}].tool_calls[${$}].function.name
69
+ ${gh(t)}`);if(ie==null)throw new W(`missing choices[${h}].tool_calls[${$}].function.arguments
70
+ ${gh(t)}`);return{...oe,id:Q||`call_${Er()}`,type:K,function:{...fe,name:ae,arguments:ie}}})}}:{...g,message:{...R,...G,content:_,role:S,refusal:f.refusal??null},finish_reason:x,index:h,logprobs:m}}),created:s,model:o,object:"chat.completion",...l?{system_fingerprint:l}:{}};return IT(c,e)}function WD(t){return t?.id!=null&&t.data!=null&&t.transcript!=null&&t.expires_at!=null}function gh(t){return JSON.stringify(t)}var Zo=class t extends vr{static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}toReadableStream(){let e=[],n=[],r=!1,i,s,o=c=>{let f=n.shift();f?f.resolve(c):e.push(c)};this.on("chunk",c=>{i=c,o(c)}),this.on("message",c=>{if(_n(c)){s=c.tool_calls?.map(f=>f.id);return}if(Ho(c)){if(!i)throw new W("cannot serialize a tool message before receiving any chunks");o(MT(i,c,s))}}),this.on("end",()=>{r=!0;for(let c of n)c.resolve(void 0);n.length=0}),this.on("abort",c=>{r=!0;for(let f of n)f.reject(c);n.length=0}),this.on("error",c=>{r=!0;for(let f of n)f.reject(c);n.length=0});let l=()=>({next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((f,p)=>n.push({resolve:f,reject:p})).then(f=>f?{value:f,done:!1}:{value:void 0,done:!0});let c=e.shift();return c?{value:c,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new je(l,this.controller).toReadableStream()}static runTools(e,n,r){let i=new t(n),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,n,i,s)),i}};var En=class extends v{constructor(){super(...arguments),this.messages=new Ir(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/chat/completions/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chat/completions",re,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}parse(e,n){return PT(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Vo(r,e))}runTools(e,n){return e.stream?Zo.runTools(this._client,e,n):Xo.runTools(this._client,e,n)}stream(e,n){return vr.createChatCompletion(this._client,e,n)}};En.Messages=Ir;var Kn=class extends v{constructor(){super(...arguments),this.completions=new En(this._client)}};Kn.Completions=En;var Zi=class extends v{create(e,n){return this._client.post("/organization/admin_api_keys",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/admin_api_keys",re,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ji=class extends v{list(e={},n){return this._client.getAPIList("/organization/audit_logs",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}};var es=class extends v{create(e,n){return this._client.post("/organization/certificates",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(E`/organization/certificates/${e}`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/certificates/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/certificates",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/certificates/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}activate(e,n){return this._client.getAPIList("/organization/certificates/activate",$e,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n){return this._client.getAPIList("/organization/certificates/deactivate",$e,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var ts=class extends v{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/data_retention",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}};var ns=class extends v{create(e,n){return this._client.post("/organization/invites",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/invites",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rs=class extends v{create(e,n){return this._client.post("/organization/roles",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/roles/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/roles",Pe,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var is=class extends v{create(e,n){return this._client.post("/organization/spend_alerts",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/spend_alerts/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/spend_alerts",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ss=class extends v{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/spend_limit",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var os=class extends v{audioSpeeches(e,n){return this._client.get("/organization/usage/audio_speeches",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,n){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,n){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}completions(e,n){return this._client.get("/organization/usage/completions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}costs(e,n){return this._client.get("/organization/costs",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}embeddings(e,n){return this._client.get("/organization/usage/embeddings",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,n){return this._client.get("/organization/usage/file_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}images(e,n){return this._client.get("/organization/usage/images",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}moderations(e,n){return this._client.get("/organization/usage/moderations",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,n){return this._client.get("/organization/usage/vector_stores",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,n){return this._client.get("/organization/usage/web_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}};var as=class extends v{create(e,n,r){return this._client.post(E`/organization/groups/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{group_id:i}=n;return this._client.get(E`/organization/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/groups/${e}/roles`,Pe,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:i}=n;return this._client.delete(E`/organization/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ls=class extends v{create(e,n,r){return this._client.post(E`/organization/groups/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{group_id:i}=n;return this._client.get(E`/organization/groups/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/groups/${e}/users`,Pe,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:i}=n;return this._client.delete(E`/organization/groups/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wn=class extends v{constructor(){super(...arguments),this.users=new ls(this._client),this.roles=new as(this._client)}create(e,n){return this._client.post("/organization/groups",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/groups/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/groups",Pe,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Wn.Users=ls;Wn.Roles=as;var us=class extends v{retrieve(e,n,r){let{project_id:i}=n;return this._client.get(E`/organization/projects/${i}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/api_keys`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/organization/projects/${i}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var cs=class extends v{list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/certificates`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,n,r){return this._client.getAPIList(E`/organization/projects/${e}/certificates/activate`,$e,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n,r){return this._client.getAPIList(E`/organization/projects/${e}/certificates/deactivate`,$e,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var ds=class extends v{retrieve(e,n){return this._client.get(E`/organization/projects/${e}/data_retention`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/projects/${e}/data_retention`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}};var fs=class extends v{retrieve(e,n){return this._client.get(E`/organization/projects/${e}/hosted_tool_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/projects/${e}/hosted_tool_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}};var ps=class extends v{retrieve(e,n){return this._client.get(E`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/projects/${e}/model_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}};var hs=class extends v{listRateLimits(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/rate_limits`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/organization/projects/${i}/rate_limits/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}};var ms=class extends v{create(e,n,r){return this._client.post(E`/projects/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i}=n;return this._client.get(E`/projects/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/projects/${i}/roles/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/projects/${e}/roles`,Pe,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/projects/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var gs=class extends v{create(e,n,r){return this._client.post(E`/organization/projects/${e}/spend_alerts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i}=n;return this._client.get(E`/organization/projects/${i}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/organization/projects/${i}/spend_alerts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/spend_alerts`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/organization/projects/${i}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var _s=class extends v{retrieve(e,n){return this._client.get(E`/organization/projects/${e}/spend_limit`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/projects/${e}/spend_limit`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/projects/${e}/spend_limit`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ys=class extends v{create(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/projects/${i}/groups/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i,group_id:s}=n;return this._client.get(E`/projects/${i}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:i,...s}=n;return this._client.getAPIList(E`/projects/${i}/groups/${e}/roles`,Pe,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i,group_id:s}=n;return this._client.delete(E`/projects/${i}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Pr=class extends v{constructor(){super(...arguments),this.roles=new ys(this._client)}create(e,n,r){return this._client.post(E`/organization/projects/${e}/groups`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i,...s}=n;return this._client.get(E`/organization/projects/${i}/groups/${e}`,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/groups`,Pe,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/organization/projects/${i}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Pr.Roles=ys;var As=class extends v{create(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/organization/projects/${i}/service_accounts/${e}/api_keys`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}};var Rr=class extends v{constructor(){super(...arguments),this.apiKeys=new As(this._client)}create(e,n,r){return this._client.post(E`/organization/projects/${e}/service_accounts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i}=n;return this._client.get(E`/organization/projects/${i}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/organization/projects/${i}/service_accounts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/service_accounts`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/organization/projects/${i}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Rr.APIKeys=As;var Es=class extends v{create(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/projects/${i}/users/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i,user_id:s}=n;return this._client.get(E`/projects/${i}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:i,...s}=n;return this._client.getAPIList(E`/projects/${i}/users/${e}/roles`,Pe,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i,user_id:s}=n;return this._client.delete(E`/projects/${i}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var xr=class extends v{constructor(){super(...arguments),this.roles=new Es(this._client)}create(e,n,r){return this._client.post(E`/organization/projects/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:i}=n;return this._client.get(E`/organization/projects/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:i,...s}=n;return this._client.post(E`/organization/projects/${i}/users/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/projects/${e}/users`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:i}=n;return this._client.delete(E`/organization/projects/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};xr.Roles=Es;var De=class extends v{constructor(){super(...arguments),this.users=new xr(this._client),this.serviceAccounts=new Rr(this._client),this.apiKeys=new us(this._client),this.rateLimits=new hs(this._client),this.modelPermissions=new ps(this._client),this.hostedToolPermissions=new fs(this._client),this.groups=new Pr(this._client),this.roles=new ms(this._client),this.dataRetention=new ds(this._client),this.spendLimit=new _s(this._client),this.spendAlerts=new gs(this._client),this.certificates=new cs(this._client)}create(e,n){return this._client.post("/organization/projects",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(E`/organization/projects/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/projects/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/projects",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}archive(e,n){return this._client.post(E`/organization/projects/${e}/archive`,{...n,__security:{adminAPIKeyAuth:!0}})}};De.Users=xr;De.ServiceAccounts=Rr;De.APIKeys=us;De.RateLimits=hs;De.ModelPermissions=ps;De.HostedToolPermissions=fs;De.Groups=Pr;De.Roles=ms;De.DataRetention=ds;De.SpendLimit=_s;De.SpendAlerts=gs;De.Certificates=cs;var Ts=class extends v{create(e,n,r){return this._client.post(E`/organization/users/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{user_id:i}=n;return this._client.get(E`/organization/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/organization/users/${e}/roles`,Pe,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{user_id:i}=n;return this._client.delete(E`/organization/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var br=class extends v{constructor(){super(...arguments),this.roles=new Ts(this._client)}retrieve(e,n){return this._client.get(E`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(E`/organization/users/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/users",ue,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(E`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};br.Roles=Ts;var Oe=class extends v{constructor(){super(...arguments),this.auditLogs=new ji(this._client),this.adminAPIKeys=new Zi(this._client),this.usage=new os(this._client),this.invites=new ns(this._client),this.users=new br(this._client),this.groups=new Wn(this._client),this.roles=new rs(this._client),this.dataRetention=new ts(this._client),this.spendLimit=new ss(this._client),this.spendAlerts=new is(this._client),this.certificates=new es(this._client),this.projects=new De(this._client)}};Oe.AuditLogs=ji;Oe.AdminAPIKeys=Zi;Oe.Usage=os;Oe.Invites=ns;Oe.Users=br;Oe.Groups=Wn;Oe.Roles=rs;Oe.DataRetention=ts;Oe.SpendLimit=ss;Oe.SpendAlerts=is;Oe.Certificates=es;Oe.Projects=De;var Jn=class extends v{constructor(){super(...arguments),this.organization=new Oe(this._client)}};Jn.Organization=Oe;var ws=class extends v{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:B([{Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Cs=class extends v{create(e,n){return this._client.post("/audio/transcriptions",Ve({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Is=class extends v{create(e,n){return this._client.post("/audio/translations",Ve({body:e,...n,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var en=class extends v{constructor(){super(...arguments),this.transcriptions=new Cs(this._client),this.translations=new Is(this._client),this.speech=new ws(this._client)}};en.Transcriptions=Cs;en.Translations=Is;en.Speech=ws;var kr=class extends v{create(e,n){return this._client.post("/batches",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/batches/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/batches",re,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(E`/batches/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}};var Ss=class extends v{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/assistants/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/assistants/${e}`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/assistants",re,{query:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/assistants/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var vs=class extends v{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ps=class extends v{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var zn=class extends v{constructor(){super(...arguments),this.sessions=new vs(this._client),this.transcriptionSessions=new Ps(this._client)}};zn.Sessions=vs;zn.TranscriptionSessions=Ps;var Rs=class extends v{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(E`/chatkit/sessions/${e}/cancel`,{...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var xs=class extends v{retrieve(e,n){return this._client.get(E`/chatkit/threads/${e}`,{...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chatkit/threads",ue,{query:e,...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/chatkit/threads/${e}`,{...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}listItems(e,n={},r){return this._client.getAPIList(E`/chatkit/threads/${e}/items`,ue,{query:n,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Yn=class extends v{constructor(){super(...arguments),this.sessions=new Rs(this._client),this.threads=new xs(this._client)}};Yn.Sessions=Rs;Yn.Threads=xs;var bs=class extends v{list(e,n={},r){let{betas:i,...s}=n??{};return this._client.getAPIList(E`/responses/${e}/input_items?beta=true`,re,{query:s,...r,headers:B([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var ks=class extends v{count(e={},n){let{betas:r,...i}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:i,...n,headers:B([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};var Xn=class extends v{constructor(){super(...arguments),this.inputItems=new bs(this._client),this.inputTokens=new ks(this._client)}create(e,n){let{betas:r,...i}=e;return this._client.post("/responses?beta=true",{body:i,...n,headers:B([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n={},r){let{betas:i,...s}=n??{};return this._client.get(E`/responses/${e}?beta=true`,{query:s,...r,headers:B([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},r?.headers]),stream:n?.stream??!1,__security:{bearerAuth:!0}})}delete(e,n={},r){let{betas:i}=n??{};return this._client.delete(E`/responses/${e}?beta=true`,{...r,headers:B([{Accept:"*/*",...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n={},r){let{betas:i}=n??{};return this._client.post(E`/responses/${e}/cancel?beta=true`,{...r,headers:B([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,n){let{betas:r,...i}=e;return this._client.post("/responses/compact?beta=true",{body:i,...n,headers:B([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};Xn.InputItems=bs;Xn.InputTokens=ks;var Ns=class extends v{create(e,n,r){return this._client.post(E`/threads/${e}/messages`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:i}=n;return this._client.get(E`/threads/${i}/messages/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:i,...s}=n;return this._client.post(E`/threads/${i}/messages/${e}`,{body:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/threads/${e}/messages`,re,{query:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{thread_id:i}=n;return this._client.delete(E`/threads/${i}/messages/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ms=class extends v{retrieve(e,n,r){let{thread_id:i,run_id:s,...o}=n;return this._client.get(E`/threads/${i}/runs/${s}/steps/${e}`,{query:o,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n,r){let{thread_id:i,...s}=n;return this._client.getAPIList(E`/threads/${i}/runs/${e}/steps`,re,{query:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var DT=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),n=e.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);return Array.from(new Float32Array(r.buffer))}};var Ft=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var Fe,Mr,yh,tn,Pu,Gt,Dr,Ds,Nr,bu,dt,Ru,xu,ta,jo,ea,OT,UT,LT,FT,GT,qT,BT,Tn=class extends Vn{constructor(){super(...arguments),Fe.add(this),yh.set(this,[]),tn.set(this,{}),Pu.set(this,{}),Gt.set(this,void 0),Dr.set(this,void 0),Ds.set(this,void 0),Nr.set(this,void 0),bu.set(this,void 0),dt.set(this,void 0),Ru.set(this,void 0),xu.set(this,void 0),ta.set(this,void 0)}[(yh=new WeakMap,tn=new WeakMap,Pu=new WeakMap,Gt=new WeakMap,Dr=new WeakMap,Ds=new WeakMap,Nr=new WeakMap,bu=new WeakMap,dt=new WeakMap,Ru=new WeakMap,xu=new WeakMap,ta=new WeakMap,Fe=new WeakSet,Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",i=>{let s=structuredClone(i),o=n.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,o)=>n.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let n=new Mr;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),this._connected();let r=je.fromReadableStream(e,this.controller);for await(let i of r)b(this,Fe,"m",jo).call(this,i);if(r.controller.signal?.aborted)throw new we;return this._addRun(b(this,Fe,"m",ea).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,i){let s=new Mr;return s._run(()=>s._runToolAssistantStream(e,n,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,n,r,i){this._listenForAbort(i?.signal);let s={...r,stream:!0},o=await e.submitToolOutputs(n,s,{...i,signal:this.controller.signal});this._connected();for await(let l of o)b(this,Fe,"m",jo).call(this,l);if(o.controller.signal?.aborted)throw new we;return this._addRun(b(this,Fe,"m",ea).call(this))}static createThreadAssistantStream(e,n,r){let i=new Mr;return i._run(()=>i._threadAssistantStream(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,n,r,i){let s=new Mr;return s._run(()=>s._runAssistantStream(e,n,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return b(this,Ru,"f")}currentRun(){return b(this,xu,"f")}currentMessageSnapshot(){return b(this,Gt,"f")}currentRunStepSnapshot(){return b(this,ta,"f")}async finalRunSteps(){return await this.done(),Object.values(b(this,tn,"f"))}async finalMessages(){return await this.done(),Object.values(b(this,Pu,"f"))}async finalRun(){if(await this.done(),!b(this,Dr,"f"))throw Error("Final run was not received.");return b(this,Dr,"f")}async _createThreadAssistantStream(e,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},s=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(let o of s)b(this,Fe,"m",jo).call(this,o);if(s.controller.signal?.aborted)throw new we;return this._addRun(b(this,Fe,"m",ea).call(this))}async _createAssistantStream(e,n,r,i){this._listenForAbort(i?.signal);let s={...r,stream:!0},o=await e.create(n,s,{...i,signal:this.controller.signal});this._connected();for await(let l of o)b(this,Fe,"m",jo).call(this,l);if(o.controller.signal?.aborted)throw new we;return this._addRun(b(this,Fe,"m",ea).call(this))}static accumulateDelta(e,n){for(let[r,i]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=i;continue}let s=e[r];if(s==null){e[r]=i;continue}if(r==="index"||r==="type"){e[r]=i;continue}if(typeof s=="string"&&typeof i=="string")s+=i;else if(typeof s=="number"&&typeof i=="number")s+=i;else if(Do(s)&&Do(i))s=this.accumulateDelta(s,i);else if(Array.isArray(s)&&Array.isArray(i)){if(s.every(o=>typeof o=="string"||typeof o=="number")){s.push(...i);continue}for(let o of i){if(!Do(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let l=o.index;if(l==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let d=s[l];d==null?s[l]=o:s[l]=this.accumulateDelta(d,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${s}`);e[r]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,i){return await this._createAssistantStream(n,e,r,i)}async _runToolAssistantStream(e,n,r,i){return await this._createToolAssistantStream(n,e,r,i)}};Mr=Tn,jo=function(e){if(!this.ended)switch(Z(this,Ru,e,"f"),b(this,Fe,"m",LT).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":b(this,Fe,"m",BT).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":b(this,Fe,"m",UT).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":b(this,Fe,"m",OT).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ea=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");if(!b(this,Dr,"f"))throw Error("Final run has not been received");return b(this,Dr,"f")},OT=function(e){let[n,r]=b(this,Fe,"m",GT).call(this,e,b(this,Gt,"f"));Z(this,Gt,n,"f"),b(this,Pu,"f")[n.id]=n;for(let i of r){let s=n.content[i.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let s=i.text,o=n.content[i.index];if(o&&o.type=="text")this._emit("textDelta",s,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=b(this,Ds,"f")){if(b(this,Nr,"f"))switch(b(this,Nr,"f").type){case"text":this._emit("textDone",b(this,Nr,"f").text,b(this,Gt,"f"));break;case"image_file":this._emit("imageFileDone",b(this,Nr,"f").image_file,b(this,Gt,"f"));break}Z(this,Ds,i.index,"f")}Z(this,Nr,n.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(b(this,Ds,"f")!==void 0){let i=e.data.content[b(this,Ds,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,b(this,Gt,"f"));break;case"text":this._emit("textDone",i.text,b(this,Gt,"f"));break}}b(this,Gt,"f")&&this._emit("messageDone",e.data),Z(this,Gt,void 0,"f")}},UT=function(e){let n=b(this,Fe,"m",FT).call(this,e);switch(Z(this,ta,n,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(let s of r.step_details.tool_calls)s.index==b(this,bu,"f")?this._emit("toolCallDelta",s,n.step_details.tool_calls[s.index]):(b(this,dt,"f")&&this._emit("toolCallDone",b(this,dt,"f")),Z(this,bu,s.index,"f"),Z(this,dt,n.step_details.tool_calls[s.index],"f"),b(this,dt,"f")&&this._emit("toolCallCreated",b(this,dt,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Z(this,ta,void 0,"f"),e.data.step_details.type=="tool_calls"&&b(this,dt,"f")&&(this._emit("toolCallDone",b(this,dt,"f")),Z(this,dt,void 0,"f")),this._emit("runStepDone",e.data,n);break;case"thread.run.step.in_progress":break}},LT=function(e){b(this,yh,"f").push(e),this._emit("event",e)},FT=function(e){switch(e.event){case"thread.run.step.created":return b(this,tn,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=b(this,tn,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let i=Mr.accumulateDelta(n,r.delta);b(this,tn,"f")[e.data.id]=i}return b(this,tn,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":b(this,tn,"f")[e.data.id]=e.data;break}if(b(this,tn,"f")[e.data.id])return b(this,tn,"f")[e.data.id];throw new Error("No snapshot available")},GT=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let s of i.delta.content)if(s.index in n.content){let o=n.content[s.index];n.content[s.index]=b(this,Fe,"m",qT).call(this,s,o)}else n.content[s.index]=s,r.push(s);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},qT=function(e,n){return Mr.accumulateDelta(n,e)},BT=function(e){switch(Z(this,xu,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Z(this,Dr,e.data,"f"),b(this,dt,"f")&&(this._emit("toolCallDone",b(this,dt,"f")),Z(this,dt,void 0,"f"));break;case"thread.run.cancelling":break}};var Or=class extends v{constructor(){super(...arguments),this.steps=new Ms(this._client)}create(e,n,r){let{include:i,...s}=n;return this._client.post(E`/threads/${e}/runs`,{query:{include:i},body:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:i}=n;return this._client.get(E`/threads/${i}/runs/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:i,...s}=n;return this._client.post(E`/threads/${i}/runs/${e}`,{body:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/threads/${e}/runs`,re,{query:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{thread_id:i}=n;return this._client.post(E`/threads/${i}/runs/${e}/cancel`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let i=await this.create(e,n,r);return await this.poll(i.id,{thread_id:e},r)}createAndStream(e,n,r){return Tn.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){let i=B([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(e,n,{...r,headers:{...r?.headers,...i}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let d=o.headers.get("openai-poll-after-ms");if(d){let c=parseInt(d);isNaN(c)||(l=c)}}await Zt(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,n,r){return Tn.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){let{thread_id:i,...s}=n;return this._client.post(E`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,n,r){let i=await this.submitToolOutputs(e,n,r);return await this.poll(i.id,n,r)}submitToolOutputsStream(e,n,r){return Tn.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};Or.Steps=Ms;var Qn=class extends v{constructor(){super(...arguments),this.runs=new Or(this._client),this.messages=new Ns(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/threads/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/threads/${e}`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/threads/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,n){let r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return Tn.createThreadAssistantStream(e,this._client.beta.threads,n)}};Qn.Runs=Or;Qn.Messages=Ns;var Ct=class extends v{constructor(){super(...arguments),this.realtime=new zn(this._client),this.responses=new Xn(this._client),this.chatkit=new Yn(this._client),this.assistants=new Ss(this._client),this.threads=new Qn(this._client)}};Ct.Realtime=zn;Ct.Responses=Xn;Ct.ChatKit=Yn;Ct.Assistants=Ss;Ct.Threads=Qn;var Ur=class extends v{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Os=class extends v{retrieve(e,n,r){let{container_id:i}=n;return this._client.get(E`/containers/${i}/files/${e}/content`,{...r,headers:B([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Lr=class extends v{constructor(){super(...arguments),this.content=new Os(this._client)}create(e,n,r){return this._client.post(E`/containers/${e}/files`,$n({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{container_id:i}=n;return this._client.get(E`/containers/${i}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/containers/${e}/files`,re,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{container_id:i}=n;return this._client.delete(E`/containers/${i}/files/${e}`,{...r,headers:B([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Lr.Content=Os;var Zn=class extends v{constructor(){super(...arguments),this.files=new Lr(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/containers/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/containers",re,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/containers/${e}`,{...n,headers:B([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Zn.Files=Lr;var Us=class extends v{create(e,n,r){let{include:i,...s}=n;return this._client.post(E`/conversations/${e}/items`,{query:{include:i},body:s,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{conversation_id:i,...s}=n;return this._client.get(E`/conversations/${i}/items/${e}`,{query:s,...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/conversations/${e}/items`,ue,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{conversation_id:i}=n;return this._client.delete(E`/conversations/${i}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var jn=class extends v{constructor(){super(...arguments),this.items=new Us(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/conversations/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}};jn.Items=Us;var Fr=class extends v{create(e,n){let r=!!e.encoding_format,i=r?e.encoding_format:"base64";r&&Ce(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:i},...n,__security:{bearerAuth:!0}});return r?s:(Ce(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(o=>(o&&o.data&&o.data.forEach(l=>{let d=l.embedding;l.embedding=DT(d)}),o)))}};var Ls=class extends v{retrieve(e,n,r){let{eval_id:i,run_id:s}=n;return this._client.get(E`/evals/${i}/runs/${s}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n,r){let{eval_id:i,...s}=n;return this._client.getAPIList(E`/evals/${i}/runs/${e}/output_items`,re,{query:s,...r,__security:{bearerAuth:!0}})}};var Gr=class extends v{constructor(){super(...arguments),this.outputItems=new Ls(this._client)}create(e,n,r){return this._client.post(E`/evals/${e}/runs`,{body:n,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{eval_id:i}=n;return this._client.get(E`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/evals/${e}/runs`,re,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{eval_id:i}=n;return this._client.delete(E`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,n,r){let{eval_id:i}=n;return this._client.post(E`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};Gr.OutputItems=Ls;var er=class extends v{constructor(){super(...arguments),this.runs=new Gr(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/evals/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/evals",re,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}};er.Runs=Gr;var qr=class extends v{create(e,n){return this._client.post("/files",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(E`/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/files",re,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/files/${e}`,{...n,__security:{bearerAuth:!0}})}content(e,n){return this._client.get(E`/files/${e}/content`,{...n,headers:B([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),s=Date.now(),o=await this.retrieve(e);for(;!o.status||!i.has(o.status);)if(await Zt(n),o=await this.retrieve(e),Date.now()-s>r)throw new qn({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}};var Fs=class extends v{};var Gs=class extends v{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n,__security:{bearerAuth:!0}})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n,__security:{bearerAuth:!0}})}};var Br=class extends v{constructor(){super(...arguments),this.graders=new Gs(this._client)}};Br.Graders=Gs;var qs=class extends v{create(e,n,r){return this._client.getAPIList(E`/fine_tuning/checkpoints/${e}/permissions`,$e,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(E`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/fine_tuning/checkpoints/${e}/permissions`,ue,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{fine_tuned_model_checkpoint:i}=n;return this._client.delete(E`/fine_tuning/checkpoints/${i}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var $r=class extends v{constructor(){super(...arguments),this.permissions=new qs(this._client)}};$r.Permissions=qs;var Bs=class extends v{list(e,n={},r){return this._client.getAPIList(E`/fine_tuning/jobs/${e}/checkpoints`,re,{query:n,...r,__security:{bearerAuth:!0}})}};var Vr=class extends v{constructor(){super(...arguments),this.checkpoints=new Bs(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/fine_tuning/jobs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",re,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(E`/fine_tuning/jobs/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}listEvents(e,n={},r){return this._client.getAPIList(E`/fine_tuning/jobs/${e}/events`,re,{query:n,...r,__security:{bearerAuth:!0}})}pause(e,n){return this._client.post(E`/fine_tuning/jobs/${e}/pause`,{...n,__security:{bearerAuth:!0}})}resume(e,n){return this._client.post(E`/fine_tuning/jobs/${e}/resume`,{...n,__security:{bearerAuth:!0}})}};Vr.Checkpoints=Bs;var qt=class extends v{constructor(){super(...arguments),this.methods=new Fs(this._client),this.jobs=new Vr(this._client),this.checkpoints=new $r(this._client),this.alpha=new Br(this._client)}};qt.Methods=Fs;qt.Jobs=Vr;qt.Checkpoints=$r;qt.Alpha=Br;var $s=class extends v{};var tr=class extends v{constructor(){super(...arguments),this.graderModels=new $s(this._client)}};tr.GraderModels=$s;var Hr=class extends v{createVariation(e,n){return this._client.post("/images/variations",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}edit(e,n){return this._client.post("/images/edits",Ve({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Kr=class extends v{retrieve(e,n){return this._client.get(E`/models/${e}`,{...n,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",$e,{...e,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/models/${e}`,{...n,__security:{bearerAuth:!0}})}};var Wr=class extends v{create(e,n){return this._client.post("/moderations",{body:e,...n,__security:{bearerAuth:!0}})}};var Vs=class extends v{accept(e,n,r){return this._client.post(E`/realtime/calls/${e}/accept`,{body:n,...r,headers:B([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,n){return this._client.post(E`/realtime/calls/${e}/hangup`,{...n,headers:B([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}refer(e,n,r){return this._client.post(E`/realtime/calls/${e}/refer`,{body:n,...r,headers:B([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,n={},r){return this._client.post(E`/realtime/calls/${e}/reject`,{body:n,...r,headers:B([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Hs=class extends v{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n,__security:{bearerAuth:!0}})}};var wn=class extends v{constructor(){super(...arguments),this.clientSecrets=new Hs(this._client),this.calls=new Vs(this._client)}};wn.ClientSecrets=Hs;wn.Calls=Vs;function $T(t,e){if(!e||!iU(e)){let n={...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(i=>({...i,parsed:null}))}:r)};return HT(t,n)&&ft(n),n}return Ah(t,e)}function Ah(t,e){let n=!t.status||t.status==="completed",r=t.output.map(s=>{if(s.type==="function_call")return n?oU(e,s):{...s,parsed_arguments:null};if(s.type==="message"){let o=s.content.map(l=>l.type==="output_text"?{...l,parsed:n?rU(e,l.text):null}:l);return{...s,content:o}}return s}),i=Object.assign({},t,{output:r});return HT(t,i)&&ft(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let s of i.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),i}function rU(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function iU(t){return $o(t.text?.format)?!0:Array.isArray(t.tools)&&t.tools.some(e=>VT(e)||e.type==="function"&&e.strict===!0)}function VT(t){return t?.$brand==="auto-parseable-tool"}function sU(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function oU(t,e){let n=sU(t.tools??[],e.name);return{...e,...e,parsed_arguments:VT(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function HT(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function ft(t){let e=[];for(let n of t.output)if(n.type==="message")for(let r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}function WT(t,e){if(!e){if(t.type!=="response.created")throw new W(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return KT(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&ft(e);break}case"response.output_item.done":{le(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&ft(e);break}case"response.content_part.added":{let n=le(e,t.output_index),r=n.type,i=t.part;r==="message"&&i.type!=="reasoning_text"?(n.content.push(structuredClone(i)),i.type==="output_text"&&ft(e)):r==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(structuredClone(i)));break}case"response.content_part.done":{let n=le(e,t.output_index),r=t.part;if(n.type==="message"&&r.type!=="reasoning_text")It(n.content,t.content_index),n.content[t.content_index]=structuredClone(r),r.type==="output_text"&&ft(e);else if(n.type==="reasoning"&&r.type==="reasoning_text"){let i=n.content;if(!i)throw new W(`missing content at index ${t.content_index}`);It(i,t.content_index),i[t.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let n=le(e,t.output_index);if(n.type==="message"){let r=It(n.content,t.content_index);if(r.type!=="output_text")throw new W(`expected content to be 'output_text', got ${r.type}`);r.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let n=le(e,t.output_index);if(n.type==="message"){let r=It(n.content,t.content_index);if(r.type!=="output_text")throw new W(`expected content to be 'output_text', got ${r.type}`);r.text=t.text,ft(e)}break}case"response.output_text.annotation.added":{let n=le(e,t.output_index);if(n.type==="message"){let r=It(n.content,t.content_index);if(r.type!=="output_text")throw new W(`expected content to be 'output_text', got ${r.type}`);r.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let n=le(e,t.output_index);if(n.type==="message"){let r=It(n.content,t.content_index);if(r.type!=="refusal")throw new W(`expected content to be 'refusal', got ${r.type}`);r.refusal+=t.delta}break}case"response.refusal.done":{let n=le(e,t.output_index);if(n.type==="message"){let r=It(n.content,t.content_index);if(r.type!=="refusal")throw new W(`expected content to be 'refusal', got ${r.type}`);r.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let n=le(e,t.output_index);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.function_call_arguments.done":{let n=le(e,t.output_index);n.type==="function_call"&&(n.arguments=t.arguments);break}case"response.reasoning_text.delta":{let n=le(e,t.output_index);if(n.type==="reasoning"){if(!n.content)throw new W(`missing content at index ${t.content_index}`);let r=It(n.content,t.content_index);if(r.type!=="reasoning_text")throw new W(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=t.delta}break}case"response.reasoning_text.done":{let n=le(e,t.output_index);if(n.type==="reasoning"){if(!n.content)throw new W(`missing content at index ${t.content_index}`);let r=It(n.content,t.content_index);if(r.type!=="reasoning_text")throw new W(`expected content to be 'reasoning_text', got ${r.type}`);r.text=t.text}break}case"response.reasoning_summary_part.added":{let n=le(e,t.output_index);n.type==="reasoning"&&n.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let n=le(e,t.output_index);n.type==="reasoning"&&(It(n.summary,t.summary_index),n.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let n=le(e,t.output_index);if(n.type==="reasoning"){let r=It(n.summary,t.summary_index);r.text+=t.delta}break}case"response.reasoning_summary_text.done":{let n=le(e,t.output_index);if(n.type==="reasoning"){let r=It(n.summary,t.summary_index);r.text=t.text}break}case"response.custom_tool_call_input.delta":{let n=le(e,t.output_index);n.type==="custom_tool_call"&&(n.input+=t.delta);break}case"response.custom_tool_call_input.done":{let n=le(e,t.output_index);n.type==="custom_tool_call"&&(n.input=t.input);break}case"response.mcp_call_arguments.delta":{let n=le(e,t.output_index);n.type==="mcp_call"&&(n.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let n=le(e,t.output_index);n.type==="mcp_call"&&(n.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let n=le(e,t.output_index);n.type==="code_interpreter_call"&&(n.code=(n.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let n=le(e,t.output_index);n.type==="code_interpreter_call"&&(n.code=t.code);break}case"response.code_interpreter_call.in_progress":{let n=le(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let n=le(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="interpreting");break}case"response.code_interpreter_call.completed":{let n=le(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="completed");break}case"response.file_search_call.in_progress":{let n=le(e,t.output_index);n.type==="file_search_call"&&(n.status="in_progress");break}case"response.file_search_call.searching":{let n=le(e,t.output_index);n.type==="file_search_call"&&(n.status="searching");break}case"response.file_search_call.completed":{let n=le(e,t.output_index);n.type==="file_search_call"&&(n.status="completed");break}case"response.web_search_call.in_progress":{let n=le(e,t.output_index);n.type==="web_search_call"&&(n.status="in_progress");break}case"response.web_search_call.searching":{let n=le(e,t.output_index);n.type==="web_search_call"&&(n.status="searching");break}case"response.web_search_call.completed":{let n=le(e,t.output_index);n.type==="web_search_call"&&(n.status="completed");break}case"response.image_generation_call.in_progress":{let n=le(e,t.output_index);n.type==="image_generation_call"&&(n.status="in_progress");break}case"response.image_generation_call.generating":{let n=le(e,t.output_index);n.type==="image_generation_call"&&(n.status="generating");break}case"response.image_generation_call.completed":{let n=le(e,t.output_index);n.type==="image_generation_call"&&(n.status="completed");break}case"response.mcp_call.in_progress":{let n=le(e,t.output_index);n.type==="mcp_call"&&(n.status="in_progress");break}case"response.mcp_call.completed":{let n=le(e,t.output_index);n.type==="mcp_call"&&(n.status="completed");break}case"response.mcp_call.failed":{let n=le(e,t.output_index);n.type==="mcp_call"&&(n.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=KT(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:aU(t)}return e}function KT(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&ft(e),e}function le(t,e){let n=t.output[e];if(!n)throw new W(`missing output at index ${e}`);return n}function It(t,e){let n=t[e];if(!n)throw new W(`missing content at index ${e}`);return n}function aU(t){throw new W(`Unhandled response stream event: ${JSON.stringify(t)}`)}var nr,ku,Jr,Nu,Eh,Th,wh,Mu=class t extends Vn{constructor(e){super(),nr.add(this),ku.set(this,void 0),Jr.set(this,void 0),Nu.set(this,void 0),Z(this,ku,e,"f")}static createResponse(e,n,r){let i=new t(n);return i._run(()=>i._createOrRetrieveResponse(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}async _createOrRetrieveResponse(e,n,r){this._listenForAbort(r?.signal),b(this,nr,"m",Eh).call(this);let i,s=null;"response_id"in n?(i=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),s=n.starting_after??null):i=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let o of i)b(this,nr,"m",Th).call(this,o,s);if(i.controller.signal?.aborted)throw new we;return b(this,nr,"m",wh).call(this)}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),b(this,nr,"m",Eh).call(this),this._connected();let r=je.fromReadableStream(e,this.controller);for await(let i of r)b(this,nr,"m",Th).call(this,i,null);if(r.controller.signal?.aborted)throw new we;return b(this,nr,"m",wh).call(this)}[(ku=new WeakMap,Jr=new WeakMap,Nu=new WeakMap,nr=new WeakSet,Eh=function(){this.ended||Z(this,Jr,void 0,"f")},Th=function(n,r){if(this.ended)return;let i=(o,l)=>{(r==null||l.sequence_number>r)&&this._emit(o,l)},s=WT(n,b(this,Jr,"f"));switch(Z(this,Jr,s,"f"),i("event",n),n.type){case"response.output_text.delta":{let o=s.output[n.output_index];if(!o)throw new W(`missing output at index ${n.output_index}`);if(o.type==="message"){let l=o.content[n.content_index];if(!l)throw new W(`missing content at index ${n.content_index}`);if(l.type!=="output_text")throw new W(`expected content to be 'output_text', got ${l.type}`);i("response.output_text.delta",{...n,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let o=s.output[n.output_index];if(!o)throw new W(`missing output at index ${n.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...n,snapshot:o.arguments});break}default:i(n.type,n);break}},wh=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let n=b(this,Jr,"f");if(!n)throw new W("request ended without sending any events");Z(this,Jr,void 0,"f");let r=lU(n,b(this,ku,"f"));return Z(this,Nu,r,"f"),r},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",i=>{let s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(let i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(let s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,o)=>n.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=b(this,Nu,"f");if(!e)throw new W("stream ended without producing a ChatCompletion");return e}};function lU(t,e){return $T(t,e)}var Ks=class extends v{list(e,n={},r){return this._client.getAPIList(E`/responses/${e}/input_items`,re,{query:n,...r,__security:{bearerAuth:!0}})}};var Ws=class extends v{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n,__security:{bearerAuth:!0}})}};var nn=class extends v{constructor(){super(...arguments),this.inputItems=new Ks(this._client),this.inputTokens=new Ws(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ft(r),r))}retrieve(e,n={},r){return this._client.get(E`/responses/${e}`,{query:n,...r,stream:n?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(i=>("object"in i&&i.object==="response"&&ft(i),i))}delete(e,n){return this._client.delete(E`/responses/${e}`,{...n,headers:B([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>Ah(r,e))}stream(e,n){return Mu.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(E`/responses/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}compact(e,n){return this._client.post("/responses/compact",{body:e,...n,__security:{bearerAuth:!0}})}};nn.InputItems=Ks;nn.InputTokens=Ws;var Js=class extends v{retrieve(e,n){return this._client.get(E`/skills/${e}/content`,{...n,headers:B([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var zs=class extends v{retrieve(e,n,r){let{skill_id:i}=n;return this._client.get(E`/skills/${i}/versions/${e}/content`,{...r,headers:B([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var zr=class extends v{constructor(){super(...arguments),this.content=new zs(this._client)}create(e,n={},r){return this._client.post(E`/skills/${e}/versions`,$n({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{skill_id:i}=n;return this._client.get(E`/skills/${i}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/skills/${e}/versions`,re,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{skill_id:i}=n;return this._client.delete(E`/skills/${i}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};zr.Content=zs;var Cn=class extends v{constructor(){super(...arguments),this.content=new Js(this._client),this.versions=new zr(this._client)}create(e={},n){return this._client.post("/skills",$n({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(E`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/skills/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/skills",re,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}};Cn.Content=Js;Cn.Versions=zr;var Ys=class extends v{create(e,n,r){return this._client.post(E`/uploads/${e}/parts`,Ve({body:n,...r,__security:{bearerAuth:!0}},this._client))}};var rr=class extends v{constructor(){super(...arguments),this.parts=new Ys(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(E`/uploads/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}complete(e,n,r){return this._client.post(E`/uploads/${e}/complete`,{body:n,...r,__security:{bearerAuth:!0}})}};rr.Parts=Ys;var JT=async t=>{let e=await Promise.allSettled(t),n=e.filter(i=>i.status==="rejected");if(n.length){for(let i of n)console.error(i.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let i of e)i.status==="fulfilled"&&r.push(i.value);return r};var Xs=class extends v{create(e,n,r){return this._client.post(E`/vector_stores/${e}/file_batches`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:i}=n;return this._client.get(E`/vector_stores/${i}/file_batches/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{vector_store_id:i}=n;return this._client.post(E`/vector_stores/${i}/file_batches/${e}/cancel`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let i=await this.create(e,n);return await this.poll(e,i.id,r)}listFiles(e,n,r){let{vector_store_id:i,...s}=n;return this._client.getAPIList(E`/vector_stores/${i}/file_batches/${e}/files`,re,{query:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,n,r){let i=B([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(n,{vector_store_id:e},{...r,headers:i}).withResponse();switch(s.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let d=o.headers.get("openai-poll-after-ms");if(d){let c=parseInt(d);isNaN(c)||(l=c)}}await Zt(l);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},i){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=i?.maxConcurrency??5,o=Math.min(s,n.length),l=this._client,d=n.values(),c=[...r];async function f(h){for(let m of h){let g=await l.files.create({file:m,purpose:"assistants"},i);c.push(g.id)}}let p=Array(o).fill(d).map(f);return await JT(p),await this.createAndPoll(e,{file_ids:c})}};var Qs=class extends v{create(e,n,r){return this._client.post(E`/vector_stores/${e}/files`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:i}=n;return this._client.get(E`/vector_stores/${i}/files/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{vector_store_id:i,...s}=n;return this._client.post(E`/vector_stores/${i}/files/${e}`,{body:s,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(E`/vector_stores/${e}/files`,re,{query:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{vector_store_id:i}=n;return this._client.delete(E`/vector_stores/${i}/files/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let i=await this.create(e,n,r);return await this.poll(e,i.id,r)}async poll(e,n,r){let i=B([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(n,{vector_store_id:e},{...r,headers:i}).withResponse(),o=s.data;switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let d=s.response.headers.get("openai-poll-after-ms");if(d){let c=parseInt(d);isNaN(c)||(l=c)}}await Zt(l);break;case"failed":case"completed":return o}}}async upload(e,n,r){let i=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:i.id},r)}async uploadAndPoll(e,n,r){let i=await this.upload(e,n,r);return await this.poll(e,i.id,r)}content(e,n,r){let{vector_store_id:i}=n;return this._client.getAPIList(E`/vector_stores/${i}/files/${e}/content`,$e,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var In=class extends v{constructor(){super(...arguments),this.files=new Qs(this._client),this.fileBatches=new Xs(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(E`/vector_stores/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(E`/vector_stores/${e}`,{body:n,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/vector_stores",re,{query:e,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/vector_stores/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}search(e,n,r){return this._client.getAPIList(E`/vector_stores/${e}/search`,$e,{body:n,method:"post",...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};In.Files=Qs;In.FileBatches=Xs;var Yr=class extends v{create(e,n){return this._client.post("/videos",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(E`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/videos",ue,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(E`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}createCharacter(e,n){return this._client.post("/videos/characters",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}downloadContent(e,n={},r){return this._client.get(E`/videos/${e}/content`,{query:n,...r,headers:B([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}extend(e,n){return this._client.post("/videos/extensions",Ve({body:e,...n,__security:{bearerAuth:!0}},this._client))}getCharacter(e,n){return this._client.get(E`/videos/characters/${e}`,{...n,__security:{bearerAuth:!0}})}remix(e,n,r){return this._client.post(E`/videos/${e}/remix`,$n({body:n,...r,__security:{bearerAuth:!0}},this._client))}};var Zs,zT,Du,Xr=class extends v{constructor(){super(...arguments),Zs.add(this)}async unwrap(e,n,r=this._client.webhookSecret,i=300){return await this.verifySignature(e,n,r,i),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");b(this,Zs,"m",zT).call(this,r);let s=B([n]).values,o=b(this,Zs,"m",Du).call(this,s,"webhook-signature"),l=b(this,Zs,"m",Du).call(this,s,"webhook-timestamp"),d=b(this,Zs,"m",Du).call(this,s,"webhook-id"),c=parseInt(l,10);if(isNaN(c))throw new Qt("Invalid webhook timestamp format");let f=Math.floor(Date.now()/1e3);if(f-c>i)throw new Qt("Webhook timestamp is too old");if(c>f+i)throw new Qt("Webhook timestamp is too new");let p=o.split(" ").map(_=>_.startsWith("v1,")?_.substring(3):_),h=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),m=d?`${d}.${l}.${e}`:`${l}.${e}`,g=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let _ of p)try{let y=Buffer.from(_,"base64");if(await crypto.subtle.verify("HMAC",g,y,new TextEncoder().encode(m)))return}catch{continue}throw new Qt("The given webhook signature does not match the expected signature")}};Zs=new WeakSet,zT=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Du=function(e,n){if(!e)throw new Error("Headers are required");let r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var XT=Symbol.for("openai.node.providerDefinitions.v1"),QT=globalThis,ZT=QT[XT],jT=ZT??new WeakMap;ZT||Object.defineProperty(QT,XT,{value:jT});function ew(t){let e=jT.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Ch,Ih,na,tw,_U="workload-identity-auth",ne=class{constructor(e={}){Ch.add(this),na.set(this,void 0),this.completions=new Ur(this),this.chat=new Kn(this),this.embeddings=new Fr(this),this.files=new qr(this),this.images=new Hr(this),this.audio=new en(this),this.moderations=new Wr(this),this.models=new Kr(this),this.fineTuning=new qt(this),this.graders=new tr(this),this.vectorStores=new In(this),this.webhooks=new Xr(this),this.beta=new Ct(this),this.batches=new kr(this),this.uploads=new rr(this),this.admin=new Jn(this),this.responses=new nn(this),this.realtime=new wn(this),this.conversations=new jn(this),this.evals=new er(this),this.containers=new Zn(this),this.skills=new Cn(this),this.videos=new Yr(this);let n=e.provider;if(n){let _=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(_.length)throw new W(`The \`provider\` option cannot be used with ${_.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=n?null:Ft("OPENAI_BASE_URL"),apiKey:i=n?null:Ft("OPENAI_API_KEY")??null,adminAPIKey:s=n?null:Ft("OPENAI_ADMIN_KEY")??null,organization:o=n?null:Ft("OPENAI_ORG_ID")??null,project:l=n?null:Ft("OPENAI_PROJECT_ID")??null,webhookSecret:d=Ft("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:c,...f}=e,p=n?ew(n):void 0,h={apiKey:i,adminAPIKey:s,organization:o,project:l,webhookSecret:d,workloadIdentity:c,provider:n,...f,baseURL:p?.baseURL??(r||"https://api.openai.com/v1")};if(i&&c)throw new W("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!i&&!s&&!c)throw new W("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!h.dangerouslyAllowBrowser&&QE())throw new W(`It looks like you're running in a browser-like environment.
71
+
72
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
73
+ If you understand the risks and have appropriate mitigations in place,
74
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
75
+
76
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
77
+
78
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
79
+ `);this.baseURL=h.baseURL,this.timeout=h.timeout??Ih.DEFAULT_TIMEOUT,this.logger=h.logger??console;let m="warn";this.logLevel=m,this.logLevel=Kp(h.logLevel,"ClientOptions.logLevel",this)??Kp(Ft("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??m,this.fetchOptions=h.fetchOptions,this.maxRetries=h.maxRetries??2,this.fetch=h.fetch??au(),Z(this,na,eT,"f");let g=n?void 0:Ft("OPENAI_CUSTOM_HEADERS");if(g){let _={};for(let y of g.split(`
80
+ `)){let T=y.indexOf(":");T>=0&&(_[y.substring(0,T).trim()]=y.substring(T+1).trim())}h.defaultHeaders=B([_,h.defaultHeaders])}this._options=h,this._provider=p,c&&(this._workloadIdentityAuth=new hu(c,this.fetch)),this.apiKey=typeof i=="string"?i:null,this.adminAPIKey=s,this.organization=o,this.project=l,this.webhookSecret=d}withOptions(e){let n=this._options.provider,r=e.provider??n,i={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete i.apiKey,delete i.adminAPIKey,delete i.workloadIdentity,delete i.baseURL,r!==n&&(delete i.organization,delete i.project,delete i.defaultHeaders)),new this.constructor({...i,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return B([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return B([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return B([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return B([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return uT(e)}getUserAgent(){return`${this.constructor.name}/JS ${Bn}`}defaultIdempotencyKey(){return`stainless-node-retry-${Er()}`}makeStatusError(e,n,r,i){return Ae.generate(e,n,r,i)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof W?r:new W(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new W(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){let i=!b(this,Ch,"m",tw).call(this)&&r||this.baseURL,s=HE(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),l=Object.fromEntries(s.searchParams);return(!Op(o)||!Op(l))&&(n={...l,...o,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(i=>({method:e,path:n,...i})))}request(e,n=null){return new Cr(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let i=await e,s=i.maxRetries??this.maxRetries;n==null&&(n=s),await this.prepareOptions(i);let{req:o,url:l,timeout:d}=await this.buildRequest(i,{retryCount:s-n}),c=i.__metadata?.hasStreamingBody===!0;await this.prepareRequest(o,{url:l,options:i}),await this._provider?.prepareRequest?.(o,{url:l,options:i});let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(Ce(this).debug(`[${f}] sending request`,gn({retryOfRequestLogID:r,method:i.method,url:l,options:i,headers:o.headers})),i.signal?.aborted)throw new we;let m=i.__security??{bearerAuth:!0},g=new AbortController,_=await this.fetchWithAuth(l,o,d,g,m).catch(No),y=Date.now();if(_ instanceof globalThis.Error){let R=`retrying, ${n} attempts remaining`;if(i.signal?.aborted)throw new we;let x=ko(_)||/timed? ?out/i.test(String(_)+("cause"in _?String(_.cause):""));if(n&&!c)return Ce(this).info(`[${f}] connection ${x?"timed out":"failed"} - ${R}`),Ce(this).debug(`[${f}] connection ${x?"timed out":"failed"} (${R})`,gn({retryOfRequestLogID:r,url:l,durationMs:y-h,message:_.message})),this.retryRequest(i,n,r??f);let G=c?"error; streaming body cannot be retried":"error; no more retries left";throw Ce(this).info(`[${f}] connection ${x?"timed out":"failed"} - ${G}`),Ce(this).debug(`[${f}] connection ${x?"timed out":"failed"} (${G})`,gn({retryOfRequestLogID:r,url:l,durationMs:y-h,message:_.message})),_ instanceof Tr||_ instanceof Mo?_:x?new qn:new Gn({message:yU(_),cause:_})}let T=[..._.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,x])=>", "+R+": "+JSON.stringify(x)).join(""),C=`[${f}${p}${T}] ${o.method} ${l} ${_.ok?"succeeded":"failed"} with status ${_.status} in ${y-h}ms`;if(!_.ok){if(_.status===401&&this._workloadIdentityAuth&&m.bearerAuth&&!i.__metadata?.hasStreamingBody&&!i.__metadata?.workloadIdentityTokenRefreshed)return await Lp(_.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...i,__metadata:{...i.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??f);let R=await this.shouldRetry(_);if(n&&R&&!c){let N=`retrying, ${n} attempts remaining`;return await Lp(_.body),Ce(this).info(`${C} - ${N}`),Ce(this).debug(`[${f}] response error (${N})`,gn({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,durationMs:y-h})),this.retryRequest(i,n,r??f,_.headers)}let x=R?c?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";Ce(this).info(`${C} - ${x}`);let G=await _.text().catch(N=>No(N).message),S=JE(G),q=S?void 0:G;throw Ce(this).debug(`[${f}] response error (${x})`,gn({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,message:q,durationMs:Date.now()-h})),this.makeStatusError(_.status,S,q,_.headers)}return Ce(this).info(C),Ce(this).debug(`[${f}] response start`,gn({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,durationMs:y-h})),{response:_,options:i,controller:g,requestLogID:f,retryOfRequestLogID:r,startTime:h}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new Go(this,r,e)}async fetchWithAuth(e,n,r,i,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let l=n.headers,d=l.get("Authorization");if(!d||d===`Bearer ${_U}`){let c=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,n,r,i)}async fetchWithTimeout(e,n,r,i){let{signal:s,method:o,...l}=n||{},d=this._makeAbort(i);s&&s.addEventListener("abort",d,{once:!0});let c=setTimeout(d,r),f=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,p={signal:i.signal,...f?{duplex:"half"}:{},method:"GET",...l};o&&(p.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,i){let s,o=i?.get("retry-after-ms");if(o){let d=parseFloat(o);Number.isNaN(d)||(s=d)}let l=i?.get("retry-after");if(l&&!s){let d=parseFloat(l);Number.isNaN(d)?s=Date.parse(l)-Date.now():s=d*1e3}if(s===void 0){let d=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(n,d)}return await Zt(s),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let s=n-e,o=Math.min(.5*Math.pow(2,s),8),l=1-Math.random()*.25;return o*l*1e3}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:i,path:s,query:o,defaultBaseURL:l}=r,d=this.buildURL(s,o,l);"timeout"in r&&WE("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:f,isStreamingBody:p}=this.buildBody({options:r});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let h=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:n});return{req:{method:i,headers:h,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}},url:d,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=B([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ZE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(o,e.__security??{bearerAuth:!0}),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:n,headers:r}=e;if(!n)return n===void 0&&"body"in e?{...b(this,na,"f").call(this,{body:n,headers:B([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=B([r]),s=typeof globalThis.ReadableStream<"u"&&n instanceof globalThis.ReadableStream,o=!s&&(typeof n=="string"||n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof globalThis.Blob<"u"&&n instanceof globalThis.Blob||n instanceof URLSearchParams||n instanceof FormData);return ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof DataView||typeof n=="string"&&i.values.has("content-type")||globalThis.Blob&&n instanceof globalThis.Blob||n instanceof FormData||n instanceof URLSearchParams||s?{bodyHeaders:void 0,body:n,isStreamingBody:!o}:typeof n=="object"&&(Symbol.asyncIterator in n||Symbol.iterator in n&&"next"in n&&typeof n.next=="function")?{bodyHeaders:void 0,body:Oo(n),isStreamingBody:!0}:typeof n=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(n),isStreamingBody:!1}:{...b(this,na,"f").call(this,{body:n,headers:i}),isStreamingBody:!1}}};Ih=ne,na=new WeakMap,Ch=new WeakSet,tw=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};ne.OpenAI=Ih;ne.DEFAULT_TIMEOUT=6e5;ne.OpenAIError=W;ne.APIError=Ae;ne.APIConnectionError=Gn;ne.APIConnectionTimeoutError=qn;ne.APIUserAbortError=we;ne.NotFoundError=Li;ne.ConflictError=Fi;ne.RateLimitError=qi;ne.BadRequestError=Di;ne.AuthenticationError=Oi;ne.InternalServerError=Bi;ne.PermissionDeniedError=Ui;ne.UnprocessableEntityError=Gi;ne.InvalidWebhookSignatureError=Qt;ne.toFile=yu;ne.toStreamingFile=gu;ne.Completions=Ur;ne.Chat=Kn;ne.Embeddings=Fr;ne.Files=qr;ne.Images=Hr;ne.Audio=en;ne.Moderations=Wr;ne.Models=Kr;ne.FineTuning=qt;ne.Graders=tr;ne.VectorStores=In;ne.Webhooks=Xr;ne.Beta=Ct;ne.Batches=kr;ne.Uploads=rr;ne.Admin=Jn;ne.Responses=nn;ne.Realtime=wn;ne.Conversations=jn;ne.Evals=er;ne.Containers=Zn;ne.Skills=Cn;ne.Videos=Yr;function yU(t){if(AU(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function AU(t){let e=t;for(let n=0;n<8&&e&&typeof e=="object";n++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var EU=class{constructor(){sn(this,"adapters",new Map),sn(this,"staticModelsCache",new Map),this.initializeAdapters()}getProviderTypeDescription(){return"provider"}createUnknownProviderError(t){return new Error(`Unknown ${this.getProviderTypeDescription()}: ${t}`)}createDynamicModelUnsupportedError(t){return new Error(`${t.name} does not support dynamic model fetching`)}preloadStaticModels(){this.adapters.forEach((t,e)=>{this.getProviderFromAdapter(t).id===e&&this.staticModelsCache.set(e,this.getModelsFromAdapter(t))})}getAdapter(t){let e=this.adapters.get(t.toLowerCase());if(!e)throw this.createUnknownProviderError(t);return e}getAllProviders(){let t=[],e=new Set;return this.adapters.forEach(n=>{let r=this.getProviderFromAdapter(n);e.has(r.id)||(e.add(r.id),t.push(r))}),t}getStaticModels(t){let e=t.toLowerCase();if(this.staticModelsCache.has(e))return this.staticModelsCache.get(e);let n=this.getAdapter(e),r=this.getModelsFromAdapter(n);return this.staticModelsCache.set(e,r),r}async getDynamicModels(t,e){let n=this.getAdapter(t),r=this.getProviderFromAdapter(n);if(!r.supportsDynamicModels)throw this.createDynamicModelUnsupportedError(r);try{return await this.getModelsAsyncFromAdapter(n,e)}catch(i){throw console.warn(`Failed to fetch dynamic models (${t}):`,i),i}}async getModels(t,e){let n=this.getAdapter(t);if(this.getProviderFromAdapter(n).supportsDynamicModels&&e)try{let i=await this.getDynamicModels(t,e),s=this.getStaticModels(t),o=new Set(i.map(d=>d.id));return[...i,...s.filter(d=>!o.has(d.id))]}catch(i){return console.warn(`Failed to load dynamic models (${t}); falling back to static models:`,i),this.getStaticModels(t)}return this.getStaticModels(t)}getAllStaticModels(){let t=[];for(let e of this.getAllProviders()){let n=this.getStaticModels(e.id);for(let r of n)t.push({provider:e,model:r})}return t}supportsDynamicModels(t){try{let e=this.getAdapter(t);return this.getProviderFromAdapter(e).supportsDynamicModels}catch{return!1}}validateProviderModel(t,e){try{return this.getStaticModels(t).some(r=>r.id===e)}catch{return!1}}clearCache(){this.staticModelsCache.clear(),this.preloadStaticModels()}},qu=class extends Error{constructor(t,e,n){super(e?`[${t}] ${e}`:`[${t}]`),sn(this,"code"),sn(this,"params"),this.name=this.constructor.name,this.code=t,this.params=n??(e?{details:e}:void 0),Object.setPrototypeOf(this,new.target.prototype)}},Ue=class extends qu{constructor(t){super(Ke.API_ERROR,t)}},Ie=class extends qu{constructor(t){super(Ke.CONFIG_ERROR,t)}},XJ=class extends qu{constructor(t){super(Ke.VALIDATION_ERROR,t)}},QJ=class extends qu{constructor(t){super(Ke.INITIALIZATION_ERROR,t)}},TU=class extends Error{constructor(t,e,n){super(e?`[${t}] ${e}`:`[${t}]`),sn(this,"code"),sn(this,"params"),this.name="LLMError",this.code=t,this.params=n??(e?{details:e}:void 0)}},ZJ=class extends TU{constructor(t){super(Ke.CONFIG_ERROR,t),this.name="ModelConfigError"}},jJ={API_KEY_REQUIRED:Ke.API_KEY_REQUIRED,MODEL_NOT_FOUND:Ke.MODEL_NOT_FOUND,TEMPLATE_INVALID:Ke.TEMPLATE_INVALID,EMPTY_INPUT:Ke.EMPTY_INPUT,OPTIMIZATION_FAILED:Ke.OPTIMIZATION_FAILED,ITERATION_FAILED:Ke.ITERATION_FAILED,TEST_FAILED:Ke.TEST_FAILED,MODEL_KEY_REQUIRED:Ke.MODEL_KEY_REQUIRED,INPUT_TOO_LONG:Ke.INPUT_TOO_LONG},Bu=class{async doSendImageUnderstanding(t,e){throw new Ie(`${this.getProvider().name} does not support image understanding requests`)}async doSendImageUnderstandingStream(t,e,n){throw new Ie(`${this.getProvider().name} does not support streaming image understanding requests`)}async sendMessage(t,e){return this.validateMessages(t),await this.doSendMessage(t,e)}async sendMessageStream(t,e,n){this.validateMessages(t),await this.doSendMessageStream(t,e,n)}async sendMessageStreamWithTools(t,e,n,r){this.validateMessages(t),await this.doSendMessageStream(t,e,r)}async sendImageUnderstanding(t,e){return this.validateImageUnderstandingRequest(t),await this.doSendImageUnderstanding(t,e)}async sendImageUnderstandingStream(t,e,n){this.validateImageUnderstandingRequest(t),await this.doSendImageUnderstandingStream(t,e,n)}validateMessages(t){if(!Array.isArray(t))throw new Ie("Messages must be an array");if(t.length===0)throw new Ie("Messages array cannot be empty");for(let e of t){if(!e.role||!e.content)throw new Ie("Each message must have role and content");if(!["system","user","assistant","tool"].includes(e.role))throw new Ie(`Invalid message role: ${e.role}`);if(typeof e.content!="string")throw new Ie("Message content must be a string")}}validateImageUnderstandingRequest(t){if(!t||typeof t!="object")throw new Ie("Image understanding request cannot be empty");if(typeof t.userPrompt!="string"||!t.userPrompt.trim())throw new Ie("Image understanding user prompt cannot be empty");if(!Array.isArray(t.images)||t.images.length===0)throw new Ie("Image understanding request requires at least one image");t.images.forEach((e,n)=>{if(!e||typeof e!="object")throw new Ie(`Image at index ${n} is invalid`);if(typeof e.b64!="string"||!e.b64.trim())throw new Ie(`Image at index ${n} is missing base64 data`)})}processThinkTags(t){if(!t.includes("<think>"))return{content:t};let e=/<think>([\s\S]*?)<\/think>/g,n=[],r;for(;(r=e.exec(t))!==null;)n.push(r[1]);return{content:t.replace(e,"").trim(),reasoning:n.length>0?n.join(`
81
+ `):void 0}}processStreamContentWithThinkTags(t,e,n){if(!e.onReasoningToken){let{content:s}=this.processThinkTags(t);s&&e.onToken(s);return}n.buffer+=t;let r=n.buffer,i="";for(;r.length>0;)if(n.isInThinkMode){let s=r.indexOf("</think>");if(s!==-1){if(s>0){let o=r.slice(0,s);e.onReasoningToken(o),i+=o+"</think>"}else i+="</think>";n.isInThinkMode=!1,r=r.slice(s+8)}else if(r.endsWith("<")||r.endsWith("</")||r.endsWith("</t")||r.endsWith("</th")||r.endsWith("</thi")||r.endsWith("</thin")||r.endsWith("</think")){n.buffer=r;return}else e.onReasoningToken(r),i+=r,r=""}else{let s=r.indexOf("<think>");if(s!==-1){if(s>0){let o=r.slice(0,s);e.onToken(o),i+=o+"<think>"}else i+="<think>";n.isInThinkMode=!0,r=r.slice(s+7)}else if(r.endsWith("<")||r.endsWith("<t")||r.endsWith("<th")||r.endsWith("<thi")||r.endsWith("<thin")||r.endsWith("<think")){n.buffer=r;return}else e.onToken(r),i+=r,r=""}n.buffer=""}getModelById(t){return this.getModels().find(n=>n.id===t)}buildDefaultModel(t){let e=this.getProvider();return{id:t,name:t,description:`Custom model ${t} for ${e.name}`,providerId:e.id,capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:128e3},parameterDefinitions:this.getParameterDefinitions(t),defaultParameterValues:this.getDefaultParameterValues(t)}}},Uu=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Ou=t=>typeof t=="number"&&Number.isFinite(t),Qr=t=>typeof t=="number"&&Number.isSafeInteger(t),nw=t=>typeof t=="boolean",xh=t=>e=>typeof e=="string"&&t.includes(e),Lu=xh(["none","minimal","low","medium","high","xhigh","max"]),Ph=xh(["auto","concise","detailed"]),Fu={temperature:Ou,top_p:Ou,presence_penalty:Ou,frequency_penalty:Ou,max_tokens:Qr,max_completion_tokens:Qr,max_output_tokens:Qr,n:Qr,seed:Qr,logprobs:nw,top_logprobs:Qr,reasoning_effort:Lu,service_tier:xh(["auto","default","flex","scale","priority"]),store:nw,timeout:Qr};function rw(t,e){return Uu(Fu,t)&&Fu[t](e)}function ez(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.entries(t).every(([e,n])=>e==="reasoning.effort"?Lu(n):e==="reasoning.summary"?Ph(n):rw(e,n))}function tz(t){return Array.isArray(t)&&new Set(t).size===t.length&&t.every(e=>typeof e=="string"&&(e==="other"||e==="reasoning"||Uu(Fu,e)))}var wU=new Set(["model","input","messages","stream"]),CU=["instructions","conversation","previous_response_id","prompt","tools","tool_choice","functions","function_call","extra_body"];function Sh(t,e){let n=e;if(CU.some(o=>{let l=n[o];return Uu(n,o)&&l!=null&&(!Array.isArray(l)||l.length>0)})||n.background===!0)throw new Ie("Text comparisons require foreground requests with no tools or extra context");let i={},s=new Set;for(let o of Object.keys(n).sort()){if(wU.has(o))continue;let l=n[o];if(l!==void 0){if(o==="reasoning"&&l!==null&&typeof l=="object"&&!Array.isArray(l)){let d=l;Lu(d.effort)&&(i["reasoning.effort"]=d.effort),Ph(d.summary)&&(i["reasoning.summary"]=d.summary),Object.keys(d).some(c=>c==="effort"?!Lu(d[c]):c!=="summary"||!Ph(d[c]))&&s.add("reasoning");continue}if(!Uu(Fu,o)){s.add("other");continue}rw(o,l)?i[o]=l:s.add(o)}}return{modelId:e.model,api:t,parameters:i,omittedParameterNames:[...s].sort()}}var iw=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,IU=new Set(["authorization","connection","content-length","content-type","cookie","host","keep-alive","origin","proxy-authenticate","proxy-authorization","referer","set-cookie","te","trailer","transfer-encoding","upgrade","user-agent"]),SU=["proxy-","sec-","x-stainless-"];function vU(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sw(t){let e=t.toLowerCase();return IU.has(e)||SU.some(n=>e.startsWith(n))}function ow(t){return t?Array.isArray(t)?t.map(e=>({key:String(e.key??e.name??"").trim(),value:e.value})):vU(t)?Object.entries(t).map(([e,n])=>({key:e.trim(),value:n})):[]:[]}function PU(t){let e=[];for(let{key:n,value:r}of ow(t)){let i=typeof r=="string"?r.trim():r;if(!(!n&&(i==null||i===""))){if(!n||!iw.test(n)){e.push({key:n||"(empty)",reason:"invalid-name"});continue}if(sw(n)){e.push({key:n,reason:"forbidden-name"});continue}if(r==null||String(r).trim()===""){e.push({key:n,reason:"missing-value"});continue}typeof r!="string"&&typeof r!="number"&&typeof r!="boolean"&&e.push({key:n,reason:"invalid-value"})}}return{valid:e.length===0,errors:e}}function aw(t){let e={};for(let{key:n,value:r}of ow(t)){let i=r==null?"":String(r).trim();!n&&!i||!n||!iw.test(n)||sw(n)||!i||(e[n]=i)}return Object.keys(e).length>0?e:void 0}var RU=[{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",description:"Balanced GPT-5.6 model for general-purpose work with strong reasoning and low latency",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:105e4},defaultParameterValues:{reasoning_effort:"none"}},{id:"gpt-6-astra",name:"GPT-6 Astra",description:"Most capable OpenAI model for the hardest end-to-end work",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:105e4},defaultParameterValues:{reasoning_effort:"low"}},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",description:"Fast GPT-5.6 model for cost-sensitive, high-throughput workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:105e4},defaultParameterValues:{reasoning_effort:"none"}}],et=class extends Bu{getProvider(){return{id:"openai",name:"OpenAI",description:"Official OpenAI API",requiresApiKey:!0,defaultBaseURL:"https://api.openai.com/v1",supportsDynamicModels:!0,apiKeyUrl:"https://platform.openai.com/api-keys",connectionSchema:{required:["apiKey"],optional:["baseURL","requestStyle"],fieldTypes:{apiKey:"string",baseURL:"string",requestStyle:"string"}}}}getModels(){return RU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}async getModelsAsync(t){let e=t.connectionConfig.baseURL||this.getProvider().defaultBaseURL,n=this.createOpenAIInstance(t,!1);try{let r=await n.models.list();if(r&&r.data&&Array.isArray(r.data)){let i=r.data.map(s=>this.buildDefaultModel(s.id)).sort((s,o)=>s.id.localeCompare(o.id));if(i.length===0)throw new Ue("API returned empty model list");return i}throw new Ue("Unexpected API response format")}catch(r){throw console.error("[OpenAIAdapter] Failed to fetch models:",r),r.message&&(r.message.includes("Failed to fetch")||r.message.includes("Connection error"))?this.detectCrossOriginError(r,e)?new Ue(`Cross-origin connection failed: ${r.message}`):new Ue(`Connection failed: ${r.message}`):r.response?.data?new Ue(`API error: ${JSON.stringify(r.response.data)}`):new Ue(r.message||"Unknown error")}}getParameterDefinitions(t){let e=t==="gpt-6-astra";return[{name:"reasoning_effort",labelKey:"params.reasoning_effort.label",descriptionKey:"params.reasoning_effort.description",description:"Reasoning effort for current OpenAI models.",type:"string",defaultValue:e?"low":"none",default:e?"low":"none",allowedValues:e?["low","medium","high","xhigh","max"]:["none","low","medium","high","xhigh","max"]},{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-2). Higher values make output more random.",type:"number",defaultValue:1,default:1,minValue:0,maxValue:2,min:0,max:2,step:.1},{name:"top_p",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter (0-1). Alternative to temperature.",type:"number",defaultValue:1,default:1,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"max_completion_tokens",labelKey:"params.max_completion_tokens.label",descriptionKey:"params.max_completion_tokens.description",description:"Maximum tokens in completion (recommended over max_tokens)",type:"integer",minValue:1,maxValue:1e6,min:1,max:1e6,step:1,unitKey:"params.tokens.unit"},{name:"max_tokens",labelKey:"params.max_tokens.label",descriptionKey:"params.max_tokens.description",description:"Deprecated: Use max_completion_tokens instead",type:"integer",minValue:1,maxValue:1e6,min:1,max:1e6,step:1,unitKey:"params.tokens.unit"},{name:"presence_penalty",labelKey:"params.presence_penalty.label",descriptionKey:"params.presence_penalty.description",description:"Presence penalty (-2.0 to 2.0). Penalizes tokens based on presence.",type:"number",defaultValue:0,default:0,minValue:-2,maxValue:2,min:-2,max:2,step:.1},{name:"frequency_penalty",labelKey:"params.frequency_penalty.label",descriptionKey:"params.frequency_penalty.description",description:"Frequency penalty (-2.0 to 2.0). Penalizes tokens based on frequency.",type:"number",defaultValue:0,default:0,minValue:-2,maxValue:2,min:-2,max:2,step:.1},{name:"logprobs",labelKey:"params.logprobs.label",descriptionKey:"params.logprobs.description",description:"Return log probabilities of output tokens",type:"boolean",defaultValue:!1,default:!1},{name:"top_logprobs",labelKey:"params.top_logprobs.label",descriptionKey:"params.top_logprobs.description",description:"Number of most likely tokens to return (0-20)",type:"integer",minValue:0,maxValue:20,min:0,max:20,step:1},{name:"seed",labelKey:"params.seed.label",descriptionKey:"params.seed.description",description:"Seed for deterministic sampling (integer)",type:"integer",minValue:0,maxValue:2147483647,min:0,max:2147483647,step:1},{name:"n",labelKey:"params.n.label",descriptionKey:"params.n.description",description:"Number of completions to generate (default: 1)",type:"integer",defaultValue:1,default:1,minValue:1,maxValue:10,min:1,max:10,step:1},{name:"timeout",labelKey:"params.timeout.label",descriptionKey:"params.timeout.description_openai",description:"Client timeout in milliseconds (OpenAI SDK setting)",type:"integer",defaultValue:6e4,default:6e4,minValue:1e3,maxValue:6e5,min:1e3,max:6e5,step:1e3,unit:"ms"}]}getDefaultParameterValues(t){return{}}getRequestStyle(t){return String(t.connectionConfig.requestStyle||"").trim().toLowerCase()==="responses"?"responses":"chat_completions"}supportsStreamRequestEvidence(){let{id:t}=this.getProvider();return t==="openai"||t==="openai-compatible"}describeStreamRequest(t){if(this.supportsStreamRequestEvidence())return this.getRequestStyle(t)==="responses"?Sh("responses",this.buildResponsesStreamRequest([],t)):Sh("chat-completions",this.buildChatStreamRequest([],t))}captureStreamRequest(t,e,n){if(n.onRequest){if(!this.supportsStreamRequestEvidence())throw new Ie("This adapter cannot capture text request evidence");n.signal?.throwIfAborted(),n.onRequest(Sh(t,e)),n.signal?.throwIfAborted()}}buildChatStreamRequest(t,e){let{timeout:n,model:r,messages:i,stream:s,...o}=e.paramOverrides??{};return{model:e.modelMeta.id,messages:t.map(({role:l,content:d})=>({role:l,content:d})),stream:!0,...o}}buildResponsesInput(t){return t.map((e,n)=>e.role==="tool"?{type:"function_call_output",call_id:e.tool_call_id||e.name||`tool_call_${n}`,output:e.content}:{role:e.role,content:e.content})}buildImageDataUrl(t){let e=t.b64.trim();return/^data:/i.test(e)?e:`data:${t.mimeType||"image/png"};base64,${e}`}buildResponsesImageUnderstandingInput(t){let e=[];return t.systemPrompt?.trim()&&e.push({role:"system",content:[{type:"input_text",text:t.systemPrompt}]}),e.push({role:"user",content:[{type:"input_text",text:t.userPrompt},...t.images.map(n=>({type:"input_image",image_url:this.buildImageDataUrl(n)}))]}),e}normalizeResponsesParams(t){let{timeout:e,model:n,messages:r,input:i,stream:s,max_tokens:o,max_completion_tokens:l,presence_penalty:d,frequency_penalty:c,n:f,seed:p,logprobs:h,reasoning_effort:m,responseMimeType:g,..._}=t||{},y={..._},T=l??o??y.max_output_tokens;if(T!==void 0&&(y.max_output_tokens=T),h===!0&&y.include===void 0&&(y.include=["message.output_text.logprobs"]),m!==void 0){let C=y.reasoning;y.reasoning={...C&&typeof C=="object"?C:{},effort:m}}return y}async sendResponsesMessage(t,e,n,r,i){let s={model:n.modelMeta.id,input:r??this.buildResponsesInput(e),...this.normalizeResponsesParams(i??n.paramOverrides)},o=await t.responses.create(s);return this.parseResponsesResponse(o,n.modelMeta.id)}buildResponsesStreamRequest(t,e,n,r){return{model:e.modelMeta.id,input:n??this.buildResponsesInput(t),stream:!0,...this.normalizeResponsesParams(r??e.paramOverrides)}}async sendResponsesMessageStream(t,e,n,r,i,s,o){let l={...this.buildResponsesStreamRequest(e,n,s,o),...i?.length?{tools:i}:{}};this.captureStreamRequest("responses",l,r);let d=r.signal?await t.responses.create(l,{signal:r.signal}):await t.responses.create(l),c="",f="",p={isInThinkMode:!1,buffer:""},h=new Map;for await(let m of d){if(m&&typeof m=="object"&&!("type"in m)&&typeof m.message=="string"){let g=typeof m.code=="string"?`${m.code}: ${m.message}`:m.message;throw new Ue(g)}switch(m.type){case"response.output_text.delta":{let g=m.delta||"";g&&(c+=g,this.processStreamContentWithThinkTags(g,r,p));break}case"response.reasoning_text.delta":case"response.reasoning_summary_text.delta":{let g=m.delta||"";g&&(f+=g,r.onReasoningToken?.(g));break}case"response.output_item.added":{let g=m.item;g?.type==="function_call"&&h.set(m.output_index,{id:g.call_id||g.id||"",type:"function",function:{name:g.name||"",arguments:g.arguments||""}});break}case"response.function_call_arguments.delta":{let g=h.get(m.output_index)||{id:m.item_id||"",type:"function",function:{name:"",arguments:""}};if(g.function.arguments+=m.delta||"",h.set(m.output_index,g),r.onToolCall)try{JSON.parse(g.function.arguments),r.onToolCall(g)}catch{}break}case"response.completed":{let g=m.response;!c&&g?.output_text&&(c=g.output_text),f||(f=this.extractResponsesReasoning(g?.output));break}case"response.failed":throw new Ue("Responses API request failed");case"response.error":throw new Ue(m.error?.message||"Responses API request failed");default:break}}await r.onComplete({content:c,reasoning:f||void 0,toolCalls:h.size>0?Array.from(h.values()):void 0,metadata:{model:n.modelMeta.id}})}extractResponsesText(t){if(!Array.isArray(t))return"";let e=[];for(let n of t)if(!(n?.type!=="message"||!Array.isArray(n.content)))for(let r of n.content)r?.type==="output_text"&&typeof r.text=="string"&&e.push(r.text);return e.join("")}extractResponsesReasoning(t){if(!Array.isArray(t))return"";let e=[];for(let n of t)if(n?.type==="reasoning"&&(typeof n.content=="string"&&e.push(n.content),Array.isArray(n.summary)))for(let r of n.summary)typeof r?.text=="string"&&e.push(r.text);return e.join(`
82
+ `).trim()}extractResponsesToolCalls(t){if(!Array.isArray(t))return;let e=t.filter(n=>n?.type==="function_call").map(n=>({id:n.call_id||n.id||"",type:"function",function:{name:n.name||"",arguments:n.arguments||""}}));return e.length>0?e:void 0}parseResponsesResponse(t,e){let n=typeof t?.output_text=="string"?t.output_text:this.extractResponsesText(t?.output),r=this.extractResponsesReasoning(t?.output);return{content:n,reasoning:r||void 0,toolCalls:this.extractResponsesToolCalls(t?.output),metadata:{model:e}}}detectCrossOriginError(t,e){if(typeof window>"u")return!1;try{let n=new URL(e),r=new URL(window.location.href),i=t.toString(),s=n.origin!==r.origin,o=i.includes("ERR_NAME_NOT_RESOLVED")||i.includes("ERR_CONNECTION_REFUSED")||i.includes("ERR_NETWORK_CHANGED")||i.includes("ERR_INTERNET_DISCONNECTED")||i.includes("ERR_EMPTY_RESPONSE");return s&&!o}catch(n){return console.warn("[OpenAIAdapter] Failed to parse URL for CORS detection:",n),!1}}shouldForceCrossOriginCredentialOmit(t){if(typeof window>"u")return!1;try{return this.resolveRequestURL(t,window.location.href).origin!==window.location.origin}catch(e){return console.warn("[OpenAIAdapter] Failed to resolve request URL for credentials mode:",e),!1}}resolveRequestURL(t,e){return typeof t=="string"?new URL(t,e):t instanceof URL?new URL(t.toString(),e):typeof Request<"u"&&t instanceof Request?new URL(t.url,e):new URL(String(t),e)}sanitizeCrossOriginHeaders(t){if(!t)return;let e=new Headers(t),n=new Headers;return e.forEach((r,i)=>{let s=i.toLowerCase();s.startsWith("x-stainless-")||s==="user-agent"||s==="content-length"||n.set(i,r)}),n}stripAuthorizationHeader(t){if(!t)return;let e=new Headers(t),n=new Headers;return e.forEach((r,i)=>{i.toLowerCase()!=="authorization"&&n.set(i,r)}),n}getCustomDefaultHeaders(t){if(this.getProvider().id==="openai-compatible"||t.providerMeta?.id==="openai-compatible")return aw(t.connectionConfig?.customHeaders)}createOpenAIInstance(t,e=!1,n=!1){let r=t.connectionConfig.apiKey||"",i=typeof r=="string"&&r.trim().length>0,s=t.connectionConfig.baseURL||this.getProvider().defaultBaseURL;s?.endsWith("/chat/completions")&&(s=s.slice(0,-17));let o=e?9e4:6e4,l=t.paramOverrides?.timeout!==void 0?t.paramOverrides.timeout:o,d={apiKey:i||this.getProvider().requiresApiKey?r:"not-required",baseURL:s,timeout:l,maxRetries:e?2:3,...n?{logLevel:"off",maxRetries:0}:{}},c=this.getCustomDefaultHeaders(t);c&&(d.defaultHeaders=c);let f=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0;return f&&(!i||typeof window<"u")&&(d.fetch=(h,m)=>{let g=m?.headers;if(i||(g=this.stripAuthorizationHeader(g)),typeof window<"u"&&this.shouldForceCrossOriginCredentialOmit(h)){let _=this.sanitizeCrossOriginHeaders(g);return f(h,{...m??{},..._?{headers:_}:{},mode:m?.mode??"cors",credentials:"omit"})}return g!==m?.headers?f(h,{...m??{},...g?{headers:g}:{}}):f(h,m)}),typeof window<"u"&&(d.dangerouslyAllowBrowser=!0,console.log("[OpenAIAdapter] Browser environment detected. Setting dangerouslyAllowBrowser=true.")),new ne(d)}async doSendMessage(t,e){let n=this.createOpenAIInstance(e,!1);if(this.getRequestStyle(e)==="responses")try{return await this.sendResponsesMessage(n,t,e)}catch(c){throw console.error("[OpenAIAdapter] Responses API call failed:",c),c}let r=t.map(c=>({role:c.role,content:c.content})),{timeout:i,model:s,messages:o,...l}=e.paramOverrides||{},d={model:e.modelMeta.id,messages:r,...l};try{let c=await n.chat.completions.create(d);return await this.parseCompletionResponse(c,e.modelMeta.id)}catch(c){throw console.error("[OpenAIAdapter] API call failed:",c),c}}async doSendImageUnderstanding(t,e){let n=this.createOpenAIInstance(e,!1),r={...e.paramOverrides||{},...t.paramOverrides||{}};if(this.getRequestStyle(e)==="responses")return await this.sendResponsesMessage(n,[],e,this.buildResponsesImageUnderstandingInput(t),r);let{timeout:i,model:s,messages:o,stream:l,responseMimeType:d,...c}=r,f=[{type:"text",text:t.userPrompt},...t.images.map(g=>({type:"image_url",image_url:{url:this.buildImageDataUrl(g)}}))],p=[];t.systemPrompt?.trim()&&p.push({role:"system",content:t.systemPrompt}),p.push({role:"user",content:f});let h={model:e.modelMeta.id,messages:p,...c},m=await n.chat.completions.create(h);return await this.parseCompletionResponse(m,e.modelMeta.id)}async doSendImageUnderstandingStream(t,e,n){try{let r=this.createOpenAIInstance(e,!0),i={...e.paramOverrides||{},...t.paramOverrides||{}};if(this.getRequestStyle(e)==="responses"){await this.sendResponsesMessageStream(r,[],e,n,void 0,this.buildResponsesImageUnderstandingInput(t),i);return}let{timeout:s,model:o,messages:l,stream:d,responseMimeType:c,...f}=i,p=[{type:"text",text:t.userPrompt},...t.images.map(C=>({type:"image_url",image_url:{url:this.buildImageDataUrl(C)}}))],h=[];t.systemPrompt?.trim()&&h.push({role:"system",content:t.systemPrompt}),h.push({role:"user",content:p});let m={model:e.modelMeta.id,messages:h,stream:!0,...f},g=n.signal?await r.chat.completions.create(m,{signal:n.signal}):await r.chat.completions.create(m),_="",y="",T={isInThinkMode:!1,buffer:""};for await(let C of g){let R=C.choices?.[0]?.delta?.reasoning_content||"";R&&(_+=R,n.onReasoningToken?.(R));let x=C.choices?.[0]?.delta?.content||"";x&&(y+=x,this.processStreamContentWithThinkTags(x,n,T))}await n.onComplete({content:y,reasoning:_||void 0,metadata:{model:e.modelMeta.id}})}catch(r){throw n.onError(r instanceof Error?r:new Error(String(r))),r}}async parseCompletionResponse(t,e){if(typeof t=="string")return this.parseSSEResponse(t,e);if(this.isStreamResponse(t))return await this.consumeStreamResponse(t,e);if(!t.choices||t.choices.length===0)throw new Ue("API returned invalid response: choices is empty or missing");let n=t.choices[0];if(!n?.message)throw new Ue("No valid response received");let r=n.message.content||"",i="";if(n.message.reasoning_content)i=n.message.reasoning_content;else{let s=this.processThinkTags(r);r=s.content,i=s.reasoning||""}return{content:r,reasoning:i||void 0,metadata:{model:e,finishReason:n.finish_reason||void 0}}}parseSSEResponse(t,e){let n="",r="",i,s=t.split(`
83
+ `);for(let l of s){let d=l.trim();if(d&&!(d==="data: [DONE]"||d==="data:[DONE]")&&d.startsWith("data:")){let c=d.slice(5).trimStart();if(!c)continue;try{let f=JSON.parse(c),p=f.choices?.[0]?.delta?.reasoning_content||"";p&&(r+=p);let h=f.choices?.[0]?.delta?.content||"";h&&(n+=h),f.choices?.[0]?.finish_reason&&f.choices[0].finish_reason!==""&&(i=f.choices[0].finish_reason)}catch{}}}if(!n&&!r){try{let l=JSON.parse(t),d=l.choices?.[0]?.message?.content||"",c=l.choices?.[0]?.message?.reasoning_content||"";if(d||c){let f=this.processThinkTags(d);return{content:f.content,reasoning:c||f.reasoning||void 0,metadata:{model:e,finishReason:l.choices?.[0]?.finish_reason}}}}catch{}throw new Ue(`SSE response parsing failed: unable to extract any content from response. First 200 chars: ${t.slice(0,200)}`)}let o=this.processThinkTags(n);return{content:o.content,reasoning:r||o.reasoning||void 0,metadata:{model:e,finishReason:i}}}isStreamResponse(t){if(t&&t.choices&&Array.isArray(t.choices)&&t.choices.length>0){let e=t.choices[0];if(e&&e.message!==void 0)return!1}return!!(t&&typeof t[Symbol.asyncIterator]=="function")}async consumeStreamResponse(t,e){let n="",r="",i;for await(let o of t){let l=o.choices?.[0]?.delta?.reasoning_content||"";l&&(r+=l);let d=o.choices?.[0]?.delta?.content||"";d&&(n+=d),o.choices?.[0]?.finish_reason&&(i=o.choices[0].finish_reason)}let s=this.processThinkTags(n);return{content:s.content,reasoning:r||s.reasoning||void 0,metadata:{model:e,finishReason:i}}}async doSendMessageStream(t,e,n){try{let r=this.createOpenAIInstance(e,!0,!!n.onRequest);if(this.getRequestStyle(e)==="responses"){await this.sendResponsesMessageStream(r,t,e,n);return}let i=this.buildChatStreamRequest(t,e);this.captureStreamRequest("chat-completions",i,n);let s=n.signal?await r.chat.completions.create(i,{signal:n.signal}):await r.chat.completions.create(i),o="",l="",d={isInThinkMode:!1,buffer:""};for await(let f of s){let p=f.choices[0]?.delta?.reasoning_content||"";p&&(o+=p,n.onReasoningToken&&n.onReasoningToken(p));let h=f.choices[0]?.delta?.content||"";h&&(l+=h,this.processStreamContentWithThinkTags(h,n,d))}let c={content:l,reasoning:o||void 0,metadata:{model:e.modelMeta.id}};await n.onComplete(c)}catch(r){throw n.onRequest||console.error("[OpenAIAdapter] Stream error:",r),n.onError(r instanceof Error?r:new Error(String(r))),r}}async sendMessageStreamWithTools(t,e,n,r){try{let i=this.createOpenAIInstance(e,!0);if(this.getRequestStyle(e)==="responses"){await this.sendResponsesMessageStream(i,t,e,r,n);return}let s=t.map(R=>({role:R.role,content:R.content})),{timeout:o,model:l,messages:d,stream:c,tools:f,...p}=e.paramOverrides||{},h={model:e.modelMeta.id,messages:s,tools:n,tool_choice:"auto",stream:!0,...p},m=r.signal?await i.chat.completions.create(h,{signal:r.signal}):await i.chat.completions.create(h),g="",_="",y=[],T={isInThinkMode:!1,buffer:""};for await(let R of m){let x=R.choices[0]?.delta?.reasoning_content||"";x&&(g+=x,r.onReasoningToken&&r.onReasoningToken(x));let G=R.choices[0]?.delta?.tool_calls;if(G){for(let q of G)if(q.index!==void 0){for(;y.length<=q.index;)y.push({id:"",type:"function",function:{name:"",arguments:""}});let $=y[q.index];if(q.id&&($.id=q.id),q.type&&($.type=q.type),q.function&&(q.function.name&&($.function.name+=q.function.name),q.function.arguments&&($.function.arguments+=q.function.arguments),$.id&&$.function.name&&q.function.arguments&&r.onToolCall))try{JSON.parse($.function.arguments),r.onToolCall($)}catch{}}}let S=R.choices[0]?.delta?.content||"";S&&(_+=S,this.processStreamContentWithThinkTags(S,r,T))}let C={content:_,reasoning:g||void 0,toolCalls:y.length>0?y:void 0,metadata:{model:e.modelMeta.id}};await r.onComplete(C)}catch(i){throw console.error("[OpenAIAdapter] Stream with tools error:",i),r.onError(i instanceof Error?i:new Error(String(i))),i}}},xU=[{id:"custom-model",name:"Custom Model",description:"Generic model entry for custom endpoints that support OpenAI-compatible Chat Completions or Responses APIs"}],bU=class extends et{getProvider(){return{id:"openai-compatible",name:"OpenAI Compatible (Custom)",description:"Custom endpoints that implement OpenAI Chat Completions or Responses APIs",requiresApiKey:!1,defaultBaseURL:"http://localhost:11434/v1",supportsDynamicModels:!0,connectionSchema:{required:[],optional:["baseURL","apiKey","requestStyle"],fieldTypes:{baseURL:"string",apiKey:"string",requestStyle:"string"}}}}getModels(){return xU.map(t=>({...this.buildDefaultModel(t.id),name:t.name,description:t.description}))}},bh=["ollama","magpie","lmstudio","cc-switch","cliproxyapi","litellm","llamacpp"];function kU(t={}){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid local service ports");let e={};for(let n of bh){let r=t[n];if(r!==void 0){if(!Number.isInteger(r)||r<1||r>65535)throw new Error("Invalid local service port");e[n]=r}}return e}var Ye=class extends Error{constructor(t,e){super(t),sn(this,"status",t),sn(this,"httpStatus",e)}};async function rz(t={},e={}){let n=kU(t),r=e.fetch??globalThis.fetch,i={ollama:[11434],magpie:[3425],lmstudio:[1234],"cc-switch":[15721],cliproxyapi:[8317],litellm:[4e3],llamacpp:[9931,8080]},s=bh.filter(o=>!["lmstudio","cc-switch"].includes(o)).flatMap(o=>(n[o]===void 0?i[o]:[n[o]]).map(l=>({kind:o,port:l})));return Promise.all(s.map(async({kind:o,port:l})=>{let d={ollama:"Ollama",magpie:"Magpie",lmstudio:"LM Studio","cc-switch":"CC Switch",cliproxyapi:"CLIProxyAPI",litellm:"LiteLLM",llamacpp:"llama.cpp"},c=`http://${o==="ollama"?"localhost":"127.0.0.1"}:${l}`,f={kind:o,name:d[o],baseURL:`${c}/v1`,status:"unavailable",models:[]},p=new AbortController,h=()=>p.abort();e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();let m=!1,g=setTimeout(()=>{m=!0,h()},e.timeoutMs??3e3),_=T=>r(`${c}${T}`,{signal:p.signal,credentials:"omit",redirect:"error",cache:"no-store"}),y=async(T,C=!1)=>{let R=await _(T);if(R.status===401||R.status===403){if(o==="magpie"&&T==="/api/hello"&&R.status===401){let x=await R.json().catch(()=>null),G=x?.error?.message;if(x?.error?.type==="authentication_error"&&typeof G=="string"&&G.startsWith("a web page or browser extension calls magpie with a gateway key: ")&&G.includes("magpie's Gateway page"))return{name:"magpie"}}throw new Ye("unauthorized",R.status)}if(!R.ok)throw new Ye("incompatible",R.status);try{return C?await R.text():await R.json()}catch(x){throw p.signal.aborted?x:new Ye("incompatible")}};try{if(o==="magpie"){if((await y("/api/hello"))?.name!=="magpie")throw new Ye("incompatible")}else if(o==="ollama"){if((await y("/",!0)).trim()!=="Ollama is running")throw new Ye("incompatible")}else if(o==="lmstudio"){if((await y("/lmstudio-greeting"))?.lmstudio!==!0)throw new Ye("incompatible")}else if(o==="cliproxyapi"){let T=await y("/");if(T?.message!=="CLI Proxy API Server"||!Array.isArray(T.endpoints)||!["POST /v1/chat/completions","GET /v1/models"].every(C=>T.endpoints.includes(C)))throw new Ye("incompatible");f.providerId="openai-compatible",f.requestStyle="chat_completions"}else if(o==="litellm"){if(await y("/health/liveliness")!=="I'm alive!")throw new Ye("incompatible");let T=await y("/",!0);if(!/<title>\s*LiteLLM API\s*-\s*Swagger UI\s*<\/title>/i.test(T)||!T.includes("SwaggerUIBundle"))throw new Ye("incompatible");f.providerId="openai-compatible",f.requestStyle="chat_completions"}else if(o==="llamacpp"){let T=await _("/health"),C=await T.json().catch(()=>null);if(!(T.ok&&C?.status==="ok")&&!(T.status===503&&C?.error?.type==="unavailable_error"&&C.error.message==="Loading model"))throw new Ye("incompatible");let R=T.headers.get("Server")==="llama.cpp";if(!R)try{let x=await y("/props");R=typeof x?.build_info=="string"&&!!x.build_info.trim()&&Number.isInteger(x.total_slots)&&x.total_slots>0&&typeof x.default_generation_settings?.n_ctx=="number"&&typeof x.chat_template=="string"&&typeof x.model_path=="string"}catch(x){if(!(x instanceof Ye)||!["unauthorized","incompatible"].includes(x.status))throw x}if(!R){let x=await y("/manifest.webmanifest");R=["llama-ui","llama.cpp"].includes(x?.name)&&x?.description==="Local AI chat interface powered by llama.cpp"}if(!R)throw new Ye("incompatible");f.providerId="openai-compatible",f.requestStyle="chat_completions"}else{let T=await y("/health");if(T?.status!=="healthy"||typeof T.timestamp!="string")throw new Ye("incompatible");let C=await y("/status");if(C?.running!==!0||C.port!==l||typeof C.address!="string"||!["active_connections","total_requests","success_requests","failed_requests","uptime_seconds","failover_count"].every(x=>typeof C[x]=="number"&&Number.isFinite(C[x]))||!Array.isArray(C.active_targets)||C.active_targets.some(x=>!x||typeof x.app_type!="string"||typeof x.provider_id!="string"||typeof x.provider_name!="string"))throw new Ye("incompatible");f.providerId="openai-compatible",f.requestStyle="responses";let R=C.active_targets.map(x=>x.app_type.toLowerCase());R.includes("claude")&&!R.includes("codex")&&(f.providerId="anthropic",f.baseURL=c,delete f.requestStyle)}f.status="ready"}catch(T){f.models=[],f.status=m?"timeout":T instanceof Ye?T.status:"unavailable"}finally{clearTimeout(g),e.signal?.removeEventListener("abort",h)}return f}))}function lw(t){if(typeof t!="string")return!1;try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)&&!e.username&&!e.password&&!e.search&&!e.hash&&["","/v1"].includes(e.pathname.replace(/\/+$/,""))}catch{return!1}}async function iz(t,e={}){if(!t||!bh.includes(t.kind))throw new Error("Invalid local service");if(!lw(t.baseURL))throw new Error("Invalid local service address");let n=new URL(t.baseURL);if(t.apiKey!==void 0&&typeof t.apiKey!="string")throw new Error("Invalid API key");if(t.providerId!==void 0&&!["anthropic","openai-compatible"].includes(t.providerId))throw new Error("Invalid local service protocol");let r=e.signal?AbortSignal.any([e.signal,AbortSignal.timeout(e.timeoutMs??1e4)]):AbortSignal.timeout(e.timeoutMs??1e4),i=e.fetch??globalThis.fetch,s=t.apiKey?.trim(),o=s?t.providerId==="anthropic"?{"x-api-key":s}:{Authorization:`Bearer ${s}`}:void 0;if(!PU(t.customHeaders).valid)throw new Error("Invalid custom request headers");let l=aw(t.customHeaders),d=async h=>{let m=await i(n.origin+h,{signal:r,credentials:"omit",redirect:"error",cache:"no-store",...o||l?{headers:{...l,...o}}:{}});if(!m.ok)throw new Error(`HTTP ${m.status}`);return m.json()},c;if(t.kind==="ollama"){let h=await d("/api/tags");c=Array.isArray(h?.models)?h.models.map(m=>({id:m?.name})):void 0}else if(t.kind==="lmstudio"){let h,m=!1;try{h=await d("/api/v1/models")}catch(_){if(!(_ instanceof Error)||_.message!=="HTTP 404")throw _;m=!0,h=await d("/api/v0/models")}let g=m?h?.data:h?.models;if(!Array.isArray(g)||g.some(_=>!_||!["llm","vlm","embedding","embeddings","decision"].includes(_.type)||typeof _[m?"id":"key"]!="string"))throw new Error("Invalid local model catalog");c=g.filter(_=>["llm","vlm"].includes(_.type)).map(_=>({id:m?_.id:_.loaded_instances?.[0]?.id??_.key,display_name:_.display_name}))}else{let h=await d(t.kind==="cc-switch"&&t.providerId==="anthropic"?"/v1/models?limit=1000":"/v1/models");c=t.kind==="cc-switch"&&Array.isArray(h?.models)?h.models.map(m=>({id:m?.slug,display_name:m?.display_name})):h?.data}if(!Array.isArray(c))throw new Error("Invalid local model catalog");let f=[],p=new Set;for(let h of c){if(typeof h?.id!="string"||!h.id.trim())throw new Error("Invalid local model catalog");p.has(h.id)||(p.add(h.id),f.push({value:h.id,label:typeof h.display_name=="string"?h.display_name:h.id}))}return f}var ir=8192,NU=class extends Bu{getProvider(){return{id:"anthropic",name:"Anthropic",description:"Anthropic Claude models (Official SDK)",requiresApiKey:!0,defaultBaseURL:"https://api.anthropic.com",supportsDynamicModels:!0,apiKeyUrl:"https://console.anthropic.com/settings/keys",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){let t="anthropic";return[{id:"claude-sonnet-5",name:"Claude Sonnet 5",description:"Balanced Claude 5 model for coding, agents, and general-purpose work",providerId:t,capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6},parameterDefinitions:this.getParameterDefinitions("claude-sonnet-5"),defaultParameterValues:this.getDefaultParameterValues("claude-sonnet-5")},{id:"claude-opus-5",name:"Claude Opus 5",description:"Most capable Claude model for complex reasoning and agentic tasks",providerId:t,capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6},parameterDefinitions:this.getParameterDefinitions("claude-opus-5"),defaultParameterValues:this.getDefaultParameterValues("claude-opus-5")},{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",description:"Fast, efficient Claude model for high-throughput workloads",providerId:t,capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:2e5},parameterDefinitions:this.getParameterDefinitions("claude-haiku-4-5-20251001"),defaultParameterValues:this.getDefaultParameterValues("claude-haiku-4-5-20251001")}]}async getModelsAsync(t){let e=this.createClient(t);try{let n=await e.models.list();if(n&&n.data&&Array.isArray(n.data)){let r=n.data.map(i=>this.buildDefaultModel(i.id)).sort((i,s)=>i.id.localeCompare(s.id));if(r.length===0)throw new Ue("API returned empty model list");return console.log(`[AnthropicAdapter] Successfully fetched ${r.length} models`),r}throw new Ue("Unexpected API response format")}catch(n){throw console.error("[AnthropicAdapter] Failed to fetch models:",n),n.message&&(n.message.includes("Failed to fetch")||n.message.includes("NetworkError")||n.message.includes("ECONNREFUSED")||n.message.includes("CORS"))?new Ue(`Network error: ${n.message}`):n.status?new Ue(`Anthropic API error (${n.status}): ${n.message}`):n}}getParameterDefinitions(t){let e=[{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-1)",type:"number",defaultValue:1,default:1,minValue:0,maxValue:1,min:0,max:1,step:.1},{name:"top_p",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter",type:"number",defaultValue:1,default:1,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"top_k",labelKey:"params.top_k.label",descriptionKey:"params.top_k.description",description:"Top-k sampling parameter",type:"integer",minValue:1,min:1,step:1}],n=[{name:"max_tokens",labelKey:"params.max_tokens.label",descriptionKey:"params.max_tokens.description",description:"Maximum tokens to generate",type:"integer",defaultValue:ir,default:ir,minValue:1,min:1,unitKey:"params.tokens.unit",step:1},...this.isAdaptiveThinkingModel(t)?[{name:"effort",labelKey:"params.reasoning_effort.label",descriptionKey:"params.reasoning_effort.description",description:"Adaptive reasoning effort for Claude 5.",type:"string",defaultValue:"high",default:"high",allowedValues:["low","medium","high","xhigh","max"]}]:[{name:"thinking_budget_tokens",labelKey:"params.thinkingBudget.label",descriptionKey:"params.thinkingBudget.description",description:"Extended thinking budget in tokens (requires \u22651024)",type:"integer",minValue:1024,min:1024,unitKey:"params.tokens.unit",step:1,tags:["advanced"]}]];return this.isAdaptiveThinkingModel(t)?n:[...e,...n]}getDefaultParameterValues(t){return{max_tokens:ir,...this.isAdaptiveThinkingModel(t)?{effort:"high"}:{}}}isAdaptiveThinkingModel(t){return/^claude-(?:sonnet|opus)-5(?:-|$)/.test(t)}applyThinkingConfig(t,e,n,r){if(this.isAdaptiveThinkingModel(e)){t.thinking={type:"adaptive"},["low","medium","high","xhigh","max"].includes(String(r))&&(t.output_config={...t.output_config||{},effort:r});return}typeof n=="number"&&n>=1024&&(t.thinking={type:"enabled",budget_tokens:n})}async doSendMessage(t,e){let n=this.createClient(e);try{let{max_tokens:r,temperature:i,top_p:s,top_k:o,thinking_budget_tokens:l,effort:d,...c}=e.paramOverrides||{},f={model:e.modelMeta.id,messages:this.convertMessages(t),max_tokens:r??ir};!this.isAdaptiveThinkingModel(e.modelMeta.id)&&i!==void 0&&(f.temperature=i),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&s!==void 0&&(f.top_p=s),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&o!==void 0&&(f.top_k=o);let p=this.extractSystemMessage(t);p&&(f.system=p),Object.assign(f,c),this.applyThinkingConfig(f,e.modelMeta.id,l,d);let h=await n.messages.create(f),m=this.extractThinking(h);return{content:this.extractContent(h),reasoning:m,metadata:{model:h.model,finishReason:h.stop_reason||void 0,tokens:h.usage?(h.usage.input_tokens||0)+(h.usage.output_tokens||0):void 0}}}catch(r){throw this.handleError(r)}}async doSendImageUnderstanding(t,e){let n=this.createClient(e);try{let r={...e.paramOverrides||{},...t.paramOverrides||{}},{max_tokens:i,temperature:s,top_p:o,top_k:l,thinking_budget_tokens:d,effort:c,responseMimeType:f,...p}=r,h={model:e.modelMeta.id,messages:[{role:"user",content:[{type:"text",text:t.userPrompt},...t.images.map(_=>({type:"image",source:{type:"base64",media_type:_.mimeType||"image/png",data:_.b64}}))]}],max_tokens:i??ir};!this.isAdaptiveThinkingModel(e.modelMeta.id)&&s!==void 0&&(h.temperature=s),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&o!==void 0&&(h.top_p=o),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&l!==void 0&&(h.top_k=l),t.systemPrompt?.trim()&&(h.system=t.systemPrompt),Object.assign(h,p),this.applyThinkingConfig(h,e.modelMeta.id,d,c);let m=await n.messages.create(h),g=this.extractThinking(m);return{content:this.extractContent(m),reasoning:g,metadata:{model:m.model,finishReason:m.stop_reason||void 0,tokens:m.usage?(m.usage.input_tokens||0)+(m.usage.output_tokens||0):void 0}}}catch(r){throw this.handleError(r)}}async doSendImageUnderstandingStream(t,e,n){let r=this.createClient(e),i={isInThinkMode:!1,buffer:""};try{let s={...e.paramOverrides||{},...t.paramOverrides||{}},{max_tokens:o,temperature:l,top_p:d,top_k:c,thinking_budget_tokens:f,effort:p,responseMimeType:h,...m}=s,g={model:e.modelMeta.id,messages:[{role:"user",content:[{type:"text",text:t.userPrompt},...t.images.map(C=>({type:"image",source:{type:"base64",media_type:C.mimeType||"image/png",data:C.b64}}))]}],max_tokens:o??ir};!this.isAdaptiveThinkingModel(e.modelMeta.id)&&l!==void 0&&(g.temperature=l),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&d!==void 0&&(g.top_p=d),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&c!==void 0&&(g.top_k=c),t.systemPrompt?.trim()&&(g.system=t.systemPrompt),Object.assign(g,m),this.applyThinkingConfig(g,e.modelMeta.id,f,p);let _=n.signal?await r.messages.stream(g,{signal:n.signal}):await r.messages.stream(g),y="";_.on("thinking",C=>{y+=C,n.onReasoningToken?.(C)}),_.on("text",C=>{this.processStreamContentWithThinkTags(C,n,i)}),_.on("error",C=>{n.onError(C)});let T=await _.finalMessage();await n.onComplete({content:this.extractContent(T),reasoning:y||void 0,metadata:{model:T.model,finishReason:T.stop_reason||void 0,tokens:T.usage?(T.usage.input_tokens||0)+(T.usage.output_tokens||0):void 0}})}catch(s){throw n.onError(this.handleError(s)),s}}async doSendMessageStream(t,e,n){let r=this.createClient(e),i={isInThinkMode:!1,buffer:""};try{let{max_tokens:s,temperature:o,top_p:l,top_k:d,thinking_budget_tokens:c,effort:f,...p}=e.paramOverrides||{},h={model:e.modelMeta.id,messages:this.convertMessages(t),max_tokens:s??ir};!this.isAdaptiveThinkingModel(e.modelMeta.id)&&o!==void 0&&(h.temperature=o),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&l!==void 0&&(h.top_p=l),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&d!==void 0&&(h.top_k=d);let m=this.extractSystemMessage(t);m&&(h.system=m),Object.assign(h,p),this.applyThinkingConfig(h,e.modelMeta.id,c,f);let g=n.signal?await r.messages.stream(h,{signal:n.signal}):await r.messages.stream(h),_="";g.on("thinking",C=>{_+=C,n.onReasoningToken&&n.onReasoningToken(C)}),g.on("text",C=>{this.processStreamContentWithThinkTags(C,n,i)}),g.on("error",C=>{n.onError(C)});let y=await g.finalMessage(),T={content:this.extractContent(y),reasoning:_||void 0,metadata:{model:y.model,finishReason:y.stop_reason||void 0,tokens:y.usage?(y.usage.input_tokens||0)+(y.usage.output_tokens||0):void 0}};await n.onComplete(T)}catch(s){throw n.onError(this.handleError(s)),s}}async sendMessageStreamWithTools(t,e,n,r){let i=this.createClient(e),s={isInThinkMode:!1,buffer:""};try{let{max_tokens:o,temperature:l,top_p:d,top_k:c,thinking_budget_tokens:f,effort:p,...h}=e.paramOverrides||{},m={model:e.modelMeta.id,messages:this.convertMessages(t),tools:this.convertTools(n),max_tokens:o??ir};!this.isAdaptiveThinkingModel(e.modelMeta.id)&&l!==void 0&&(m.temperature=l),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&d!==void 0&&(m.top_p=d),!this.isAdaptiveThinkingModel(e.modelMeta.id)&&c!==void 0&&(m.top_k=c);let g=this.extractSystemMessage(t);g&&(m.system=g),Object.assign(m,h),this.applyThinkingConfig(m,e.modelMeta.id,f,p);let _=r.signal?await i.messages.stream(m,{signal:r.signal}):await i.messages.stream(m),y="",T="",C=[],R=-1;_.on("thinking",S=>{T+=S,r.onReasoningToken&&r.onReasoningToken(S)}),_.on("contentBlockStart",S=>{S.contentBlock?.type==="tool_use"&&(R++,C.push({id:S.contentBlock.id,type:"function",function:{name:S.contentBlock.name,arguments:""}}))}),_.on("contentBlockDelta",S=>{if(S.delta?.type==="text_delta"){let q=S.delta.text||"";y+=q,this.processStreamContentWithThinkTags(q,r,s)}else if(S.delta?.type==="input_json_delta"&&R>=0&&C[R]){C[R].function.arguments+=S.delta.partial_json||"";try{JSON.parse(C[R].function.arguments),r.onToolCall&&r.onToolCall(C[R])}catch{}}}),_.on("error",S=>{r.onError(S)});let x=await _.finalMessage(),G={content:y,reasoning:T||void 0,toolCalls:C.length>0?C:void 0,metadata:{model:x.model,finishReason:x.stop_reason||void 0,tokens:x.usage?(x.usage.input_tokens||0)+(x.usage.output_tokens||0):void 0}};await r.onComplete(G)}catch(o){throw r.onError(this.handleError(o)),o}}createClient(t){let e={apiKey:t.connectionConfig?.apiKey||"",dangerouslyAllowBrowser:!0};if(!t.connectionConfig?.apiKey&&lw(t.connectionConfig?.baseURL)&&(e.defaultHeaders={"X-Api-Key":null,Authorization:null}),t.connectionConfig?.baseURL){let n=t.connectionConfig.baseURL;n.endsWith("/v1")&&(n=n.slice(0,-3)),e.baseURL=n}return t.connectionConfig?.timeout&&(e.timeout=t.connectionConfig.timeout),new Nh(e)}convertMessages(t){return t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}extractSystemMessage(t){let e=t.filter(n=>n.role==="system");return e.length>0?e.map(n=>n.content).join(`
84
+ `):void 0}extractContent(t){return!t.content||t.content.length===0?"":t.content.filter(e=>e.type==="text").map(e=>e.text).join("")}convertTools(t){return t.map(e=>({name:e.function.name,description:e.function.description||"",input_schema:{type:"object",properties:e.function.parameters?.properties||{},required:e.function.parameters?.required||[]}}))}extractThinking(t){if(!t.content||t.content.length===0)return;let e=t.content.filter(n=>n.type==="thinking");if(e.length!==0)return e.map(n=>n.thinking).join(`
85
+ `)}handleError(t){return t.status?new Error(`Anthropic API error (${t.status}): ${t.message}`):t instanceof Error?t:new Error(String(t))}},MU=[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",description:"Latest Gemini Flash model for fast multimodal reasoning and agentic workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"gemini-3.5-flash-lite",name:"Gemini 3.5 Flash-Lite",description:"Efficient Gemini model for high-throughput, cost-sensitive workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"Advanced Gemini Pro preview model for complex reasoning and coding",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}}],DU=class extends Bu{getProvider(){return{id:"gemini",name:"Google Gemini",description:"Google Generative AI models",requiresApiKey:!0,defaultBaseURL:"https://generativelanguage.googleapis.com",supportsDynamicModels:!0,apiKeyUrl:"https://aistudio.google.com/apikey",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return MU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}async getModelsAsync(t){try{let e=t.connectionConfig.apiKey||"",n=t.connectionConfig.baseURL,i=await new xo(n?{apiKey:e,httpOptions:{baseUrl:n}}:{apiKey:e}).models.list({config:{pageSize:100}}),s=[],o="gemini";for await(let l of i)s.push({id:l.name?.replace("models/","")||l.name||"",name:l.displayName||l.name||"",description:l.description||"",providerId:o,capabilities:{supportsTools:!0,supportsReasoning:!1,maxContextLength:l.inputTokenLimit||1e6},parameterDefinitions:this.getParameterDefinitions(l.name||""),defaultParameterValues:this.getDefaultParameterValues(l.name||"")});return s.length>0?s:this.getModels()}catch(e){return console.error("[GeminiAdapter] Failed to fetch models dynamically, falling back to static list:",e),this.getModels()}}getParameterDefinitions(t){let e=[{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-2)",type:"number",defaultValue:1,default:1,minValue:0,maxValue:2,min:0,max:2,step:.1},{name:"topP",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter",type:"number",defaultValue:.95,default:.95,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"topK",labelKey:"params.top_k.label",descriptionKey:"params.top_k.description",description:"Top-k sampling parameter",type:"integer",defaultValue:1,default:1,minValue:1,min:1,step:1},{name:"maxOutputTokens",labelKey:"params.maxOutputTokens.label",descriptionKey:"params.maxOutputTokens.description",description:"Maximum tokens to generate",type:"integer",defaultValue:8192,default:8192,minValue:1,min:1,unitKey:"params.tokens.unit",step:1},{name:"candidateCount",labelKey:"params.candidateCount.label",descriptionKey:"params.candidateCount.description",description:"Number of response candidates",type:"integer",defaultValue:1,default:1,minValue:1,maxValue:8,min:1,max:8,step:1},{name:"stopSequences",labelKey:"params.stopSequences.label",descriptionKey:"params.stopSequences.description",description:"Stop sequences for generation",type:"string",defaultValue:[],tags:["string-array"]},{name:"thinkingBudget",labelKey:"params.thinkingBudget.label",descriptionKey:"params.thinkingBudget.description",description:"Thinking budget in tokens (Gemini 2.5+). Set to 0 to disable thinking.",type:"number",defaultValue:0,default:0,minValue:0,maxValue:8192,min:0,max:8192,unitKey:"params.tokens.unit",step:1},{name:"includeThoughts",labelKey:"params.includeThoughts.label",descriptionKey:"params.includeThoughts.description",description:"Include thinking process in response (Gemini 2.5+)",type:"boolean",defaultValue:!1}];if(this.isGemini3Model(t)){let n=t.replace(/^models\//,""),r=n.startsWith("gemini-3.1-pro")||n.startsWith("gemini-3.8-")?["low","medium","high"]:["minimal","low","medium","high"];return[...e.filter(i=>i.name==="thinkingBudget"?!1:this.usesDeprecatedSamplingParameters(t)?!["temperature","topP","topK","candidateCount"].includes(i.name):!0),{name:"thinkingLevel",labelKey:"params.reasoning_effort.label",descriptionKey:"params.reasoning_effort.description",description:"Dynamic thinking level for Gemini 3 models.",type:"string",allowedValues:r}]}return e}getDefaultParameterValues(t){return{}}createClient(t){let e=t.connectionConfig.apiKey||"",n=t.connectionConfig.baseURL;return new xo(n?{apiKey:e,httpOptions:{baseUrl:n}}:{apiKey:e})}buildGenerationConfig(t,e={},n){let{temperature:r,maxOutputTokens:i,topP:s,topK:o,candidateCount:l,stopSequences:d,thinkingBudget:c,thinkingLevel:f,includeThoughts:p,...h}=e,m={};n&&(m.systemInstruction=n);let g=!this.usesDeprecatedSamplingParameters(t);g&&r!==void 0&&(m.temperature=r),i!==void 0&&(m.maxOutputTokens=i),g&&s!==void 0&&(m.topP=s),g&&o!==void 0&&(m.topK=o),!this.usesDeprecatedSamplingParameters(t)&&l!==void 0&&(m.candidateCount=l),d!==void 0&&Array.isArray(d)&&(m.stopSequences=d),(c!==void 0||f!==void 0||p!==void 0)&&(m.thinkingConfig={},!this.isGemini3Model(t)&&c!==void 0&&(m.thinkingConfig.thinkingBudget=c),this.isGemini3Model(t)&&f!==void 0&&(m.thinkingConfig.thinkingLevel=f),p!==void 0&&(m.thinkingConfig.includeThoughts=p));for(let[_,y]of Object.entries(h))["timeout","model","messages","stream"].includes(_)||(m[_]=y);return m}usesDeprecatedSamplingParameters(t){let e=t.replace(/^models\//,"");return e.startsWith("gemini-3.5-")||e.startsWith("gemini-3.6-")||e.startsWith("gemini-3.8-")}isGemini3Model(t){return t.replace(/^models\//,"").startsWith("gemini-3")}convertToolsToGemini(t){return!t||t.length===0?[]:[{functionDeclarations:t.map(n=>({name:n.function.name,description:n.function.description,parameters:n.function.parameters}))}]}convertGeminiFunctionCallsToToolCalls(t){return!t||t.length===0?[]:t.map(e=>({id:e.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:e.name||"",arguments:JSON.stringify(e.args||{})}}))}formatMessages(t){let e=[];for(let n of t)n.role==="user"?e.push({role:"user",parts:[{text:n.content}]}):n.role==="assistant"&&e.push({role:"model",parts:[{text:n.content}]});return e}async doSendMessage(t,e){let n=t.filter(s=>s.role==="system"),r=n.length>0?n.map(s=>s.content).join(`
86
+ `):"",i=t.filter(s=>s.role!=="system");if(i.length===0)return{content:"",metadata:{model:e.modelMeta.id}};try{let s=this.createClient(e),o=this.buildGenerationConfig(e.modelMeta.id,e.paramOverrides||{},r),l=this.formatMessages(i),d=await s.models.generateContent({model:e.modelMeta.id,contents:l,config:o});return this.extractResponsePayload(d,e.modelMeta.id)}catch(s){throw console.error("[GeminiAdapter] API call failed:",s),s}}async doSendImageUnderstanding(t,e){try{let n=this.createClient(e),r={...e.paramOverrides||{},...t.paramOverrides||{}},i=this.buildGenerationConfig(e.modelMeta.id,r,t.systemPrompt);t.responseMimeType&&(i.responseMimeType=t.responseMimeType);let s=[{role:"user",parts:[{text:t.userPrompt},...t.images.map(l=>({inlineData:{mimeType:l.mimeType||"image/png",data:l.b64}}))]}],o=await n.models.generateContent({model:e.modelMeta.id,contents:s,config:i});return this.extractResponsePayload(o,e.modelMeta.id)}catch(n){throw console.error("[GeminiAdapter] Image understanding request failed:",n),n}}async doSendImageUnderstandingStream(t,e,n){try{let r=this.createClient(e),i={...e.paramOverrides||{},...t.paramOverrides||{}},s=this.buildGenerationConfig(e.modelMeta.id,i,t.systemPrompt);t.responseMimeType&&(s.responseMimeType=t.responseMimeType);let o=[{role:"user",parts:[{text:t.userPrompt},...t.images.map(f=>({inlineData:{mimeType:f.mimeType||"image/png",data:f.b64}}))]}],l=await r.models.generateContentStream({model:e.modelMeta.id,contents:o,config:{...s,abortSignal:n.signal}}),d="",c="";for await(let f of l){let p=!1;if(f.candidates?.[0]?.content?.parts)for(let m of f.candidates[0].content.parts){let g=m.text;g&&(m.thought?(c+=g,n.onReasoningToken?.(g)):(p=!0,d+=g,n.onToken(g)))}let h=f.text;h&&!p&&(d+=h,n.onToken(h))}await n.onComplete({content:d,reasoning:c||void 0,metadata:{model:e.modelMeta.id}})}catch(r){throw console.error("[GeminiAdapter] Image understanding stream failed:",r),n.onError(r instanceof Error?r:new Error(String(r))),r}}extractResponsePayload(t,e){let n="",r;if(t.text)n=t.text;else if(t.candidates?.[0]?.content?.parts){let i=[],s=[];for(let o of t.candidates[0].content.parts)if(o.text){let l=o.text;o.thought?s.push(l):i.push(l)}n=i.join(""),s.length>0&&(r=s.join(""))}else if(t.candidates?.[0]?.content){let i=t.candidates[0].content;typeof i=="string"?n=i:i.text&&(n=i.text)}return{content:n,reasoning:r,metadata:{model:e,finishReason:t.candidates?.[0]?.finishReason}}}async doSendMessageStream(t,e,n){let r=t.filter(o=>o.role==="system"),i=r.length>0?r.map(o=>o.content).join(`
87
+ `):"",s=t.filter(o=>o.role!=="system");if(s.length===0){let o={content:"",metadata:{model:e.modelMeta.id}};await n.onComplete(o);return}try{let o=this.createClient(e),l=this.buildGenerationConfig(e.modelMeta.id,e.paramOverrides||{},i),d=this.formatMessages(s),c=await o.models.generateContentStream({model:e.modelMeta.id,contents:d,config:{...l,abortSignal:n.signal}}),f="",p="";for await(let m of c){let g=!1;if(m.candidates?.[0]?.content?.parts)for(let y of m.candidates[0].content.parts){let T=y.text;T&&(y.thought?(p+=T,n.onReasoningToken&&n.onReasoningToken(T)):(g=!0,f+=T,n.onToken(T)))}let _=m.text;_&&!g&&(f+=_,n.onToken(_))}let h={content:f,reasoning:p||void 0,metadata:{model:e.modelMeta.id}};await n.onComplete(h)}catch(o){throw console.error("[GeminiAdapter] Stream error:",o),n.onError(o instanceof Error?o:new Error(String(o))),o}}async doSendMessageStreamWithTools(t,e,n,r){let i=t.filter(l=>l.role==="system"),s=i.length>0?i.map(l=>l.content).join(`
88
+ `):"",o=t.filter(l=>l.role!=="system");if(o.length===0){let l={content:"",metadata:{model:e.modelMeta.id}};await r.onComplete(l);return}try{let l=this.createClient(e),d=this.buildGenerationConfig(e.modelMeta.id,e.paramOverrides||{},s),c=this.convertToolsToGemini(n);c.length>0&&(d.tools=c);let f=this.formatMessages(o),p=await l.models.generateContentStream({model:e.modelMeta.id,contents:f,config:{...d,abortSignal:r.signal}}),h="",m="",g=[];for await(let y of p){let T=y.text;if(T&&(h+=T,r.onToken(T)),y.functionCalls&&y.functionCalls.length>0){let C=this.convertGeminiFunctionCallsToToolCalls(y.functionCalls);g.push(...C),r.onToolCall&&C.forEach(R=>r.onToolCall(R))}if(y.candidates?.[0]?.content?.parts){for(let C of y.candidates[0].content.parts)if(C.thought){let R=C.text??C.thought;if(R!==void 0){let x=typeof R=="string"?R:JSON.stringify(R);m+=x,r.onReasoningToken&&r.onReasoningToken(x)}}}}let _={content:h,reasoning:m||void 0,toolCalls:g.length>0?g:void 0,metadata:{model:e.modelMeta.id}};await r.onComplete(_)}catch(l){throw console.error("[GeminiAdapter] Stream with tools error:",l),r.onError(l instanceof Error?l:new Error(String(l))),l}}},OU=[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",description:"DeepSeek V4 Flash model via OpenAI-compatible API",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6},defaultParameterValues:{thinking_type:"disabled"}},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",description:"DeepSeek V4 Pro model via OpenAI-compatible API",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6},defaultParameterValues:{thinking_type:"disabled"}}],UU=class extends et{getProvider(){return{id:"deepseek",name:"DeepSeek",description:"DeepSeek OpenAI-compatible models",requiresApiKey:!0,defaultBaseURL:"https://api.deepseek.com",supportsDynamicModels:!0,apiKeyUrl:"https://platform.deepseek.com/api_keys",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return OU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}getParameterDefinitions(t){return[{name:"thinking_type",labelKey:"params.deepseek.thinking_type.label",descriptionKey:"params.deepseek.thinking_type.description",description:"Controls DeepSeek thinking mode. Sent as thinking.type in the API request.",type:"string",defaultValue:"disabled",default:"disabled",allowedValues:["disabled","enabled"],allowedValueLabelKeys:["params.deepseek.thinking_type.disabled","params.deepseek.thinking_type.enabled"]},{name:"reasoning_effort",labelKey:"params.reasoning_effort.label",descriptionKey:"params.reasoning_effort.description",description:"Reasoning effort for thinking mode. DeepSeek supports high and max.",type:"string",allowedValues:["high","max"]},{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-2). Ineffective when thinking mode is enabled.",type:"number",defaultValue:1,default:1,minValue:0,maxValue:2,min:0,max:2,step:.1},{name:"top_p",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter (0-1). Ineffective when thinking mode is enabled.",type:"number",defaultValue:1,default:1,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"max_tokens",labelKey:"params.max_tokens.label",descriptionKey:"params.max_tokens.description",description:"Maximum tokens in the generated completion.",type:"integer",minValue:1,maxValue:393216,min:1,max:393216,step:1,unitKey:"params.tokens.unit"},{name:"presence_penalty",labelKey:"params.presence_penalty.label",descriptionKey:"params.presence_penalty.description",description:"Presence penalty (-2.0 to 2.0). Ineffective when thinking mode is enabled.",type:"number",defaultValue:0,default:0,minValue:-2,maxValue:2,min:-2,max:2,step:.1},{name:"frequency_penalty",labelKey:"params.frequency_penalty.label",descriptionKey:"params.frequency_penalty.description",description:"Frequency penalty (-2.0 to 2.0). Ineffective when thinking mode is enabled.",type:"number",defaultValue:0,default:0,minValue:-2,maxValue:2,min:-2,max:2,step:.1},{name:"logprobs",labelKey:"params.logprobs.label",descriptionKey:"params.logprobs.description",description:"Return log probabilities of output tokens",type:"boolean",defaultValue:!1,default:!1},{name:"top_logprobs",labelKey:"params.top_logprobs.label",descriptionKey:"params.top_logprobs.description",description:"Number of most likely tokens to return (0-20). Requires logprobs=true.",type:"integer",minValue:0,maxValue:20,min:0,max:20,step:1},{name:"timeout",labelKey:"params.timeout.label",descriptionKey:"params.timeout.description_openai",description:"Client timeout in milliseconds (OpenAI SDK setting)",type:"integer",defaultValue:6e4,default:6e4,minValue:1e3,maxValue:6e5,min:1e3,max:6e5,step:1e3,unit:"ms"}]}getDefaultParameterValues(t){return{thinking_type:"disabled"}}async doSendMessage(t,e){return super.doSendMessage(t,this.normalizeDeepseekConfig(e))}async doSendMessageStream(t,e,n){await super.doSendMessageStream(t,this.normalizeDeepseekConfig(e),n)}async sendMessageStreamWithTools(t,e,n,r){await super.sendMessageStreamWithTools(t,this.normalizeDeepseekConfig(e),n,r)}async doSendImageUnderstanding(t,e){return super.doSendImageUnderstanding(this.normalizeDeepseekImageRequest(t),this.normalizeDeepseekConfig(e))}async doSendImageUnderstandingStream(t,e,n){await super.doSendImageUnderstandingStream(this.normalizeDeepseekImageRequest(t),this.normalizeDeepseekConfig(e),n)}normalizeDeepseekConfig(t){let e=this.normalizeDeepseekParamOverrides(t.paramOverrides,!0);return{...t,paramOverrides:e}}normalizeDeepseekImageRequest(t){return t.paramOverrides?{...t,paramOverrides:this.normalizeDeepseekParamOverrides(t.paramOverrides,!1)}:t}normalizeDeepseekParamOverrides(t,e=!0){let{thinking_type:n,thinking:r,...i}=t||{},s=this.normalizeThinkingType(n)??this.extractExplicitThinkingType(r)??(e?"disabled":void 0);return s?{...i,thinking:{type:s}}:i}normalizeThinkingType(t){return t==="enabled"||t==="disabled"?t:void 0}extractExplicitThinkingType(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return this.normalizeThinkingType(t.type)}},LU=[{id:"Qwen/Qwen3-8B",name:"Qwen3-8B",description:"Qwen3-8B model via SiliconFlow",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:128e3}}],FU=class extends et{getProvider(){return{id:"siliconflow",name:"SiliconFlow",description:"SiliconFlow OpenAI-compatible models",requiresApiKey:!0,defaultBaseURL:"https://api.siliconflow.cn/v1",supportsDynamicModels:!0,apiKeyUrl:"https://cloud.siliconflow.cn/account/ak",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return LU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}},GU=[{id:"glm-5.3-flash",name:"GLM-5.3-Flash",description:"Latest efficient multimodal GLM model for reasoning, coding, and agentic tasks",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"glm-5.3",name:"GLM-5.3",description:"Latest GLM flagship model for complex reasoning, coding, and agentic tasks",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"glm-5.2",name:"GLM-5.2",description:"Previous GLM flagship model retained for compatibility",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}}],qU=class extends et{getProvider(){return{id:"zhipu",name:"Zhipu AI",description:"Zhipu GLM OpenAI-compatible models",requiresApiKey:!0,defaultBaseURL:"https://open.bigmodel.cn/api/paas/v4",supportsDynamicModels:!0,apiKeyUrl:"https://open.bigmodel.cn/usercenter/apikeys",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return GU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}getParameterDefinitions(t){return super.getParameterDefinitions(t).map(e=>e.name!=="reasoning_effort"||!/^glm-5\.(?:2|3)/.test(t)?e:{...e,description:"Reasoning effort for current GLM models.",defaultValue:"max",default:"max",allowedValues:t==="glm-5.2"?["high","max"]:["low","high","max"]})}},BU=[{id:"qwen3.7-plus",name:"Qwen3.7 Plus",description:"Latest Qwen Plus model for complex reasoning and agentic workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"qwen3.8-flash",name:"Qwen3.8 Flash",description:"Fast Qwen model for low-latency general-purpose workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"qwen3.8-max",name:"Qwen3.8 Max",description:"Latest Qwen flagship model for complex reasoning and agentic workloads",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"qwen-plus",name:"Qwen Plus",description:"High-performance Qwen model for complex tasks with long-context support",capabilities:{supportsTools:!0,supportsReasoning:!1,maxContextLength:131072}},{id:"qwen-turbo",name:"Qwen Turbo",description:"Fast Qwen model with long-context support up to 1M tokens",capabilities:{supportsTools:!0,supportsReasoning:!1,maxContextLength:1e6}},{id:"qwen-flash",name:"Qwen Flash",description:"Lightweight Qwen model optimized for fast responses and simple tasks",capabilities:{supportsTools:!0,supportsReasoning:!1,maxContextLength:131072}}],$U=class extends et{getProvider(){return{id:"dashscope",name:"DashScope",description:"Alibaba Cloud Model Studio provider for Qwen models with OpenAI-compatible Chat Completions and Responses APIs",requiresApiKey:!0,defaultBaseURL:"https://dashscope.aliyuncs.com/compatible-mode/v1",supportsDynamicModels:!0,apiKeyUrl:"https://bailian.console.aliyun.com/#/api-key",connectionSchema:{required:["apiKey"],optional:["baseURL","requestStyle"],fieldTypes:{apiKey:"string",baseURL:"string",requestStyle:"string"}}}}getModels(){return BU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}getParameterDefinitions(t){return[{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-2). Higher values make output more random.",type:"number",defaultValue:1,default:1,minValue:0,maxValue:2,min:0,max:2,step:.1},{name:"top_p",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter (0-1). Alternative to temperature.",type:"number",defaultValue:.8,default:.8,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"max_tokens",labelKey:"params.max_tokens.label",descriptionKey:"params.max_tokens.description",description:"Maximum tokens to generate",type:"integer",minValue:1,maxValue:16384,min:1,max:16384,step:1,unitKey:"params.tokens.unit"},{name:"presence_penalty",labelKey:"params.presence_penalty.label",descriptionKey:"params.presence_penalty.description",description:"Presence penalty (-2.0 to 2.0). Penalizes tokens based on presence.",type:"number",defaultValue:0,default:0,minValue:-2,maxValue:2,min:-2,max:2,step:.1},{name:"seed",labelKey:"params.seed.label",descriptionKey:"params.seed.description",description:"Seed for deterministic sampling (integer)",type:"integer",minValue:0,maxValue:2147483647,min:0,max:2147483647,step:1},{name:"enable_thinking",labelKey:"params.enable_thinking.label",descriptionKey:"params.enable_thinking.description",description:"Enable thinking mode for complex reasoning tasks (via extra_body)",type:"boolean",defaultValue:!1,default:!1,tags:["extra_body"]},{name:"thinking_budget",labelKey:"params.thinking_budget.label",descriptionKey:"params.thinking_budget.description",description:"Maximum tokens for thinking process. Limits reasoning length (via extra_body)",type:"integer",minValue:0,maxValue:2e4,min:0,max:2e4,step:100,unitKey:"params.tokens.unit",tags:["extra_body"]},{name:"enable_search",labelKey:"params.enable_search.label",descriptionKey:"params.enable_search.description",description:"Enable internet search for real-time information (via extra_body)",type:"boolean",defaultValue:!1,default:!1,tags:["extra_body"]}]}getDefaultParameterValues(t){return{enable_thinking:!1}}},VU=[{id:"openrouter/free",name:"OpenRouter Free Models Router",description:"OpenRouter router that selects a compatible free model for each request",capabilities:{supportsTools:!0,supportsReasoning:!1,maxContextLength:2e5}}],HU=class extends et{getProvider(){return{id:"openrouter",name:"OpenRouter",description:"OpenAI-compatible gateway for accessing models from many providers",requiresApiKey:!0,defaultBaseURL:"https://openrouter.ai/api/v1",supportsDynamicModels:!0,apiKeyUrl:"https://openrouter.ai/settings/keys",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return VU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}},KU=[{id:"Qwen/Qwen3-Coder-480B-A35B-Instruct",name:"Qwen3-Coder-480B-A35B-Instruct",description:"Qwen3-Coder model optimized for code generation and understanding",capabilities:{supportsTools:!1,supportsReasoning:!1,maxContextLength:131072}}],WU=class extends et{getProvider(){return{id:"modelscope",name:"ModelScope",description:"ModelScope API-Inference service for community-hosted open models",requiresApiKey:!0,defaultBaseURL:"https://api-inference.modelscope.cn/v1",supportsDynamicModels:!0,apiKeyUrl:"https://modelscope.cn/my/myaccesstoken",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return KU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}},JU="http://localhost:11434/v1",zU="ollama",YU=class extends et{getProvider(){return{id:"ollama",name:"Ollama",description:"Local Ollama (OpenAI-compatible API)",corsRestricted:!1,requiresApiKey:!1,defaultBaseURL:JU,supportsDynamicModels:!0,connectionSchema:{required:[],optional:["baseURL","apiKey"],fieldTypes:{baseURL:"string",apiKey:"string"}}}}getModels(){return[]}createOpenAIInstance(t,e=!1){let n=typeof t.connectionConfig.apiKey=="string"?t.connectionConfig.apiKey:"",r=n.trim()?n:zU,i=typeof t.connectionConfig.baseURL=="string"?t.connectionConfig.baseURL:"",s=this.normalizeBaseURL(i),o={...t,connectionConfig:{...t.connectionConfig,apiKey:r,baseURL:s}};return super.createOpenAIInstance(o,e)}normalizeBaseURL(t){let e=this.getProvider().defaultBaseURL,r=(t.trim()?t.trim():e).replace(/\/$/,"");return r.endsWith("/chat/completions")&&(r=r.slice(0,-17).replace(/\/$/,"")),/\/v1$/.test(r)?r:`${r}/v1`}},XU=class extends et{getProvider(){return{id:"magpie",name:"Magpie",description:"Local Magpie gateway (OpenAI-compatible API)",requiresApiKey:!1,defaultBaseURL:"http://127.0.0.1:3425/v1",supportsDynamicModels:!0,connectionSchema:{required:[],optional:["baseURL","apiKey"],fieldTypes:{baseURL:"string",apiKey:"string"}}}}getModels(){return[]}},QU=[{region:"global_en",openaiBaseURL:"https://api.minimax.io/v1",anthropicBaseURL:"https://api.minimax.io/anthropic",docsRoot:"https://platform.minimax.io/docs"},{region:"cn_zh",openaiBaseURL:"https://api.minimaxi.com/v1",anthropicBaseURL:"https://api.minimaxi.com/anthropic",docsRoot:"https://platform.minimaxi.com/docs"}],ZU=[{id:"MiniMax-M3",name:"MiniMax M3",description:"Latest flagship model with enhanced reasoning and coding",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"MiniMax-M2.7",name:"MiniMax M2.7",description:"Previous flagship model retained for compatibility",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:204800}},{id:"MiniMax-M2.7-highspeed",name:"MiniMax M2.7 HighSpeed",description:"High-speed version of M2.7 for low-latency scenarios",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:204800}}],jU=class extends et{getProvider(){return{id:"minimax",name:"MiniMax",description:"MiniMax AI models via OpenAI-compatible API. The default endpoint is global; Mainland China users should use https://api.minimaxi.com/v1.",requiresApiKey:!0,defaultBaseURL:"https://api.minimax.io/v1",regionalEndpoints:QU,supportsDynamicModels:!0,apiKeyUrl:"https://platform.minimaxi.com/user-center/basic-information/interface-key",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return ZU.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}},eL=[{id:"@cf/qwen/qwen3-30b-a3b-fp8",name:"Qwen3 30B A3B FP8",description:"Default recommended Cloudflare Workers AI text model with tool calling and reasoning output support",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:32768}}],tL=class extends et{getProvider(){return{id:"cloudflare",name:"Cloudflare",description:"Cloudflare Workers AI text models with dynamic model discovery",corsRestricted:!0,requiresApiKey:!0,defaultBaseURL:"https://api.cloudflare.com/client/v4/accounts/{accountId}/ai/v1",supportsDynamicModels:!0,apiKeyUrl:"https://dash.cloudflare.com/profile/api-tokens",connectionSchema:{required:["apiKey","accountId"],optional:["baseURL"],fieldTypes:{apiKey:"string",accountId:"string",baseURL:"string"}}}}async getModelsAsync(t){let e=this.getAccountId(t),r=`${this.resolveCloudflareManagementBaseURL(t.connectionConfig.baseURL,e)}/models/search?task=${encodeURIComponent("Text Generation")}&hide_experimental=true&per_page=100`,i=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.connectionConfig.apiKey||""}`}});if(!i.ok)throw new Ue(`Cloudflare model search failed: ${await this.getErrorMessage(i)}`);let s=await i.json();if(!s?.success||!Array.isArray(s?.result))throw new Ue("Cloudflare model search returned an unexpected response format");let o=s.result.filter(l=>l?.task?.name==="Text Generation"&&typeof l?.name=="string"&&!!l.name.trim()).map(l=>this.mapDynamicModel(l));return o.length>0?o:this.getModels()}getModels(){return eL.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:t.defaultParameterValues?{...e.defaultParameterValues??{},...t.defaultParameterValues}:e.defaultParameterValues}})}createOpenAIInstance(t,e=!1){let n=this.getAccountId(t),r={...t,connectionConfig:{...t.connectionConfig,baseURL:this.resolveCloudflareApiBaseURL(t.connectionConfig.baseURL,n)}};return super.createOpenAIInstance(r,e)}getAccountId(t){let e=String(t.connectionConfig.accountId||"").trim();if(!e)throw new Ie("Cloudflare requires accountId in connection config");return e}resolveCloudflareApiBaseURL(t,e){let n=this.getProvider().defaultBaseURL,r=(t||n).trim();r.endsWith("/chat/completions")&&(r=r.slice(0,-17));let i=encodeURIComponent(e),s=r.replace(/\/$/,"");return s.includes("{accountId}")?s.replace("{accountId}",i):/\/client\/v4\/accounts\/[^/]+\/ai\/v1$/.test(s)?s:/\/client\/v4\/accounts\/[^/]+$/.test(s)?`${s}/ai/v1`:/\/client\/v4$/.test(s)?`${s}/accounts/${i}/ai/v1`:s}resolveCloudflareManagementBaseURL(t,e){return this.resolveCloudflareApiBaseURL(t,e).replace(/\/ai\/v1$/,"/ai")}mapDynamicModel(t){let e=t.name.trim(),n=this.buildDefaultModel(e),r=this.toPropertyMap(t.properties),i=this.parseIntegerProperty(r.context_window),s=this.parseBooleanProperty(r.function_calling),o=this.parseBooleanProperty(r.reasoning);return{...n,name:this.toDisplayName(e),description:this.buildModelDescription(t,r),capabilities:{supportsTools:s,supportsReasoning:o,maxContextLength:i??n.capabilities.maxContextLength}}}toPropertyMap(t){let e={};for(let n of t||[])n?.property_id&&(e[n.property_id]=n.value);return e}parseIntegerProperty(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()){let e=Number.parseInt(t,10);return Number.isFinite(e)?e:void 0}}parseBooleanProperty(t){return typeof t=="boolean"?t:typeof t=="string"?t.toLowerCase()==="true":!1}toDisplayName(t){return(t.split("/").pop()||t).split(/[-_]/g).filter(Boolean).map(r=>{let i=r.toLowerCase();return i==="gpt"?"GPT":i==="oss"?"OSS":i==="qwq"?"QwQ":i.startsWith("qwen")?`Qwen${r.slice(4)}`:i==="llama"?"Llama":i==="kimi"?"Kimi":i==="gemma"?"Gemma":/^\d+(\.\d+)?$/.test(r)?r:/^\d+b$/i.test(r)||/^a\d+b$/i.test(r)||/^(fp|int)\d+$/i.test(r)||i==="awq"?r.toUpperCase():r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}buildModelDescription(t,e){let n=[],r=typeof t.description=="string"?t.description.trim():"";r&&n.push(r);let i=this.parseIntegerProperty(e.context_window);i&&n.push(`Context: ${i.toLocaleString()} tokens`);let s=this.buildPriceSummary(e.price);return s&&n.push(s),n.join(" ")}buildPriceSummary(t){if(!Array.isArray(t)||t.length===0)return;let e=t.map(n=>{if(!n||typeof n!="object")return null;let r=n.price,i=n.unit;return typeof r!="number"||typeof i!="string"?null:`$${r}/${i}`}).filter(n=>!!n);return e.length>0?`Pricing: ${e.join(", ")}`:void 0}async getErrorMessage(t){let e=`${t.status} ${t.statusText}`;try{let n=await t.json();return n?.errors?.[0]?.message||n?.messages?.[0]?.message||n?.message||e}catch{try{return await t.text()||e}catch{return e}}}},nL=[{id:"grok-4.6",name:"Grok 4.6",description:"xAI Grok 4.6 reasoning model via OpenAI-compatible Chat Completions API",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:5e5},defaultParameterValues:{reasoning_effort:"high"}}],rL=class extends et{getProvider(){return{id:"grok",name:"Grok",description:"xAI Grok models via OpenAI-compatible API",requiresApiKey:!0,defaultBaseURL:"https://api.x.ai/v1",supportsDynamicModels:!0,apiKeyUrl:"https://console.x.ai/team/default/api-keys",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return nL.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}},defaultParameterValues:{...e.defaultParameterValues??{},...t.defaultParameterValues??{}}}})}async getModelsAsync(t){let e=this.normalizeBaseUrl(t.connectionConfig.baseURL||this.getProvider().defaultBaseURL),n=t.connectionConfig.apiKey;try{let r=await fetch(`${e}/language-models`,{method:"GET",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}}});if(!r.ok)return console.warn(`Grok language models API error: ${r.status}`),this.getModels();let i=await r.json(),o=(Array.isArray(i?.models)?i.models:Array.isArray(i?.data)?i.data:[]).map(l=>{let d=typeof l=="string"?l:l?.id;return typeof d=="string"&&d.trim()?this.buildDefaultModel(d):null}).filter(l=>!!l).sort((l,d)=>l.id.localeCompare(d.id));return o.length>0?o:this.getModels()}catch(r){return console.warn("Failed to fetch Grok language models:",r),this.getModels()}}getRequestStyle(){return"chat_completions"}getParameterDefinitions(t){return[{name:"reasoning_effort",labelKey:"params.reasoning_effort.label",descriptionKey:"params.reasoning_effort.description",description:"Reasoning effort for Grok 4.6.",type:"string",defaultValue:"high",default:"high",allowedValues:["low","medium","high","xhigh"]},{name:"temperature",labelKey:"params.temperature.label",descriptionKey:"params.temperature.description",description:"Sampling temperature (0-2).",type:"number",defaultValue:1,default:1,minValue:0,maxValue:2,min:0,max:2,step:.1},{name:"top_p",labelKey:"params.top_p.label",descriptionKey:"params.top_p.description",description:"Nucleus sampling parameter (0-1).",type:"number",defaultValue:1,default:1,minValue:0,maxValue:1,min:0,max:1,step:.01},{name:"max_completion_tokens",labelKey:"params.max_completion_tokens.label",descriptionKey:"params.max_completion_tokens.description",description:"Maximum tokens in completion.",type:"integer",minValue:1,maxValue:1e6,min:1,max:1e6,step:1,unitKey:"params.tokens.unit"},{name:"timeout",labelKey:"params.timeout.label",descriptionKey:"params.timeout.description_openai",description:"Client timeout in milliseconds.",type:"integer",defaultValue:6e4,default:6e4,minValue:1e3,maxValue:6e5,min:1e3,max:6e5,step:1e3,unit:"ms"}]}getDefaultParameterValues(t){return{reasoning_effort:"high"}}normalizeBaseUrl(t){let e=t.replace(/\/$/,"");return/\/v1$/.test(e)?e:`${e}/v1`}buildDefaultModel(t){let e=super.buildDefaultModel(t),n=this.normalizeReasoningEffort(e.defaultParameterValues?.reasoning_effort);return{...e,defaultParameterValues:{...e.defaultParameterValues||{},reasoning_effort:n??"high"}}}normalizeReasoningEffort(t){return t==="low"||t==="medium"||t==="high"||t==="xhigh"?t:void 0}},Gu="chrome-built-in",vh="gemini-nano",iL="chrome-built-in-availability",sL=t=>typeof t=="string"?t.trim().length>0:Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:t!=null&&t!==!1,oz=t=>!t||t.id!==Gu||t.providerMeta?.id!==Gu||t.enabled||t.activationState?.userConfigured?!1:!Object.values(t.connectionConfig||{}).some(sL),az=t=>({enabled:!0,activationState:{...t.activationState||{},userConfigured:!1,autoEnabledBy:iL}}),lz=(t,e)=>({enabled:e,activationState:{...t?.activationState||{},userConfigured:!0,autoEnabledBy:void 0}}),uw={expectedInputs:[{type:"text",languages:["en"]}],expectedOutputs:[{type:"text",languages:["en"]}]},cw=()=>globalThis.LanguageModel,Rh=async t=>{let e=cw();if(!e)return{availability:"api-missing"};try{return{availability:await e.availability({...uw,...t})}}catch(n){return{availability:"unavailable",error:n instanceof Error?n.message:String(n)}}},dw=async(t={})=>{let e=cw();if(!e)throw new Error("Chrome built-in AI is not available in this browser");return await e.create({...uw,...t})},uz=async t=>{let e=await Rh();return e.availability==="api-missing"||e.availability==="unavailable"?e:((await dw({monitor:t?r=>{r.addEventListener("downloadprogress",t)}:void 0})).destroy?.(),await Rh())},oL=class extends Bu{getProvider(){return{id:Gu,name:"Chrome Built-in AI",description:"Local Gemini Nano model managed by Chrome. No API key required.",corsRestricted:!1,requiresApiKey:!1,defaultBaseURL:"",supportsDynamicModels:!1,connectionSchema:{required:[],optional:[],fieldTypes:{}}}}getModels(){return[{id:vh,name:"Gemini Nano (managed by Chrome)",description:"Browser-managed local model exposed through Chrome Prompt API",providerId:Gu,capabilities:{supportsTools:!1,supportsReasoning:!1},parameterDefinitions:[],defaultParameterValues:{}}]}async doSendMessage(t,e){let{initialPrompts:n,prompt:r}=this.buildPrompt(t),i=await this.createReadySession(n);try{return{content:await i.prompt(r),metadata:{model:vh}}}finally{i.destroy?.()}}async doSendMessageStream(t,e,n){n.signal?.throwIfAborted();let{initialPrompts:r,prompt:i}=this.buildPrompt(t),s=await this.createReadySession(r),o="";try{n.signal?.throwIfAborted();let l=await(n.signal?s.promptStreaming(i,{signal:n.signal}):s.promptStreaming(i));for await(let d of l)n.signal?.throwIfAborted(),o+=d,n.onToken(d);await n.onComplete({content:o,metadata:{model:vh}})}finally{s.destroy?.()}}getParameterDefinitions(t){return[]}getDefaultParameterValues(t){return{}}async createReadySession(t){let e=await Rh();if(e.availability==="downloadable")throw new Ie("Chrome built-in AI model is not downloaded. Open the model manager and click download to prepare it.");if(e.availability==="downloading")throw new Ie("Chrome built-in AI model is still downloading. Please wait for the download to finish.");if(e.availability!=="available")throw new Ie(e.error||"Chrome built-in AI is not available in this browser.");return await dw(t?.length?{initialPrompts:t}:{})}buildPrompt(t){let e=t.map(s=>({role:s.role,content:s.content.trim()})).filter(s=>s.content),n=this.findPromptMessageIndex(e),r=e.filter((s,o)=>o!==n).map(s=>this.toInitialPrompt(s)),i=e[n];return{initialPrompts:r.length>0?r:void 0,prompt:i?this.toPromptInput(i):t.map(s=>s.content).join(`
89
+
90
+ `)}}findPromptMessageIndex(t){for(let e=t.length-1;e>=0;e-=1)if(t[e].role!=="system")return e;return t.length-1}toInitialPrompt(t){return t.role==="tool"?{role:"user",content:`tool: ${t.content}`}:{role:t.role==="system"||t.role==="assistant"?t.role:"user",content:t.content}}toPromptInput(t){return t.role==="user"||t.role==="system"?t.content:`${t.role}: ${t.content}`}},aL=[{id:"mimo-v2.5-pro",name:"MiMo-V2.5-Pro",description:"Xiaomi MiMo flagship reasoning model via OpenAI-compatible Chat Completions API",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}},{id:"mimo-v2.5",name:"MiMo-V2.5",description:"Xiaomi MiMo multimodal-capable model via OpenAI-compatible Chat Completions API",capabilities:{supportsTools:!0,supportsReasoning:!0,maxContextLength:1e6}}],lL=class extends et{getProvider(){return{id:"xiaomi-mimo-token-plan",name:"Xiaomi MiMo Token Plan",description:"Xiaomi MiMo Token Plan models via OpenAI-compatible API",requiresApiKey:!0,defaultBaseURL:"https://token-plan-cn.xiaomimimo.com/v1",supportsDynamicModels:!0,apiKeyUrl:"https://platform.xiaomimimo.com",connectionSchema:{required:["apiKey"],optional:["baseURL"],fieldTypes:{apiKey:"string",baseURL:"string"}}}}getModels(){return aL.map(t=>{let e=this.buildDefaultModel(t.id);return{...e,name:t.name,description:t.description,capabilities:{...e.capabilities,...t.capabilities??{}}}})}getRequestStyle(){return"chat_completions"}},uL=class extends EU{createUnknownProviderError(t){return new Ie(`Unknown ${this.getProviderTypeDescription()}: ${t}`)}createDynamicModelUnsupportedError(t){return new Ie(`${t.name} does not support dynamic model fetching`)}initializeAdapters(){let t=new et,e=new bU,n=new UU,r=new FU,i=new qU,s=new NU,o=new DU,l=new $U,d=new HU,c=new WU,f=new YU,p=new jU,h=new tL,m=new rL,g=new oL,_=new lL;this.adapters.set("openai",t),this.adapters.set("openai-compatible",e),this.adapters.set("deepseek",n),this.adapters.set("siliconflow",r),this.adapters.set("zhipu",i),this.adapters.set("anthropic",s),this.adapters.set("gemini",o),this.adapters.set("dashscope",l),this.adapters.set("openrouter",d),this.adapters.set("modelscope",c),this.adapters.set("ollama",f),this.adapters.set("magpie",new XU),this.adapters.set("minimax",p),this.adapters.set("cloudflare",h),this.adapters.set("grok",m),this.adapters.set("chrome-built-in",g),this.adapters.set("xiaomi-mimo-token-plan",_),this.preloadStaticModels()}getProviderFromAdapter(t){return t.getProvider()}getModelsFromAdapter(t){return t.getModels()}async getModelsAsyncFromAdapter(t,e){if(!t.getModelsAsync){let n=t.getProvider();throw new Ie(`Adapter ${n.name} does not implement getModelsAsync method`)}return await t.getModelsAsync(e)}getProviderTypeDescription(){return"text model provider"}},cz=()=>new uL;export{xo as a,EU as b,qu as c,Ue as d,Ie as e,XJ as f,QJ as g,TU as h,ZJ as i,jJ as j,ez as k,tz as l,Sh as m,PU as n,aw as o,bh as p,kU as q,rz as r,lw as s,iz as t,Gu as u,vh as v,iL as w,oz as x,az as y,lz as z,Rh as A,uz as B,uL as C,cz as D};
91
+ /*! Bundled license information:
92
+
93
+ safe-buffer/index.js:
94
+ (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
95
+
96
+ @google/genai/dist/node/index.mjs:
97
+ @google/genai/dist/node/index.mjs:
98
+ @google/genai/dist/node/index.mjs:
99
+ @google/genai/dist/node/index.mjs:
100
+ @google/genai/dist/node/index.mjs:
101
+ (**
102
+ * @license
103
+ * Copyright 2025 Google LLC
104
+ * SPDX-License-Identifier: Apache-2.0
105
+ *)
106
+ */