module.exports=[59891,(e,t,r)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r)if(!this._cachedTimeouts)return!1;else this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=i,r=s)}return t}},49448,(e,t,r)=>{var n=e.r(59891);r.operation=function(e){return new n(r.timeouts(e),{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},r.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i{t.exports=e.r(49448)},53577,(e,t,r)=>{"use strict";let n=e.r(57861),i=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class o extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}let s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let a=n.operation(t);a.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error))return void s(TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof o)a.stop(),s(e.originalError);else{let r;if(e instanceof TypeError&&(r=e.message,!i.includes(r)))a.stop(),s(e);else{let r;r=t.retries-(n-1),e.attemptNumber=n,e.retriesLeft=r;try{await t.onFailedAttempt(e)}catch(e){s(e);return}a.retry(e)||s(a.mainError())}}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=o},33405,(e,t,r)=>{t.exports=e.x("child_process",()=>require("child_process"))},22734,(e,t,r)=>{t.exports=e.x("fs",()=>require("fs"))},48042,(e,t,r)=>{"use strict";var n=Object.prototype.hasOwnProperty,i=Object.prototype.toString,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===i.call(e)},l=function(e){if(!e||"[object Object]"!==i.call(e))return!1;var t,r=n.call(e,"constructor"),o=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!o)return!1;for(t in e);return void 0===t||n.call(e,t)},u=function(e,t){o&&"__proto__"===t.name?o(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},c=function(e,t){if("__proto__"===t){if(!n.call(e,t))return;else if(s)return s(e,t).value}return e[t]};t.exports=function e(){var t,r,n,i,o,s,d=arguments[0],p=1,h=arguments.length,f=!1;for("boolean"==typeof d&&(f=d,d=arguments[1]||{},p=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});p{e.v({name:"gaxios",version:"7.1.3",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2",rimraf:"^5.0.1"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"})},86766,(e,t,r)=>{"use strict";t.exports={pkg:e.r(50768)}},68356,(e,t,r)=>{"use strict";var n=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.GaxiosError=r.GAXIOS_ERROR_SYMBOL=void 0,r.defaultErrorRedactor=function e(t){let r="< - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach((t,n)=>{(/^authentication$/i.test(n)||/^authorization$/i.test(n)||/secret/i.test(n))&&e.set(n,r)})}function i(e,t){if("object"==typeof e&&null!==e&&"string"==typeof e[t]){let n=e[t];(/grant_type=/i.test(n)||/assertion=/i.test(n)||/secret/i.test(n))&&(e[t]=r)}}function o(e){!e||"object"!=typeof e||(e instanceof FormData||e instanceof URLSearchParams||"forEach"in e&&"set"in e?e.forEach((t,n)=>{(["grant_type","assertion"].includes(n)||/secret/.test(n))&&e.set(n,r)}):("grant_type"in e&&(e.grant_type=r),"assertion"in e&&(e.assertion=r),"client_secret"in e&&(e.client_secret=r)))}return t.config&&(n(t.config.headers),i(t.config,"data"),o(t.config.data),i(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",r),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",r)),t.response&&(e({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(i(t.response,"data"),o(t.response.data))),t};let i=n(e.r(48042)),o=n(e.r(86766)).default.pkg;r.GAXIOS_ERROR_SYMBOL=Symbol.for(`${o.name}-gaxios-error`);class s extends Error{config;response;code;status;error;[r.GAXIOS_ERROR_SYMBOL]=o.version;static[Symbol.hasInstance](e){return!!e&&"object"==typeof e&&r.GAXIOS_ERROR_SYMBOL in e&&e[r.GAXIOS_ERROR_SYMBOL]===o.version||Function.prototype[Symbol.hasInstance].call(s,e)}constructor(e,t,r,n){if(super(e,{cause:n}),this.config=t,this.response=r,this.error=n instanceof Error?n:void 0,this.config=(0,i.default)(!0,{},t),this.response&&(this.response.config=(0,i.default)(!0,{},this.response.config)),this.response){try{this.response.data=function(e,t){switch(e){case"stream":default:return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text())}}(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}n instanceof DOMException?this.code=n.name:n&&"object"==typeof n&&"code"in n&&("string"==typeof n.code||"number"==typeof n.code)&&(this.code=n.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let r=t;if("string"==typeof e.data&&(r=e.data),e.data&&"object"==typeof e.data&&"error"in e.data&&e.data.error&&!e.ok){if("string"==typeof e.data.error)return{message:e.data.error,code:e.status,status:e.statusText};if("object"==typeof e.data.error){r="message"in e.data.error&&"string"==typeof e.data.error.message?e.data.error.message:r;let t="status"in e.data.error&&"string"==typeof e.data.error.status?e.data.error.status:e.statusText,n="code"in e.data.error&&"number"==typeof e.data.error.code?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)"object"==typeof t&&"message"in t&&"string"==typeof t.message&&i.push(t.message);return Object.assign({message:i.join("\n")||r,code:n,status:t},e.data.error)}return Object.assign({message:r,code:n,status:t},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}}r.GaxiosError=s},16874,(e,t,r)=>{"use strict";async function n(e){var t;let r=o(e);if(!e||!e.config||!r&&!e.config.retry)return{shouldRetry:!1};(r=r||{}).currentRetryAttempt=r.currentRetryAttempt||0,r.retry=void 0===r.retry||null===r.retry?3:r.retry,r.httpMethodsToRetry=r.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],r.noResponseRetries=void 0===r.noResponseRetries||null===r.noResponseRetries?2:r.noResponseRetries,r.retryDelayMultiplier=r.retryDelayMultiplier?r.retryDelayMultiplier:2,r.timeOfFirstRequest=r.timeOfFirstRequest?r.timeOfFirstRequest:Date.now(),r.totalTimeout=r.totalTimeout?r.totalTimeout:Number.MAX_SAFE_INTEGER,r.maxRetryDelay=r.maxRetryDelay?r.maxRetryDelay:Number.MAX_SAFE_INTEGER,r.statusCodesToRetry=r.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=r;let n=r.shouldRetry||i;if(!await n(e))return{shouldRetry:!1,config:e.config};let s=Math.min(((t=r).currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,t.totalTimeout-(Date.now()-t.timeOfFirstRequest),t.maxRetryDelay);e.config.retryConfig.currentRetryAttempt+=1;let a=r.retryBackoff?r.retryBackoff(e,s):new Promise(e=>{setTimeout(e,s)});return r.onRetryAttempt&&await r.onRetryAttempt(e),await a,{shouldRetry:!0,config:e.config}}function i(e){let t=o(e);if(e.config.signal?.aborted&&"TimeoutError"!==e.code||"AbortError"===e.code||!t||0===t.retry||!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries||!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let r=!1;for(let[n,i]of t.statusCodesToRetry){let t=e.response.status;if(t>=n&&t<=i){r=!0;break}}if(!r)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function o(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}Object.defineProperty(r,"__esModule",{value:!0}),r.getRetryConfig=n},88947,(e,t,r)=>{t.exports=e.x("stream",()=>require("stream"))},43308,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.GaxiosInterceptorManager=void 0;class n extends Set{}r.GaxiosInterceptorManager=n},84141,(e,t,r)=>{"use strict";var n,i=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.Gaxios=void 0;let o=i(e.r(48042)),s=e.r(24836),a=e.r(68356),l=e.r(16874),u=e.r(88947),c=e.r(43308),d=async()=>globalThis.crypto?.randomUUID()||(await e.A(85685)).randomUUID();class p{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new c.GaxiosInterceptorManager,response:new c.GaxiosInterceptorManager}}fetch(...e){let t,r=e[0],i=e[1],o=new Headers;return("string"==typeof r?t=new URL(r):r instanceof URL?t=r:r&&r.url&&(t=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&n.mergeHeaders(o,r.headers),i&&n.mergeHeaders(o,new Headers(i.headers)),"object"!=typeof r||r instanceof URL)?this.request({...i,headers:o,url:t}):this.request({...i,...r,headers:o,url:t})}async request(e={}){let t=await this.#e(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await n.#n(),r={...e};delete r.data;let i=await t(e.url,r),o=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}}),Object.assign(i,{config:e,data:o})}async _request(e){try{let t;if(t=e.adapter?await e.adapter(e,this._defaultAdapter.bind(this)):await this._defaultAdapter(e),!e.validateStatus(t.status)){if("stream"===e.responseType){let e=[];for await(let r of t.data)e.push(r);t.data=e.toString()}let r=a.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new a.GaxiosError(r?.message,e,t,r)}return t}catch(i){let t;t=i instanceof a.GaxiosError?i:i instanceof Error?new a.GaxiosError(i.message,e,void 0,i):new a.GaxiosError("Unexpected Gaxios Error",e,void 0,i);let{shouldRetry:r,config:n}=await (0,l.getRetryConfig)(t);if(r&&n)return t.config.retryConfig.currentRetryAttempt=n.retryConfig.currentRetryAttempt,e.retryConfig=t.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(t),t}}async getResponseData(e,t){if(204===t.status)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(null===t)return e.text();if((t=t.toLowerCase()).includes("application/json")){let t=await e.text();try{t=JSON.parse(t)}catch{}return t}return t.match(/^text\//)?e.text():e.blob()}async *getMultipartRequest(e,t){let r=`--${t}--`;for(let r of e){let e=r.headers.get("Content-Type")||"application/octet-stream",n=`--${t}\r Content-Type: ${e}\r \r `;yield n,"string"==typeof r.content?yield r.content:yield*r.content,yield"\r\n"}yield r}static #a;static #l;static async #s(){return this.#a||=(await e.A(4087)).HttpsProxyAgent,this.#a}static async #n(){return this.#l||=(await e.A(62103)).default,this.#l}static mergeHeaders(e,...t){for(let r of(e=e instanceof Headers?e:new Headers(e),t))(r instanceof Headers?r:new Headers(r)).forEach((t,r)=>{"set-cookie"===r?e.append(r,t):e.set(r,t)});return e}}r.Gaxios=p,n=p},65065,(e,t,r)=>{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.instance=r.Gaxios=r.GaxiosError=void 0,r.request=a;let o=e.r(84141);Object.defineProperty(r,"Gaxios",{enumerable:!0,get:function(){return o.Gaxios}});var s=e.r(68356);async function a(e){return r.instance.request(e)}Object.defineProperty(r,"GaxiosError",{enumerable:!0,get:function(){return s.GaxiosError}}),i(e.r(43308),r),r.instance=new o.Gaxios},28788,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.GCE_LINUX_BIOS_PATHS=void 0,r.isGoogleCloudServerless=o,r.isGoogleComputeEngineLinux=s,r.isGoogleComputeEngineMACAddress=a,r.isGoogleComputeEngine=l,r.detectGCPResidency=function(){return o()||l()},e.r(22734);let n=e.r(46786);r.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};let i=/^42:01/;function o(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function s(){if("linux"!==(0,n.platform)())return!1}function a(){for(let e of Object.values((0,n.networkInterfaces)()))if(e){for(let{mac:t}of e)if(i.test(t))return!0}return!1}function l(){return s()||a()}},96487,(e,t,r)=>{!function(r){"use strict";var n,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,o=Math.ceil,s=Math.floor,a="[BigNumber Error] ",l=a+"Number primitive has more than 15 significant digits: ",u=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13];function c(e){var t=0|e;return e>0||e===t?t:t-1}function d(e){for(var t,r,n=1,i=e.length,o=e[0]+"";nu^r?1:-1;for(s=0,a=(l=i.length)<(u=o.length)?l:u;so[s]^r?1:-1;return l==u?0:l>u^r?1:-1}function h(e,t,r,n){if(er||e!==s(e))throw Error(a+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function f(e){var t=e.c.length-1;return c(e.e/14)==t&&e.c[t]%2!=0}function m(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function g(e,t,r){var n,i;if(t<0){for(i=r+".";++t;i+=r);e=i+e}else if(n=e.length,++t>n){for(i=r,t-=n;--t;i+=r);e+=i}else tk?f.c=f.e=null:e.e=10;u/=10,a++);a>k?f.c=f.e=null:(f.e=a,f.c=[e]);return}p=String(e)}else{if(!i.test(p=String(e)))return S(f,p,c);f.s=45==p.charCodeAt(0)?(p=p.slice(1),-1):1}(a=p.indexOf("."))>-1&&(p=p.replace(".","")),(u=p.search(/e/i))>0?(a<0&&(a=u),a+=+p.slice(u+1),p=p.substring(0,u)):a<0&&(a=p.length)}else{if(h(t,2,M.length,"Base"),10==t&&L)return H(f=new j(e),O+f.e+1,I);if(p=String(e),c="number"==typeof e){if(0*e!=0)return S(f,p,c,t);if(f.s=1/e<0?(p=p.slice(1),-1):1,j.DEBUG&&p.replace(/^0\.0*|\./,"").length>15)throw Error(l+e)}else f.s=45===p.charCodeAt(0)?(p=p.slice(1),-1):1;for(r=M.slice(0,t),a=u=0,d=p.length;ur.indexOf(n=p.charAt(u))){if("."==n){if(u>a){a=d;continue}}else if(!o&&(p==p.toUpperCase()&&(p=p.toLowerCase())||p==p.toLowerCase()&&(p=p.toUpperCase()))){o=!0,u=-1,a=0;continue}return S(f,String(e),c,t)}c=!1,(a=(p=A(p,t,10,f.s)).indexOf("."))>-1?p=p.replace(".",""):a=p.length}for(u=0;48===p.charCodeAt(u);u++);for(d=p.length;48===p.charCodeAt(--d););if(p=p.slice(u,++d)){if(d-=u,c&&j.DEBUG&&d>15&&(e>0x1fffffffffffff||e!==s(e)))throw Error(l+f.s*e);if((a=a-u-1)>k)f.c=f.e=null;else if(a=R)?m(l,s):g(l,s,"0");else if(o=(e=H(new j(e),t,r)).e,a=(l=d(e.c)).length,1==n||2==n&&(t<=o||o<=w)){for(;as),l=g(l,o,"0"),o+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=o-a)>0)for(o+1==a&&(l+=".");t--;l+="0");return e.s<0&&i?"-"+l:l}function F(e,t){for(var r,n,i=1,o=new j(e[0]);i=10;i/=10,n++);return(r=n+14*r-1)>k?e.c=e.e=null:r=10;c/=10,i++);if((a=t-i)<0)a+=14,l=t,h=s((d=f[p=0])/u[i-l-1]%10);else if((p=o((a+1)/14))>=f.length)if(n){for(;f.length<=p;f.push(0));d=h=0,i=1,a%=14,l=a-14+1}else break e;else{for(i=1,d=c=f[p];c>=10;c/=10,i++);a%=14,h=(l=a-14+i)<0?0:s(d/u[i-l-1]%10)}if(n=n||t<0||null!=f[p+1]||(l<0?d:d%u[i-l-1]),n=r<4?(h||n)&&(0==r||r==(e.s<0?3:2)):h>5||5==h&&(4==r||n||6==r&&(a>0?l>0?d/u[i-l]:0:f[p-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=u[(14-t%14)%14],e.e=-t||0):f[0]=e.e=0,e;if(0==a?(f.length=p,c=1,p--):(f.length=p+1,c=u[14-a],f[p]=l>0?s(d/u[i-l]%u[l])*c:0),n)for(;;)if(0==p){for(a=1,l=f[0];l>=10;l/=10,a++);for(l=f[0]+=c,c=1;l>=10;l/=10,c++);a!=c&&(e.e++,1e14==f[0]&&(f[0]=1));break}else{if(f[p]+=c,1e14!=f[p])break;f[p--]=0,c=1}for(a=f.length;0===f[--a];f.pop());}e.e>k?e.c=e.e=null:e.e=R?m(t,r):g(t,r,"0"),e.s<0?"-"+t:t)}return j.clone=e,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(e){var t,r;if(null!=e)if("object"==typeof e){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(h(r=e[t],0,1e9,t),O=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(h(r=e[t],0,8,t),I=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(h(r[0],-1e9,0,t),h(r[1],0,1e9,t),w=r[0],R=r[1]):(h(r,-1e9,1e9,t),w=-(R=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)h(r[0],-1e9,-1,t),h(r[1],1,1e9,t),N=r[0],k=r[1];else if(h(r,-1e9,1e9,t),r)N=-(k=r<0?-r:r);else throw Error(a+t+" cannot be zero: "+r);if(e.hasOwnProperty(t="CRYPTO"))if(!!(r=e[t])===r)if(r)if("u">typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))P=r;else throw P=!r,Error(a+"crypto unavailable");else P=r;else throw Error(a+t+" not true or false: "+r);if(e.hasOwnProperty(t="MODULO_MODE")&&(h(r=e[t],0,9,t),x=r),e.hasOwnProperty(t="POW_PRECISION")&&(h(r=e[t],0,1e9,t),U=r),e.hasOwnProperty(t="FORMAT"))if("object"==typeof(r=e[t]))D=r;else throw Error(a+t+" not an object: "+r);if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(a+t+" invalid: "+r);L="0123456789"==r.slice(0,10),M=r}}else throw Error(a+"Object expected: "+e);return{DECIMAL_PLACES:O,ROUNDING_MODE:I,EXPONENTIAL_AT:[w,R],RANGE:[N,k],CRYPTO:P,MODULO_MODE:x,POW_PRECISION:U,FORMAT:D,ALPHABET:M}},j.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!j.DEBUG)return!0;var t,r,n=e.c,i=e.e,o=e.s;e:if("[object Array]"==({}).toString.call(n)){if((1===o||-1===o)&&i>=-1e9&&i<=1e9&&i===s(i)){if(0===n[0]){if(0===i&&1===n.length)return!0;break e}if((t=(i+1)%14)<1&&(t+=14),String(n[0]).length==t){for(t=0;t=1e14||r!==s(r))break e;if(0!==r)return!0}}}else if(null===n&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(a+"Invalid BigNumber: "+e)},j.maximum=j.max=function(){return F(arguments,-1)},j.minimum=j.min=function(){return F(arguments,1)},r=0x20000000000000*Math.random()&2097151?function(){return s(0x20000000000000*Math.random())}:function(){return(0x40000000*Math.random()|0)*8388608+(8388608*Math.random()|0)},j.random=function(e){var t,n,i,l,c,d=0,p=[],f=new j(C);if(null==e?e=O:h(e,0,1e9),l=o(e/14),P)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(l*=2));d>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[d]=n[0],t[d+1]=n[1]):(p.push(c%1e14),d+=2);d=l/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(l*=7);d=9e15?crypto.randomBytes(7).copy(t,d):(p.push(c%1e14),d+=7);d=l/7}else throw P=!1,Error(a+"crypto unavailable");if(!P)for(;d=10;c/=10,d++);d<14&&(i-=14-d)}return f.e=i,f.c=p,f},j.sum=function(){for(var e=1,t=arguments,r=new j(t[0]);er-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/r|0,s[i]%=r)}return s.reverse()}return function(r,n,i,o,s){var a,l,u,c,p,h,f,m,y=r.indexOf("."),_=O,E=I;for(y>=0&&(c=U,U=0,r=r.replace(".",""),h=(m=new j(n)).pow(r.length-y),U=c,m.c=t(g(d(h.c),h.e,"0"),10,i,e),m.e=m.c.length),u=c=(f=t(r,n,i,s?(a=M,e):(a=e,M))).length;0==f[--c];f.pop());if(!f[0])return a.charAt(0);if(y<0?--u:(h.c=f,h.e=u,h.s=o,f=(h=T(h,m,_,E,i)).c,p=h.r,u=h.e),y=f[l=u+_+1],c=i/2,p=p||l<0||null!=f[l+1],p=E<4?(null!=y||p)&&(0==E||E==(h.s<0?3:2)):y>c||y==c&&(4==E||p||6==E&&1&f[l-1]||E==(h.s<0?8:7)),l<1||!f[0])r=p?g(a.charAt(1),-_,a.charAt(0)):a.charAt(0);else{if(f.length=l,p)for(--i;++f[--l]>i;)f[l]=0,l||(++u,f=[1].concat(f));for(c=f.length;!f[--c];);for(y=0,r="";y<=c;r+=a.charAt(f[y++]));r=g(r,u,a.charAt(0))}return r}}(),T=function(){function e(e,t,r){var n,i,o,s,a=0,l=e.length,u=t%1e7,c=t/1e7|0;for(e=e.slice();l--;)n=c*(o=e[l]%1e7)+(s=e[l]/1e7|0)*u,a=((i=u*o+n%1e7*1e7+a)/r|0)+(n/1e7|0)+c*s,e[l]=i%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var i,o;if(r!=n)o=r>n?1:-1;else for(i=o=0;it[i]?1:-1;break}return o}function r(e,t,r,n){for(var i=0;r--;)e[r]-=i,i=+(e[r]1;e.splice(0,1));}return function(n,i,o,a,l){var u,d,p,h,f,m,g,y,_,E,v,T,A,S,b,C,O,I=n.s==i.s?1:-1,w=n.c,R=i.c;if(!w||!w[0]||!R||!R[0])return new j(!n.s||!i.s||(w?R&&w[0]==R[0]:!R)?NaN:w&&0==w[0]||!R?0*I:I/0);for(_=(y=new j(I)).c=[],I=o+(d=n.e-i.e)+1,l||(l=1e14,d=c(n.e/14)-c(i.e/14),I=I/14|0),p=0;R[p]==(w[p]||0);p++);if(R[p]>(w[p]||0)&&d--,I<0)_.push(1),h=!0;else{for(S=w.length,C=R.length,p=0,I+=2,(f=s(l/(R[0]+1)))>1&&(R=e(R,f,l),w=e(w,f,l),C=R.length,S=w.length),A=C,v=(E=w.slice(0,C)).length;v=l/2&&b++;do{if(f=0,(u=t(R,E,C,v))<0){if(T=E[0],C!=v&&(T=T*l+(E[1]||0)),(f=s(T/b))>1)for(f>=l&&(f=l-1),g=(m=e(R,f,l)).length,v=E.length;1==t(m,E,g,v);)f--,r(m,Ct(R,E,C,v);)f++,r(E,C=10;I/=10,p++);H(y,o+(y.e=p+14*d-1)+1,a,h)}else y.e=d,y.r=+h;return y}}(),n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,_=/^\.([^.]+)$/,E=/^-?(Infinity|NaN)$/,v=/^\s*\+(?=[\w.])|^\s+|\s+$/g,S=function(e,t,r,i){var o,s=r?t:t.replace(v,"");if(E.test(s))e.s=isNaN(s)?null:s<0?-1:1;else{if(!r&&(s=s.replace(n,function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,i&&i!=o?e:t}),i&&(o=i,s=s.replace(y,"$1").replace(_,"0.$1")),t!=s))return new j(s,o);if(j.DEBUG)throw Error(a+"Not a"+(i?" base "+i:"")+" number: "+t);e.s=null}e.c=e.e=null},b.absoluteValue=b.abs=function(){var e=new j(this);return e.s<0&&(e.s=1),e},b.comparedTo=function(e,t){return p(this,new j(e,t))},b.decimalPlaces=b.dp=function(e,t){var r,n,i;if(null!=e)return h(e,0,1e9),null==t?t=I:h(t,0,8),H(new j(this),e+this.e+1,t);if(!(r=this.c))return null;if(n=((i=r.length-1)-c(this.e/14))*14,i=r[i])for(;i%10==0;i/=10,n--);return n<0&&(n=0),n},b.dividedBy=b.div=function(e,t){return T(this,new j(e,t),O,I)},b.dividedToIntegerBy=b.idiv=function(e,t){return T(this,new j(e,t),0,1)},b.exponentiatedBy=b.pow=function(e,t){var r,n,i,l,u,c,d,p,h,m=this;if((e=new j(e)).c&&!e.isInteger())throw Error(a+"Exponent not an integer: "+B(e));if(null!=t&&(t=new j(t)),c=e.e>14,!m.c||!m.c[0]||1==m.c[0]&&!m.e&&1==m.c.length||!e.c||!e.c[0])return h=new j(Math.pow(+B(m),c?e.s*(2-f(e)):+B(e))),t?h.mod(t):h;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new j(NaN);(n=!d&&m.isInteger()&&t.isInteger())&&(m=m.mod(t))}else{if(e.e>9&&(m.e>0||m.e<-1||(0==m.e?m.c[0]>1||c&&m.c[1]>=24e7:m.c[0]<8e13||c&&m.c[0]<=9999975e7)))return l=m.s<0&&f(e)?-0:0,m.e>-1&&(l=1/l),new j(d?1/l:l);U&&(l=o(U/14+2))}for(c?(r=new j(.5),d&&(e.s=1),p=f(e)):p=(i=Math.abs(+B(e)))%2,h=new j(C);;){if(p){if(!(h=h.times(m)).c)break;l?h.c.length>l&&(h.c.length=l):n&&(h=h.mod(t))}if(i){if(0===(i=s(i/2)))break;p=i%2}else if(H(e=e.times(r),e.e+1,1),e.e>14)p=f(e);else{if(0==(i=+B(e)))break;p=i%2}m=m.times(m),l?m.c&&m.c.length>l&&(m.c.length=l):n&&(m=m.mod(t))}return n?h:(d&&(h=C.div(h)),t?h.mod(t):l?H(h,U,I,u):h)},b.integerValue=function(e){var t=new j(this);return null==e?e=I:h(e,0,8),H(t,t.e+1,e)},b.isEqualTo=b.eq=function(e,t){return 0===p(this,new j(e,t))},b.isFinite=function(){return!!this.c},b.isGreaterThan=b.gt=function(e,t){return p(this,new j(e,t))>0},b.isGreaterThanOrEqualTo=b.gte=function(e,t){return 1===(t=p(this,new j(e,t)))||0===t},b.isInteger=function(){return!!this.c&&c(this.e/14)>this.c.length-2},b.isLessThan=b.lt=function(e,t){return 0>p(this,new j(e,t))},b.isLessThanOrEqualTo=b.lte=function(e,t){return -1===(t=p(this,new j(e,t)))||0===t},b.isNaN=function(){return!this.s},b.isNegative=function(){return this.s<0},b.isPositive=function(){return this.s>0},b.isZero=function(){return!!this.c&&0==this.c[0]},b.minus=function(e,t){var r,n,i,o,s=this.s;if(t=(e=new j(e,t)).s,!s||!t)return new j(NaN);if(s!=t)return e.s=-t,this.plus(e);var a=this.e/14,l=e.e/14,u=this.c,d=e.c;if(!a||!l){if(!u||!d)return u?(e.s=-t,e):new j(d?this:NaN);if(!u[0]||!d[0])return d[0]?(e.s=-t,e):new j(u[0]?this:3==I?-0:0)}if(a=c(a),l=c(l),u=u.slice(),s=a-l){for((o=s<0)?(s=-s,i=u):(l=a,i=d),i.reverse(),t=s;t--;i.push(0));i.reverse()}else for(n=(o=(s=u.length)<(t=d.length))?s:t,s=t=0;t0)for(;t--;u[r++]=0);for(t=1e14-1;n>s;){if(u[--n]=0;){for(r=0,h=y[i]%1e7,f=y[i]/1e7|0,o=i+(s=l);o>i;)a=f*(u=g[--s]%1e7)+(d=g[s]/1e7|0)*h,r=((u=h*u+a%1e7*1e7+m[o]+r)/1e14|0)+(a/1e7|0)+f*d,m[o--]=u%1e14;m[o]=r}return r?++n:m.splice(0,1),q(e,m,n)},b.negated=function(){var e=new j(this);return e.s=-e.s||null,e},b.plus=function(e,t){var r,n=this.s;if(t=(e=new j(e,t)).s,!n||!t)return new j(NaN);if(n!=t)return e.s=-t,this.minus(e);var i=this.e/14,o=e.e/14,s=this.c,a=e.c;if(!i||!o){if(!s||!a)return new j(n/0);if(!s[0]||!a[0])return a[0]?e:new j(s[0]?this:0*n)}if(i=c(i),o=c(o),s=s.slice(),n=i-o){for(n>0?(o=i,r=a):(n=-n,r=s),r.reverse();n--;r.push(0));r.reverse()}for((n=s.length)-(t=a.length)<0&&(r=a,a=s,s=r,t=n),n=0;t;)n=(s[--t]=s[t]+a[t]+n)/1e14|0,s[t]=1e14===s[t]?0:s[t]%1e14;return n&&(s=[n].concat(s),++o),q(e,s,o)},b.precision=b.sd=function(e,t){var r,n,i;if(null!=e&&!!e!==e)return h(e,1,1e9),null==t?t=I:h(t,0,8),H(new j(this),e,t);if(!(r=this.c))return null;if(n=14*(i=r.length-1)+1,i=r[i]){for(;i%10==0;i/=10,n--);for(i=r[0];i>=10;i/=10,n++);}return e&&this.e+1>n&&(n=this.e+1),n},b.shiftedBy=function(e){return h(e,-0x1fffffffffffff,0x1fffffffffffff),this.times("1e"+e)},b.squareRoot=b.sqrt=function(){var e,t,r,n,i,o=this.c,s=this.s,a=this.e,l=O+4,u=new j("0.5");if(1!==s||!o||!o[0])return new j(!s||s<0&&(!o||o[0])?NaN:o?this:1/0);if(0==(s=Math.sqrt(+B(this)))||s==1/0?(((t=d(o)).length+a)%2==0&&(t+="0"),s=Math.sqrt(+t),a=c((a+1)/2)-(a<0||a%2),r=new j(t=s==1/0?"5e"+a:(t=s.toExponential()).slice(0,t.indexOf("e")+1)+a)):r=new j(s+""),r.c[0]){for((s=(a=r.e)+l)<3&&(s=0);;)if(i=r,r=u.times(i.plus(T(this,i,l,1))),d(i.c).slice(0,s)===(t=d(r.c)).slice(0,s)){if(r.e0&&f>0){for(i=f%s||s,c=h.substr(0,i);i0&&(c+=u+h.slice(i)),p&&(c="-"+c)}n=d?c+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?d.replace(RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):d):c}return(r.prefix||"")+n+(r.suffix||"")},b.toFraction=function(e){var t,r,n,i,o,s,l,c,p,h,f,m,g=this.c;if(null!=e&&(!(l=new j(e)).isInteger()&&(l.c||1!==l.s)||l.lt(C)))throw Error(a+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+B(l));if(!g)return new j(this);for(t=new j(C),p=r=new j(C),n=c=new j(C),m=d(g),o=t.e=m.length-this.e-1,t.c[0]=u[(s=o%14)<0?14+s:s],e=!e||l.comparedTo(t)>0?o>0?t:p:l,s=k,k=1/0,l=new j(m),c.c[0]=0;h=T(l,t,0,1),1!=(i=r.plus(h.times(n))).comparedTo(e);)r=n,n=i,p=c.plus(h.times(i=p)),c=i,t=l.minus(h.times(i=t)),l=i;return i=T(e.minus(r),n,0,1),c=c.plus(i.times(p)),r=r.plus(i.times(n)),c.s=p.s=this.s,o*=2,f=1>T(p,n,o,I).minus(this).abs().comparedTo(T(c,r,o,I).minus(this).abs())?[p,n]:[c,r],k=s,f},b.toNumber=function(){return+B(this)},b.toPrecision=function(e,t){return null!=e&&h(e,1,1e9),G(this,e,t,2)},b.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=w||i>=R?m(d(r.c),i):g(d(r.c),i,"0"):10===e&&L?t=g(d((r=H(new j(r),O+i+1,I)).c),r.e,"0"):(h(e,2,M.length,"Base"),t=A(g(d(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},b.valueOf=b.toJSON=function(){return B(this)},b._isBigNumber=!0,null!=t&&j.set(t),j}()).default=n.BigNumber=n,"function"==typeof define&&define.amd)e.r,void 0!==n&&e.v(n);else t.exports?t.exports=n:(r||(r="u">typeof self&&self?self:window),r.BigNumber=n)}(e.e)},88158,(e,t,r)=>{var n=e.r(96487),i=t.exports;!function(){"use strict";var e,t,r,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return o.lastIndex=0,o.test(e)?'"'+e.replace(o,function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}"function"!=typeof i.stringify&&(i.stringify=function(i,o,s){var l;if(e="",t="","number"==typeof s)for(l=0;l{var n=null;let i=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,o=/(?: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)/;t.exports=function(t){"use strict";var r={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=t){if(!0===t.strict&&(r.strict=!0),!0===t.storeAsString&&(r.storeAsString=!0),r.alwaysParseAsBig=!0===t.alwaysParseAsBig&&t.alwaysParseAsBig,r.useNativeBigInt=!0===t.useNativeBigInt&&t.useNativeBigInt,void 0!==t.constructorAction)if("error"===t.constructorAction||"ignore"===t.constructorAction||"preserve"===t.constructorAction)r.constructorAction=t.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(void 0!==t.protoAction)if("error"===t.protoAction||"ignore"===t.protoAction||"preserve"===t.protoAction)r.protoAction=t.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var s,a,l,u,c={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},d=function(e){throw{name:"SyntaxError",message:e,at:s,text:l}},p=function(e){return e&&e!==a&&d("Expected '"+e+"' instead of '"+a+"'"),a=l.charAt(s),s+=1,a},h=function(){var t,i="";for("-"===a&&(i="-",p("-"));a>="0"&&a<="9";)i+=a,p();if("."===a)for(i+=".";p()&&a>="0"&&a<="9";)i+=a;if("e"===a||"E"===a)for(i+=a,p(),("-"===a||"+"===a)&&(i+=a,p());a>="0"&&a<="9";)i+=a,p();if(isFinite(t=+i))return(null==n&&(n=e.r(96487)),i.length>15)?r.storeAsString?i:r.useNativeBigInt?BigInt(i):new n(i):r.alwaysParseAsBig?r.useNativeBigInt?BigInt(t):new n(t):t;d("Bad number")},f=function(){var e,t,r,n="";if('"'===a)for(var i=s;p();){if('"'===a)return s-1>i&&(n+=l.substring(i,s-1)),p(),n;if("\\"===a){if(s-1>i&&(n+=l.substring(i,s-1)),p(),"u"===a){for(t=0,r=0;t<4&&isFinite(e=parseInt(p(),16));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else if("string"==typeof c[a])n+=c[a];else break;i=s}}d("Bad string")},m=function(){for(;a&&a<=" ";)p()},g=function(){switch(a){case"t":return p("t"),p("r"),p("u"),p("e"),!0;case"f":return p("f"),p("a"),p("l"),p("s"),p("e"),!1;case"n":return p("n"),p("u"),p("l"),p("l"),null}d("Unexpected '"+a+"'")},y=function(){var e=[];if("["===a){if(p("["),m(),"]"===a)return p("]"),e;for(;a;){if(e.push(u()),m(),"]"===a)return p("]"),e;p(","),m()}}d("Bad array")},_=function(){var e,t=Object.create(null);if("{"===a){if(p("{"),m(),"}"===a)return p("}"),t;for(;a;){if(e=f(),m(),p(":"),!0===r.strict&&Object.hasOwnProperty.call(t,e)&&d('Duplicate key "'+e+'"'),!0===i.test(e)?"error"===r.protoAction?d("Object contains forbidden prototype property"):"ignore"===r.protoAction?u():t[e]=u():!0===o.test(e)?"error"===r.constructorAction?d("Object contains forbidden constructor property"):"ignore"===r.constructorAction?u():t[e]=u():t[e]=u(),m(),"}"===a)return p("}"),t;p(","),m()}}d("Bad object")};return u=function(){switch(m(),a){case"{":return _();case"[":return y();case'"':return f();case"-":return h();default:return a>="0"&&a<="9"?h():g()}},function(e,t){var r;return l=e+"",s=0,a=" ",r=u(),m(),a&&d("Syntax error"),"function"==typeof t?function e(r,n){var i,o=r[n];return o&&"object"==typeof o&&Object.keys(o).forEach(function(t){void 0!==(i=e(o,t))?o[t]=i:delete o[t]}),t.call(r,n,o)}({"":r},""):r}}},55476,(e,t,r)=>{var n=e.r(88158).stringify,i=e.r(62602);t.exports=function(e){return{parse:i(e),stringify:n}},t.exports.parse=i(),t.exports.stringify=n},27699,(e,t,r)=>{t.exports=e.x("events",()=>require("events"))},5365,(e,t,r)=>{t.exports=e.x("process",()=>require("process"))},36844,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Colours=void 0;class n{static isEnabled(e){return e&&e.isTTY&&("function"!=typeof e.getColorDepth||e.getColorDepth()>2)}static refresh(){n.enabled=n.isEnabled(null==process?void 0:process.stderr),this.enabled?(n.reset="\x1b[0m",n.bright="\x1b[1m",n.dim="\x1b[2m",n.red="\x1b[31m",n.green="\x1b[32m",n.yellow="\x1b[33m",n.blue="\x1b[34m",n.magenta="\x1b[35m",n.cyan="\x1b[36m",n.white="\x1b[37m",n.grey="\x1b[90m"):(n.reset="",n.bright="",n.dim="",n.red="",n.green="",n.yellow="",n.blue="",n.magenta="",n.cyan="",n.white="",n.grey="")}}r.Colours=n,n.enabled=!1,n.reset="",n.bright="",n.dim="",n.red="",n.green="",n.yellow="",n.blue="",n.magenta="",n.cyan="",n.white="",n.grey="",n.refresh()},75978,(e,t,r)=>{"use strict";let n;var i,o,s,a=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),l=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=e.e&&e.e.__importStar||(i=function(e){return(i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),n=0;nthis.on(e,t)}),this.func.debug=(...e)=>this.invokeSeverity(s.DEBUG,...e),this.func.info=(...e)=>this.invokeSeverity(s.INFO,...e),this.func.warn=(...e)=>this.invokeSeverity(s.WARNING,...e),this.func.error=(...e)=>this.invokeSeverity(s.ERROR,...e),this.func.sublog=e=>T(e,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(e){}try{this.emit("log",e,t)}catch(e){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}r.AdhocDebugLogger=f,r.placeholder=new f("",()=>{}).func;class m{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=null!=(e=d.env[r.env.nodeEnables])?e:"*";"all"===t&&(t="*"),this.filters=t.split(",")}log(e,t,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let n=this.cached.get(e);n||(n=this.makeLogger(e),this.cached.set(e,n)),n(t,...r)}catch(e){console.error(e)}}}r.DebugLogBackendBase=m;class g extends m{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...r)=>{var n;let i,o=`${h.Colours.green}${e}${h.Colours.reset}`,a=`${h.Colours.yellow}${d.pid}${h.Colours.reset}`;switch(t.severity){case s.ERROR:i=`${h.Colours.red}${t.severity}${h.Colours.reset}`;break;case s.INFO:i=`${h.Colours.magenta}${t.severity}${h.Colours.reset}`;break;case s.WARNING:i=`${h.Colours.yellow}${t.severity}${h.Colours.reset}`;break;default:i=null!=(n=t.severity)?n:s.DEFAULT}let l=p.formatWithOptions({colors:h.Colours.enabled},...r),u=Object.assign({},t);delete u.severity;let c=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=c?`${h.Colours.grey}${c}${h.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,o,i,l,c?` ${f}`:"")}:()=>{}}setFilters(){let e=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=RegExp(`^${e}$`,"i")}}function y(){return new g}class _ extends m{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(e,...r)=>{t(r[0],...r.slice(1))}}setFilters(){var e;let t=null!=(e=d.env.NODE_DEBUG)?e:"";d.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}}class E extends m{constructor(e){super(),this.upstream=null!=e?e:void 0}makeLogger(e){var t;let r=null==(t=this.upstream)?void 0:t.makeLogger(e);return(e,...t)=>{var n;let i=JSON.stringify(Object.assign({severity:null!=(n=e.severity)?n:s.INFO,message:p.format(...t)},e));r?r(e,i):console.log("%s",i)}}setFilters(){var e;null==(e=this.upstream)||e.setFilters()}}r.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};let v=new Map;function T(e,t){let i;if(!n&&!d.env[r.env.nodeEnables]||!e)return r.placeholder;t&&(e=`${t.instance.namespace}:${e}`);let o=v.get(e);if(o)return o.func;if(null===n)return r.placeholder;void 0===n&&(n=y());let s=new f(e,(t,...r)=>{if(i!==n){if(null===n)return;void 0===n&&(n=y()),i=n}null==n||n.log(e,t,...r)});return v.set(e,s),s.func}},93199,(e,t,r)=>{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e.r(75978),r)},37876,(e,t,r)=>{"use strict";let n;var i,o=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=e.e&&e.e.__importStar||(i=function(e){return(i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),n=0;no.set(t,e)),s=e.metadataKey,a=e.params||a,n=e.noResponseRetries||n,i=e.fastFail||i):s=e,"string"==typeof t)?s+=`/${t}`:(Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${e}' is not a valid configuration option.`)}}),t.property&&(s+=`/${t.property}`),new Headers(t.headers).forEach((e,t)=>o.set(t,e)),a=t.params||a);let l=i?g:u.request,d={url:`${f()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:T()};h.info("instance request %j",d);let p=await l(d);h.info("instance metadata is %s",p.data);let y=p.headers.get(r.HEADER_NAME);if(y!==r.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${r.HEADER_NAME} header. Expected '${r.HEADER_VALUE}', got ${y?`'${y}'`:"no header"}`);if("string"==typeof p.data)try{return c.parse(p.data)}catch{}return p.data}async function g(e){let t={...e,url:e.url?.toString().replace(f(),f(r.SECONDARY_HOST_ADDRESS))};return Promise.any([(0,u.request)(e),(0,u.request)(t)])}async function y(e){let t={};return await Promise.all(e.map(e=>(async()=>{let r=await m(e);t[e.metadataKey]=r})())),t}async function _(){if(process.env.METADATA_SERVER_DETECTION){let e=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(e in r.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${e}\`, but it should be \`${Object.keys(r.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(e){case"assume-present":return!0;case"none":return!1;case"bios-only":return E()}}try{return void 0===n&&(n=m("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await n,!0}catch(e){if(process.env.DEBUG_AUTH&&console.info(e),"request-timeout"===e.type||e.response&&404===e.response.status)return!1;if(!(e.response&&404===e.response.status)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let t="UNKNOWN";e.code&&(t=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${t}`,"MetadataLookupWarning")}return!1}}function E(){return null===r.gcpResidencyCache&&v(),r.gcpResidencyCache}function v(e=null){r.gcpResidencyCache=null!==e?e:(0,d.detectGCPResidency)()}function T(){return 3e3*!E()}r.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"}),r.gcpResidencyCache=null,l(e.r(28788),r)},61011,(e,t,r)=>{"use strict";r.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return(r+n)*3/4-n},r.toByteArray=function(e){var t,r,n=u(e),s=n[0],a=n[1],l=new o((s+a)*3/4-a),c=0,d=a>0?s-4:s;for(r=0;r>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=0,a=r-i;s>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return o.join("")}(e,s,s+16383>a?a:s+16383));return 1===i?o.push(n[(t=e[r-1])>>2]+n[t<<4&63]+"=="):2===i&&o.push(n[(t=(e[r-2]<<8)+e[r-1])>>10]+n[t>>4&63]+n[t<<2&63]+"="),o.join("")};for(var n=[],i=[],o="u">typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,l=s.length;a0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}i[45]=62,i[95]=63},84052,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.fromArrayBufferToHex=function(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}},25162,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.BrowserCrypto=void 0;let n=e.r(61011),i=e.r(84052);class o{constructor(){throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return n.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),n.fromByteArray(t)}static padBase64(e){for(;e.length%4!=0;)e+="=";return e}async verify(e,t,r){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(t),a=n.toByteArray(o.padBase64(r)),l=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,l,Buffer.from(a),s)}async sign(e,t){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(t),o=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),s=await window.crypto.subtle.sign(r,o,i);return n.fromByteArray(new Uint8Array(s))}decodeBase64StringUtf8(e){let t=n.toByteArray(o.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return n.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return(0,i.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,t){let r="string"==typeof e?e:String.fromCharCode(...new Uint16Array(e)),n=new TextEncoder,i=await window.crypto.subtle.importKey("raw",n.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,n.encode(t))}}r.BrowserCrypto=o},3988,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.NodeCrypto=void 0;let n=e.r(54799);r.NodeCrypto=class{async sha256DigestBase64(e){return n.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return n.randomBytes(e).toString("base64")}async verify(e,t,r){let i=n.createVerify("RSA-SHA256");return i.update(t),i.end(),i.verify(e,r,"base64")}async sign(e,t){let r=n.createSign("RSA-SHA256");return r.update(t),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 n.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){var r;let i="string"==typeof e?e:(r=e,Buffer.from(r));return function(e){let t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.createCrypto=function(){return function(){;}(),new o.NodeCrypto},r.hasBrowserCrypto=s,e.r(25162);let o=e.r(3988);function s(){return!1}i(e.r(84052),r)},45706,(e,t,r)=>{t.exports=e.x("querystring",()=>require("querystring"))},16919,(e,t,r)=>{var n=e.r(874),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return n.SlowBuffer(e)}},48792,(e,t,r)=>{"use strict";function n(e){return(e/8|0)+ +(e%8!=0)}var i={ES256:n(256),ES384:n(384),ES512:n(521)};t.exports=function(e){var t=i[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}},43342,(e,t,r)=>{"use strict";var n=e.r(16919).Buffer,i=e.r(48792);function o(e){if(n.isBuffer(e))return e;if("string"==typeof e)return n.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function s(e,t,r){for(var n=0;t+n=128&&--n,n}t.exports={derToJose:function(e,t){e=o(e);var r=i(t),s=r+1,a=e.length,l=0;if(48!==e[l++])throw Error('Could not find expected "seq"');var u=e[l++];if(129===u&&(u=e[l++]),a-l{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LRUCache=void 0,r.snakeToCamel=a,r.originalOrCamelOptions=function(e){return{get:function(t){let r=e||{};return r[t]??r[a(t)]}}},r.removeUndefinedValuesInObject=function(e){return Object.entries(e).forEach(([t,r])=>{(void 0===r||"undefined"===r)&&delete e[t]}),e},r.isValidFile=u,r.getWellKnownCertificateConfigFileLocation=function(){let e=process.env.CLOUDSDK_CONFIG||(i.platform().startsWith("win")?o.join(process.env.APPDATA||"",s):o.join(process.env.HOME||"",".config",s));return o.join(e,"certificate_config.json")};let n=e.r(22734),i=e.r(46786),o=e.r(14747),s="gcloud";function a(e){return e.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}class l{capacity;#u=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#c(e,t){this.#u.delete(e),this.#u.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#c(e,t),this.#d()}get(e){let t=this.#u.get(e);if(t)return this.#c(e,t.value),this.#d(),t.value}#d(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#u.entries().next();for(;!t.done&&(this.#u.size>this.capacity||t.value[1].lastAccessed{e.v({name:"google-auth-library",version:"10.6.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:"packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"7.1.3","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"echo 'disabled until linkinator is fixed'","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs"})},77235,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.USER_AGENT=r.PRODUCT_NAME=r.pkg=void 0;let n=e.r(86284);r.pkg=n;let i="google-api-nodejs-client";r.PRODUCT_NAME=i,r.USER_AGENT=`${i}/${n.version}`},5567,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AuthClient=r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=r.DEFAULT_UNIVERSE=void 0;let n=e.r(27699),i=e.r(65065),o=e.r(71850),s=e.r(93199),a=e.r(77235);r.DEFAULT_UNIVERSE="googleapis.com",r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=3e5;class l extends n.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=r.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=r.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();const t=(0,o.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??r.DEFAULT_UNIVERSE,this.transporter=e.transporter??new i.Gaxios(e.transporterOptions),!1!==t.get("useAuthRequestParameters")&&(this.transporter.interceptors.request.add(l.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(l.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t,r=e[0],n=e[1],o=new Headers;return("string"==typeof r?t=new URL(r):r instanceof URL?t=r:r&&r.url&&(t=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&i.Gaxios.mergeHeaders(o,r.headers),n&&i.Gaxios.mergeHeaders(o,new Headers(n.headers)),"object"!=typeof r||r instanceof URL)?this.request({...n,headers:o,url:t}):this.request({...n,...r,headers:o,url:t})}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,t){let r=t.get("x-goog-user-project"),n=t.get("authorization");return r&&e.set("x-goog-user-project",r),n&&e.set("authorization",n),e}static log=(0,s.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let t=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${t}`)}let t=e.headers.get("User-Agent");t?t.includes(`${a.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${a.USER_AGENT}`):e.headers.set("User-Agent",a.USER_AGENT);try{let t=e[l.RequestMethodNameSymbol],r=`${Math.floor(1e3*Math.random())}`;e[l.RequestLogIdSymbol]=r;let n={url:e.url,headers:e.headers};t?l.log.info("%s [%s] request %j",t,r,n):l.log.info("[%s] request %j",r,n)}catch(e){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let t=e.config,r=t[l.RequestMethodNameSymbol],n=t[l.RequestLogIdSymbol];r?l.log.info("%s [%s] response %j",r,n,e.data):l.log.info("[%s] response %j",n,e.data)}catch(e){}return e},rejected:async e=>{try{let t=e.config,r=t[l.RequestMethodNameSymbol],n=t[l.RequestLogIdSymbol];r?l.log.info("%s [%s] error %j",r,n,e.response?.data):l.log.error("[%s] error %j",n,e.response?.data)}catch(e){}throw e}};static setMethodName(e,t){try{e[l.RequestMethodNameSymbol]=t}catch(e){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}r.AuthClient=l},45219,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LoginTicket=void 0,r.LoginTicket=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}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()}}}},43812,(e,t,r)=>{"use strict";var n,i,o,s,a,l;Object.defineProperty(r,"__esModule",{value:!0}),r.OAuth2Client=r.ClientAuthentication=r.CertificateFormat=r.CodeChallengeMethod=void 0;let u=e.r(65065),c=e.r(45706),d=e.r(88947),p=e.r(43342),h=e.r(71850),f=e.r(24715),m=e.r(5567),g=e.r(45219);(s=n||(r.CodeChallengeMethod=n={})).Plain="plain",s.S256="S256",(a=i||(r.CertificateFormat=i={})).PEM="PEM",a.JWK="JWK",(l=o||(r.ClientAuthentication=o={})).ClientSecretPost="ClientSecretPost",l.ClientSecretBasic="ClientSecretBasic",l.None="None";class y extends m.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=i.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,r){super("object"==typeof e?e:{}),"object"!=typeof e&&(e={clientId:e,clientSecret:t,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||o.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw Error("If a code_challenge_method is provided, code_challenge must be included.");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()+"?"+c.stringify(e)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,f.createCrypto)(),t=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),r=(await e.sha256DigestBase64(t)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:t,codeChallenge:r}}getToken(e,t){let r="string"==typeof e?{code:e}:e;if(!t)return this.getTokenAsync(r);this.getTokenAsync(r).then(e=>t(null,e.tokens,e.res),e=>t(e,null,e.response))}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,n={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===o.ClientSecretBasic){let e=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${e.toString("base64")}`)}this.clientAuthentication===o.ClientSecretPost&&(n.client_secret=this._clientSecret);let i={...y.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,h.removeUndefinedValuesInObject)(n)),headers:r};m.AuthClient.setMethodName(i,"getTokenAsync");let s=await this.transporter.request(i),a=s.data;return s.data&&s.data.expires_in&&(a.expiry_date=new Date().getTime()+1e3*s.data.expires_in,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:s}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(t=>(this.refreshTokenPromises.delete(e),t),t=>{throw this.refreshTokenPromises.delete(e),t});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){let t;if(!e)throw Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"};try{let e={...y.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,h.removeUndefinedValuesInObject)(n))};m.AuthClient.setMethodName(e,"refreshTokenNoCache"),t=await this.transporter.request(e)}catch(e){throw e instanceof u.GaxiosError&&"invalid_grant"===e.message&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}let i=t.data;return t.data&&t.data.expires_in&&(i.expiry_date=new Date().getTime()+1e3*t.data.expires_in,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:t}}refreshAccessToken(e){if(!e)return this.refreshAccessTokenAsync();this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e)}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(!e)return this.getAccessTokenAsync();this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e)}async getAccessTokenAsync(){if(!(!this.credentials.access_token||this.isTokenExpiring()))return{token:this.credentials.access_token};{if(!this.credentials.refresh_token)if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token)return this.setCredentials(e),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let e=await this.refreshAccessTokenAsync();if(!e.credentials||e.credentials&&!e.credentials.access_token)throw Error("Could not refresh access token.");return{token:e.credentials.access_token,res:e.res}}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let e=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(e)}}if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token){this.setCredentials(e);let t=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(t)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,n=null;try{n=(r=await this.refreshToken(t.refresh_token)).tokens}catch(e){throw e.response&&(403===e.response.status||404===e.response.status)&&(e.message=`Could not refresh access token: ${e.message}`),e}let i=this.credentials;i.token_type=i.token_type||"Bearer",n.refresh_token=i.refresh_token,this.credentials=n;let o=new Headers({authorization:i.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(o),res:r.res}}static getRevokeTokenUrl(e){return new y().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let r={...y.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(m.AuthClient.setMethodName(r,"revokeToken"),!t)return this.transporter.request(r);this.transporter.request(r).then(e=>t(null,e),t)}revokeCredentials(e){if(!e)return this.revokeCredentialsAsync();this.revokeCredentialsAsync().then(t=>e(null,t),e)}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw Error("No access token to revoke.")}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){try{let t=await this.getRequestMetadataAsync();return e.headers=u.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),o=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,s=r.config.data instanceof d.Readable,a=401===n||403===n;if(!t&&a&&!s&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&a&&!s&&o){let t=await this.processAndValidateRefreshHandler();return t?.access_token&&this.setCredentials(t),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&"function"!=typeof t)throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(!t)return this.verifyIdTokenAsync(e);this.verifyIdTokenAsync(e).then(e=>t(null,e),t)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...y.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()+1e3*t.expires_in,scopes:t.scope.split(" ")},t);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(!e)return this.getFederatedSignonCertsAsync();this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e)}async getFederatedSignonCertsAsync(){let e,t,r=new Date().getTime(),n=(0,f.hasBrowserCrypto)()?i.JWK:i.PEM;if(this.certificateExpiry&&r[0-9]+)/.exec(o)?.groups?.maxAge;e&&(s=1e3*Number(e))}let a={};switch(n){case i.PEM:a=e.data;break;case i.JWK:for(let t of e.data.keys)a[t.kid]=t;break;default:throw Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=-1===s?null:new Date(l.getTime()+s),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,format:n,res:e}}getIapPublicKeys(e){if(!e)return this.getIapPublicKeysAsync();this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e)}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...y.RETRY_CONFIG,url:t};m.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,r,n,i){let o,s,a=(0,f.createCrypto)();i||(i=y.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(3!==l.length)throw Error("Wrong number of segments in token: "+e);let u=l[0]+"."+l[1],c=l[2];try{o=JSON.parse(a.decodeBase64StringUtf8(l[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${l[0]}': ${e.message}`),e}if(!o)throw Error("Can't parse token envelope: "+l[0]);try{s=JSON.parse(a.decodeBase64StringUtf8(l[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${l[0]}`),e}if(!s)throw Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(t,o.kid))throw Error("No pem found for envelope: "+JSON.stringify(o));let d=t[o.kid];if("ES256"===o.alg&&(c=p.joseToDer(c,"ES256").toString("base64")),!await a.verify(d,u,c))throw Error("Invalid token signature: "+e);if(!s.iat)throw Error("No issue time in token: "+JSON.stringify(s));if(!s.exp)throw Error("No expiration time in token: "+JSON.stringify(s));let h=Number(s.iat);if(isNaN(h))throw Error("iat field using invalid format");let m=Number(s.exp);if(isNaN(m))throw Error("exp field using invalid format");let _=new Date().getTime()/1e3;if(m>=_+i)throw Error("Expiration time too far in future: "+JSON.stringify(s));let E=h-y.CLOCK_SKEW_SECS_,v=m+y.CLOCK_SKEW_SECS_;if(_v)throw Error("Token used too late, "+_+" > "+v+": "+JSON.stringify(s));if(n&&0>n.indexOf(s.iss))throw Error("Invalid issuer, expected one of ["+n+"], but got "+s.iss);if(null!=r){let e=s.aud;if(!(r.constructor===Array?r.indexOf(e)>-1:e===r))throw Error("Wrong recipient, payload audience != requiredAudience")}return new g.LoginTicket(o,s)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return!!e&&e<=new Date().getTime()+this.eagerRefreshThresholdMillis}}r.OAuth2Client=y},72020,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Compute=void 0;let n=e.r(65065),i=e.r(37876),o=e.r(43812);class s extends o.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,t=`service-accounts/${this.serviceAccountEmail}/token`;try{let r={property:t};this.scopes.length>0&&(r.params={scopes:this.scopes.join(",")}),e=await i.instance(r)}catch(e){throw e instanceof n.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}let r=e;return e&&e.expires_in&&(r.expiry_date=new Date().getTime()+1e3*e.expires_in,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let t,r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`;try{t=await i.instance({property:r})}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return t}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,403===t.status?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:404===t.status&&(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))}}r.Compute=s},19820,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.IdTokenClient=void 0;let n=e.r(43812);class i extends n.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 e=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:e,expiry_date:this.getIdTokenExpiryDate(e)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return 1e3*JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp}}r.IdTokenClient=i},68791,(e,t,r)=>{"use strict";var n,i;let o;Object.defineProperty(r,"__esModule",{value:!0}),r.GCPEnv=void 0,r.clear=function(){o=void 0},r.getEnv=a;let s=e.r(37876);async function a(){return o||(o=l())}async function l(){n.NONE;return process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME?n.APP_ENGINE:process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET?n.CLOUD_FUNCTIONS:await c()?await u()?n.KUBERNETES_ENGINE:process.env.K_CONFIGURATION?n.CLOUD_RUN:process.env.CLOUD_RUN_JOB?n.CLOUD_RUN_JOBS:n.COMPUTE_ENGINE:n.NONE}async function u(){try{return await s.instance("attributes/cluster-name"),!0}catch(e){return!1}}async function c(){return s.isAvailable()}(i=n||(r.GCPEnv=n={})).APP_ENGINE="APP_ENGINE",i.KUBERNETES_ENGINE="KUBERNETES_ENGINE",i.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",i.COMPUTE_ENGINE="COMPUTE_ENGINE",i.CLOUD_RUN="CLOUD_RUN",i.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",i.NONE="NONE"},46563,(e,t,r)=>{var n=e.r(16919).Buffer,i=e.r(88947);function o(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(24361).inherits(o,i),o.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit("data",e)},o.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=o},21153,(e,t,r)=>{"use strict";var n=e.r(874).Buffer,i=e.r(874).SlowBuffer;function o(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i{var n,i=e.r(16919).Buffer,o=e.r(54799),s=e.r(43342),a=e.r(24361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof o.createPublicKey;function d(e){if(!i.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw m(u)}function p(e){if(!i.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw m("key must be a string, a buffer or an object")}function h(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r{var n=e.r(874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||n.isBuffer(e)?e.toString():JSON.stringify(e)}},90721,(e,t,r)=>{var n=e.r(16919).Buffer,i=e.r(46563),o=e.r(30967),s=e.r(88947),a=e.r(55873),l=e.r(24361);function u(e,t){return n.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,n,i=e.header,s=e.payload,c=e.secret||e.privateKey,d=e.encoding,p=o(i.alg),h=(t=(t=d)||"utf8",r=u(a(i),"binary"),n=u(a(s),t),l.format("%s.%s",r,n)),f=p.sign(h,c);return l.format("%s.%s",h,f)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new i(e.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))}l.inherits(d,s),d.prototype.sign=function(){try{var e=c({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(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},44175,(e,t,r)=>{var n=e.r(16919).Buffer,i=e.r(46563),o=e.r(30967),s=e.r(88947),a=e.r(55873),l=e.r(24361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=n.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function p(e){return u.test(e)&&!!c(e)}function h(e,t,r){if(!t){var n=Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var i=d(e=a(e)),s=e.split(".",2).join(".");return o(t).verify(s,i,r)}function f(e,t){if(t=t||{},!p(e=a(e)))return null;var r,i,o=c(e);if(!o)return null;var s=(r=r||"utf8",i=e.split(".")[1],n.from(i,"base64").toString(r));return("JWT"===o.typ||t.json)&&(s=JSON.parse(s,t.encoding)),{header:o,payload:s,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new i(e.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))}l.inherits(m,s),m.prototype.verify=function(){try{var e=h(this.signature.buffer,this.algorithm,this.key.buffer),t=f(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=f,m.isValid=p,m.verify=h,t.exports=m},64428,(e,t,r)=>{var n=e.r(90721),i=e.r(44175);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=n.sign,r.verify=i.verify,r.decode=i.decode,r.isValid=i.isValid,r.createSign=function(e){return new n(e)},r.createVerify=function(e){return new i(e)}},23227,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.buildPayloadForJwsSign=i,r.getJwsSign=function(e){let t=i(e);return(0,n.sign)({header:{alg:"RS256"},payload:t,secret:e.key})};let n=e.r(64428);function i(e){let t=Math.floor(new Date().getTime()/1e3);return{iss:e.iss,scope:e.scope,aud:"https://oauth2.googleapis.com/token",exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}},96496,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getToken=i;let n=e.r(23227);async function i(e){if(!e.transporter)throw Error("No transporter set.");try{let t={method:"POST",url:"https://oauth2.googleapis.com/token",data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:(0,n.getJwsSign)(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}};return(await e.transporter.request(t)).data}catch(t){let e=t.response?.data;throw e?.error&&(t.message=`${e.error}: ${e.error_description}`),t}}},76674,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ErrorWithCode=void 0,r.ErrorWithCode=class extends Error{code;constructor(e,t){super(e),this.code=t}}},20975,(e,t,r)=>{"use strict";var n,i;Object.defineProperty(r,"__esModule",{value:!0}),r.getCredentials=f;let o=e.r(14747),s=e.r(22734),a=e.r(24361),l=e.r(76674),u=(0,a.promisify)(s.readFile);(i=n||(n={})).JSON=".json",i.DER=".der",i.CRT=".crt",i.PEM=".pem",i.P12=".p12",i.PFX=".pfx";class c{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e,t=await u(this.keyFilePath,"utf8");try{e=JSON.parse(t)}catch(e){throw Error(`Invalid JSON key file: ${e.message}`)}let r=e.private_key,n=e.client_email;if(!r||!n)throw new l.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:n}}}class d{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await u(this.keyFilePath,"utf8")}}}class p{async getCredentials(){throw new l.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}}class h{static create(e){switch(o.extname(e)){case n.JSON:return new c(e);case n.DER:case n.CRT:case n.PEM:return new d(e);case n.P12:case n.PFX:return new p;default:throw new l.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function f(e){return h.create(e).getCredentials()}},6518,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TokenHandler=void 0;let n=e.r(96496),i=e.r(20975);r.TokenHandler=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await (0,i.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){return new Date().getTime(),!this.token||!this.tokenExpiresAt||new Date().getTime()>=this.tokenExpiresAt}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,n.getToken)(this.tokenOptions);let e=await this.inFlightRequest;return this.token=e,this.tokenExpiresAt=new Date().getTime()+(e.expires_in??0)*1e3,e}finally{this.inFlightRequest=void 0}}}},33216,(e,t,r)=>{"use strict";async function n(e,t){return await t.request({url:"https://oauth2.googleapis.com/revoke?token="+e,retry:!0})}Object.defineProperty(r,"__esModule",{value:!0}),r.revokeToken=n},12408,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleToken=void 0;let n=e.r(65065),i=e.r(6518),o=e.r(33216);r.GoogleToken=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:e=>(0,n.request)(e)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),"object"==typeof this.tokenOptions.scope&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new i.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,t={forceRefresh:!1}){let r;"function"==typeof e?r=e:"object"==typeof e&&(t=e);let n=this.tokenHandler.getToken(t.forceRefresh??!1);return r&&n.then(e=>r(null,e),r),n}revokeToken(e){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let t=(0,o.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&t.then(()=>e(),e),this.tokenHandler=new i.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}},95479,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.JWTAccess=void 0;let n=e.r(64428),i=e.r(71850),o={alg:"RS256",typ:"JWT"};class s{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new i.LRUCache({capacity:500,maxAge:36e5});constructor(e,t,r,n){this.email=e,this.key=t,this.keyId=r,this.eagerRefreshThresholdMillis=n??3e5}getCachedKey(e,t){let r=e;if(t&&Array.isArray(t)&&t.length?r=e?`${e}_${t.join("_")}`:`${t.join("_")}`:"string"==typeof t&&(r=e?`${e}_${t}`:t),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,t,r){let i,a=this.getCachedKey(e,r),l=this.cache.get(a),u=Date.now();if(l&&l.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(l.headers);let c=Math.floor(Date.now()/1e3),d=s.getExpirationTime(c);if(Array.isArray(r)&&(r=r.join(" ")),i=r?{iss:this.email,sub:this.email,scope:r,exp:d,iat:c}:{iss:this.email,sub:this.email,aud:e,exp:d,iat:c},t){for(let e in i)if(t[e])throw Error(`The '${e}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let p=this.keyId?{...o,kid:this.keyId}:o,h=Object.assign(i,t),f=n.sign({header:p,payload:h,secret:this.key}),m=new Headers({authorization:`Bearer ${f}`});return this.cache.set(a,{expiration:1e3*d,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}fromStreamAsync(e){return new Promise((t,r)=>{e||r(Error("Must pass in a stream containing the service account auth settings."));let n="";e.setEncoding("utf8").on("data",e=>n+=e).on("error",r).on("end",()=>{try{let e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}})})}}r.JWTAccess=s},25922,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.JWT=void 0;let n=e.r(12408),i=e.r(20975),o=e.r(95479),s=e.r(43812),a=e.r(5567);class l extends s.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new l(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==a.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==a.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${a.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:e}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${e.id_token}`}))}}else{let t;this.access||(this.access=new o.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis)),this.hasUserScopes()?t=this.scopes:e||(t=this.defaultScopes);let r=this.useJWTAccessWithScope||this.universeDomain!==a.DEFAULT_UNIVERSE,n=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,r?t:void 0);return{headers:this.addSharedMetadataHeaders(n)}}return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let t=new n.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){return!!this.scopes&&this.scopes.length>0}hasAnyScopes(){return!!this.scopes&&!!(this.scopes.length>0)||!!this.defaultScopes&&!!(this.defaultScopes.length>0)}authorize(e){if(!e)return this.authorizeAsync();this.authorizeAsync().then(t=>e(null,t),e)}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),t={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",t),{res:null,tokens:t}}createGToken(){return this.gtoken||(this.gtoken=new n.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 Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}fromStreamAsync(e){return new Promise((t,r)=>{if(!e)throw Error("Must pass in a stream containing the service account auth settings.");let n="";e.setEncoding("utf8").on("error",r).on("data",e=>n+=e).on("end",()=>{try{let e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}})})}fromAPIKey(e){if("string"!=typeof e)throw Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){this.createGToken();let e=await (0,i.getCredentials)(this.keyFile);return{private_key:e.privateKey,client_email:e.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}r.JWT=l},87155,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UserRefreshClient=r.USER_REFRESH_ACCOUNT_TYPE=void 0;let n=e.r(43812),i=e.r(5567);r.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class o extends n.OAuth2Client{_refreshToken;constructor(e,t,r,n,i){const o=e&&"object"==typeof e?e:{clientId:e,clientSecret:t,refreshToken:r,eagerRefreshThresholdMillis:n,forceRefreshOnFailure:i};super(o),this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...o.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 i.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the user refresh token");if("authorized_user"!==e.type)throw Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then(()=>t(),t)}async fromStreamAsync(e){return new Promise((t,r)=>{if(!e)return r(Error("Must pass in a stream containing the user refresh token."));let n="";e.setEncoding("utf8").on("error",r).on("data",e=>n+=e).on("end",()=>{try{let e=JSON.parse(n);return this.fromJSON(e),t()}catch(e){return r(e)}})})}static fromJSON(e){let t=new o;return t.fromJSON(e),t}}r.UserRefreshClient=o},7534,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Impersonated=r.IMPERSONATED_ACCOUNT_TYPE=void 0;let n=e.r(43812),i=e.r(65065),o=e.r(71850);r.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class s extends n.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 n.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,(0,o.originalOrCamelOptions)(e).get("universe_domain")){if(this.sourceClient.universeDomain!==this.universeDomain)throw RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`)}else this.universeDomain=this.sourceClient.universeDomain;this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${t}:signBlob`,n={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...s.RETRY_CONFIG,url:r,data:n,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},n=await this.sourceClient.request({...s.RETRY_CONFIG,url:t,data:r,method:"POST"}),i=n.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:n}}catch(r){if(!(r instanceof Error))throw r;let e=0,t="";if(r instanceof i.GaxiosError&&(e=r?.response?.data?.error?.status,t=r?.response?.data?.error?.message),e&&t)throw r.message=`${e}: unable to impersonate: ${t}`,r;throw r.message=`unable to impersonate: ${r}`,r}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...s.RETRY_CONFIG,url:n,data:i,method:"POST"})).data.token}}r.Impersonated=s},15774,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.OAuthClientAuthHandler=void 0,r.getErrorFromOAuthErrorResponse=function(e,t){let r=e.error,n=e.error_description,i=e.error_uri,o=`Error code ${r}`;void 0!==n&&(o+=`: ${n}`),void 0!==i&&(o+=` - ${i}`);let s=Error(o);if(t){let e=Object.keys(t);t.stack&&e.push("stack"),e.forEach(e=>{"message"!==e&&Object.defineProperty(s,e,{value:t[e],writable:!1,enumerable:!0})})}return s};let n=e.r(65065),i=e.r(24715),o=["PUT","POST","PATCH"];class s{#p=(0,i.createCrypto)();#h;transporter;constructor(e){e&&"clientId"in e?(this.#h=e,this.transporter=new n.Gaxios):(this.#h=e?.clientAuthentication,this.transporter=e?.transporter||new n.Gaxios)}applyClientAuthenticationOptions(e,t){e.headers=n.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),t||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=n.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#h?.confidentialClientType==="basic"){e.headers=n.Gaxios.mergeHeaders(e.headers);let t=this.#h.clientId,r=this.#h.clientSecret||"",i=this.#p.encodeBase64StringUtf8(`${t}:${r}`);n.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#h?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!o.includes(t))throw Error(`${t} HTTP method does not support ${this.#h.confidentialClientType} client authentication`);let r=new Headers(e.headers).get("content-type");if(r?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let t=new URLSearchParams(e.data??"");t.append("client_id",this.#h.clientId),t.append("client_secret",this.#h.clientSecret||""),e.data=t}else if(r?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#h.clientId,client_secret:this.#h.clientSecret||""});else throw Error(`${r} content-types are not supported with ${this.#h.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}r.OAuthClientAuthHandler=s},91007,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.StsCredentials=void 0;let n=e.r(65065),i=e.r(5567),o=e.r(15774),s=e.r(71850);class a extends o.OAuthClientAuthHandler{#f;constructor(e={tokenExchangeEndpoint:""},t){("object"!=typeof e||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#f=e.tokenExchangeEndpoint}async exchangeToken(e,t,r){let l={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)},u={...a.RETRY_CONFIG,url:this.#f.toString(),method:"POST",headers:t,data:new URLSearchParams((0,s.removeUndefinedValuesInObject)(l)),responseType:"json"};i.AuthClient.setMethodName(u,"exchangeToken"),this.applyClientAuthenticationOptions(u);try{let e=await this.transporter.request(u),t=e.data;return t.res=e,t}catch(e){if(e instanceof n.GaxiosError&&e.response)throw(0,o.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}}r.StsCredentials=a},1668,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.BaseExternalAccountClient=r.CLOUD_RESOURCE_MANAGER=r.EXTERNAL_ACCOUNT_TYPE=r.EXPIRATION_TIME_OFFSET=void 0;let n=e.r(65065),i=e.r(88947),o=e.r(5567),s=e.r(91007),a=e.r(71850),l=e.r(77235),u="https://www.googleapis.com/auth/cloud-platform";r.EXPIRATION_TIME_OFFSET=3e5,r.EXTERNAL_ACCOUNT_TYPE="external_account",r.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";class c extends o.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#m=null;constructor(e){super(e);const t=(0,a.originalOrCamelOptions)(e),n=t.get("type");if(n&&n!==r.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${r.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);const i=t.get("client_id"),o=t.get("client_secret");this.tokenUrl=t.get("token_url")??"https://sts.{universeDomain}/v1/token".replace("{universeDomain}",this.universeDomain);const l=t.get("subject_token_type"),c=t.get("workforce_pool_user_project"),d=t.get("service_account_impersonation_url"),p=t.get("service_account_impersonation"),h=(0,a.originalOrCamelOptions)(p).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:o}),this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[u],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=l,this.workforcePoolUserProject=c;const f=RegExp("//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+");if(this.workforcePoolUserProject&&!this.audience.match(f))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=h,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=3600),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);let e=/serviceAccounts\/(?[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl);return e?.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(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let t=await this.getRequestHeaders(),r={...c.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};o.AuthClient.setMethodName(r,"getProjectId");let n=await this.transporter.request(r);return this.projectId=n.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,o=r.config.data instanceof i.Readable;if(!t&&(401===n||403===n)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){this.#m=this.#m||this.#g();try{return await this.#m}finally{this.#m=null}}async #g(){let e=await this.retrieveSubjectToken(),t={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",audience:this.audience,requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[u]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,n=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(t,n,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+1e3*i.expires_in,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.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 t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let t={...c.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"};o.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let r=await this.transporter.request(t),n=r.data;return{access_token:n.accessToken,expiry_date:new Date(n.expireTime).getTime(),res:r}}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}getScopesArray(){return"string"==typeof this.scopes?[this.scopes]:this.scopes||[u]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=void 0!==this.serviceAccountImpersonationUrl,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${l.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}r.BaseExternalAccountClient=c},13374,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.FileSubjectTokenSupplier=void 0;let n=e.r(24361),i=e.r(22734),o=(0,n.promisify)(i.readFile??(()=>{})),s=(0,n.promisify)(i.realpath??(()=>{})),a=(0,n.promisify)(i.lstat??(()=>{}));r.FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e,t=this.filePath;try{if(t=await s(t),!(await a(t)).isFile())throw Error()}catch(e){throw e instanceof Error&&(e.message=`The file at ${t} does not exist, or it is not a file. ${e.message}`),e}let r=await o(t,{encoding:"utf8"});if("text"===this.formatType?e=r:"json"===this.formatType&&this.subjectTokenFieldName&&(e=JSON.parse(r)[this.subjectTokenFieldName]),!e)throw Error("Unable to parse the subject_token from the credential_source file");return e}}},87545,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UrlSubjectTokenSupplier=void 0;let n=e.r(5567);r.UrlSubjectTokenSupplier=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 t,r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};if(n.AuthClient.setMethodName(r,"getSubjectToken"),"text"===this.formatType?t=(await e.transporter.request(r)).data:"json"===this.formatType&&this.subjectTokenFieldName&&(t=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!t)throw Error("Unable to parse the subject_token from the credential_source URL");return t}}},61880,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.CertificateSubjectTokenSupplier=r.InvalidConfigurationError=r.CertificateSourceUnavailableError=r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;let n=e.r(71850),i=e.r(22734),o=e.r(54799),s=e.r(24836);r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class a extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}}r.CertificateSourceUnavailableError=a;class l extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}}r.InvalidConfigurationError=l,r.CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new l("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new l("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new l("Cannot create mTLS Agent with missing certificate or key");return new s.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#y();let{certPath:e,keyPath:t}=await this.#_();return{cert:this.cert,key:this.key}=await this.#E(e,t),await this.#v(this.cert)}async #y(){let e=this.certificateConfigPath;if(e){if(await (0,n.isValidFile)(e))return e;throw new a(`Provided certificate config path is invalid: ${e}`)}let t=process.env[r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await (0,n.isValidFile)(t))return t;throw new a(`Path from environment variable "${r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let i=(0,n.getWellKnownCertificateConfigFileLocation)();if(await (0,n.isValidFile)(i))return i;throw new a(`Could not find certificate configuration file. Searched override path, the "${r.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async #_(){let e,t=this.certificateConfigPath;try{e=await i.promises.readFile(t,"utf8")}catch(e){throw new a(`Failed to read certificate config file at: ${t}`)}try{let r=JSON.parse(e),n=r?.cert_configs?.workload?.cert_path,i=r?.cert_configs?.workload?.key_path;if(!n||!i)throw new l(`Certificate config file (${t}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:n,keyPath:i}}catch(e){if(e instanceof l)throw e;throw new l(`Failed to parse certificate config from ${t}: ${e.message}`)}}async #E(e,t){let r,n;try{r=await i.promises.readFile(e),new o.X509Certificate(r)}catch(r){let t=r instanceof Error?r.message:String(r);throw new a(`Failed to read certificate file at ${e}: ${t}`)}try{n=await i.promises.readFile(t),(0,o.createPrivateKey)(n)}catch(r){let e=r instanceof Error?r.message:String(r);throw new a(`Failed to read private key file at ${t}: ${e}`)}return{cert:r,key:n}}async #v(e){let t=new o.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let e,r=((await i.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((e,t)=>{try{return new o.X509Certificate(e)}catch(r){let e=r instanceof Error?r.message:String(r);throw new l(`Failed to parse certificate at index ${t} in trust chain file ${this.trustChainPath}: ${e}`)}}),n=r.findIndex(e=>t.raw.equals(e.raw));if(-1===n)e=[t,...r];else if(0===n)e=r;else throw new l(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${n}).`);return JSON.stringify(e.map(e=>e.raw.toString("base64")))}catch(t){if(t instanceof l)throw t;let e=t instanceof Error?t.message:String(t);throw new a(`Failed to process certificate chain from ${this.trustChainPath}: ${e}`)}}}},984,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.IdentityPoolClient=void 0;let n=e.r(1668),i=e.r(71850),o=e.r(13374),s=e.r(87545),a=e.r(61880),l=e.r(91007),u=e.r(65065);class c extends n.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);const t=(0,i.originalOrCamelOptions)(e),r=t.get("credential_source"),n=t.get("subject_token_supplier");if(!r&&!n)throw Error("A credential source or subject token supplier must be specified.");if(r&&n)throw Error("Only one of credential source or subject token supplier can be specified.");if(n)this.subjectTokenSupplier=n,this.credentialSourceType="programmatic";else{const e=(0,i.originalOrCamelOptions)(r),t=(0,i.originalOrCamelOptions)(e.get("format")),n=t.get("type")||"text",l=t.get("subject_token_field_name");if("json"!==n&&"text"!==n)throw Error(`Invalid credential_source format "${n}"`);if("json"===n&&!l)throw Error("Missing subject_token_field_name for JSON credential_source format");const u=e.get("file"),d=e.get("url"),p=e.get("certificate"),h=e.get("headers");if(u&&d||d&&p||u&&p)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(u)this.credentialSourceType="file",this.subjectTokenSupplier=new o.FileSubjectTokenSupplier({filePath:u,formatType:n,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new s.UrlSubjectTokenSupplier({url:d,formatType:n,subjectTokenFieldName:l,headers:h,additionalGaxiosOptions:c.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";const e=new a.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=e}else throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof a.CertificateSubjectTokenSupplier){let e=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new l.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new u.Gaxios({agent:e})}),this.transporter=new u.Gaxios({...this.transporter.defaults||{},agent:e})}return e}}r.IdentityPoolClient=c},3168,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AwsRequestSigner=void 0;let n=e.r(65065),i=e.r(24715),o="AWS4-HMAC-SHA256";async function s(e,t,r){return await e.signWithHmacSha256(t,r)}async function a(e,t,r,n,i){let o=await s(e,`AWS4${t}`,r),a=await s(e,o,n),l=await s(e,a,i);return await s(e,l,"aws4_request")}async function l(e){let t=n.Gaxios.mergeHeaders(e.additionalAmzHeaders),r=e.requestPayload||"",l=e.host.split(".")[0],u=new Date,c=u.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),d=u.toISOString().replace(/[-]/g,"").replace(/T.*/,"");e.securityCredentials.token&&t.set("x-amz-security-token",e.securityCredentials.token);let p=n.Gaxios.mergeHeaders({host:e.host},t.has("date")?{}:{"x-amz-date":c},t),h="",f=[...p.keys()].sort();f.forEach(e=>{h+=`${e}:${p.get(e)} `});let m=f.join(";"),g=await e.crypto.sha256DigestHex(r),y=`${e.method.toUpperCase()} ${e.canonicalUri} ${e.canonicalQuerystring} ${h} ${m} ${g}`,_=`${d}/${e.region}/${l}/aws4_request`,E=`${o} ${c} ${_} `+await e.crypto.sha256DigestHex(y),v=await a(e.crypto,e.securityCredentials.secretAccessKey,d,e.region,l),T=await s(e.crypto,v,E),A=`${o} Credential=${e.securityCredentials.accessKeyId}/${_}, SignedHeaders=${m}, Signature=${(0,i.fromArrayBufferToHex)(T)}`;return{amzDate:t.has("date")?void 0:c,authorizationHeader:A,canonicalQuerystring:e.canonicalQuerystring}}r.AwsRequestSigner=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,i.createCrypto)()}async getRequestOptions(e){if(!e.url)throw RangeError('"url" is required in "amzOptions"');let t="object"==typeof e.data?JSON.stringify(e.data):e.data,r=e.url,i=e.method||"GET",o=e.body||t,s=e.headers,a=await this.getCredentials(),u=new URL(r);if("string"!=typeof o&&void 0!==o)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${o}`);let c=await l({crypto:this.crypto,host:u.host,canonicalUri:u.pathname,canonicalQuerystring:u.search.slice(1),method:i,region:this.region,securityCredentials:a,requestPayload:o,additionalAmzHeaders:s}),d=n.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:u.host},s||{});a.token&&n.Gaxios.mergeHeaders(d,{"x-amz-security-token":a.token});let p={url:r,method:i,headers:d};return void 0!==o&&(p.body=o),p}}},8775,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.DefaultAwsSecurityCredentialsSupplier=void 0;let n=e.r(5567);r.DefaultAwsSecurityCredentialsSupplier=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.#T)return this.#T;let t=new Headers;if(!this.#T&&this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#A(e.transporter)),!this.regionUrl)throw 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:t};n.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.#S)return this.#S;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#A(e.transporter));let r=await this.#b(t,e.transporter),n=await this.#C(r,t,e.transporter);return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,token:n.Token}}async #A(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return n.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async #b(e,t){if(!this.securityCredentialsUrl)throw 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 n.AuthClient.setMethodName(r,"#getAwsRoleName"),(await t.request(r)).data}async #C(e,t,r){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t,responseType:"json"};return n.AuthClient.setMethodName(i,"#retrieveAwsSecurityCredentials"),(await r.request(i)).data}get #T(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get #S(){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}}},85338,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AwsClient=void 0;let n=e.r(3168),i=e.r(1668),o=e.r(8775),s=e.r(71850),a=e.r(65065);class l extends i.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static #O="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);const t=(0,s.originalOrCamelOptions)(e),r=t.get("credential_source"),n=t.get("aws_security_credentials_supplier");if(!r&&!n)throw Error("A credential source or AWS security credentials supplier must be specified.");if(r&&n)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(n)this.awsSecurityCredentialsSupplier=n,this.regionalCredVerificationUrl=l.#O,this.credentialSourceType="programmatic";else{const e=(0,s.originalOrCamelOptions)(r);this.environmentId=e.get("environment_id");const t=e.get("region_url"),n=e.get("url"),i=e.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new o.DefaultAwsSecurityCredentialsSupplier({regionUrl:t,securityCredentialsUrl:n,imdsV2SessionTokenUrl:i}),this.regionalCredVerificationUrl=e.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){if(1!==parseInt(e[2],10))throw Error(`aws version "${e[2]}" is not supported in the current build.`)}else throw Error('No valid AWS "credential_source" provided')}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new n.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...l.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return a.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((e,r)=>t.push({key:r,value:e})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}}r.AwsClient=l},21475,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidSubjectTokenError=r.InvalidMessageFieldError=r.InvalidCodeFieldError=r.InvalidTokenTypeFieldError=r.InvalidExpirationTimeFieldError=r.InvalidSuccessFieldError=r.InvalidVersionFieldError=r.ExecutableResponseError=r.ExecutableResponse=void 0;let n="urn:ietf:params:oauth:token-type:saml2",i="urn:ietf:params:oauth:token-type:id_token",o="urn:ietf:params:oauth:token-type:jwt";r.ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new a("Executable response must contain a 'version' field.");if(void 0===e.success)throw new l("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!==n&&this.tokenType!==i&&this.tokenType!==o)throw new u(`Executable response must contain a 'token_type' field when successful and it must be one of ${i}, ${o}, or ${n}.`);if(this.tokenType===n){if(!e.saml_response)throw new p(`Executable response must contain a 'saml_response' field when token_type=${n}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new p(`Executable response must contain a 'id_token' field when token_type=${i} or ${o}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new c("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new d("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 void 0!==this.expirationTime&&this.expirationTime{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.PluggableAuthHandler=r.ExecutableError=void 0;let n=e.r(21475),i=e.r(33405),o=e.r(22734);class s extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}r.ExecutableError=s;class a{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw Error("No command provided.");if(this.commandComponents=a.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,r)=>{let o=i.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",e=>{a+=e}),o.stderr.on("data",e=>{a+=e});let l=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",e=>{if(clearTimeout(l),0!==e)return r(new s(a,e.toString()));try{let e=JSON.parse(a),r=new n.ExecutableResponse(e);return t(r)}catch(e){if(e instanceof n.ExecutableResponseError)return r(e);return r(new n.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}})})}async retrieveCachedResponse(){let e;if(!this.outputFile||0===this.outputFile.length)return;try{e=await o.promises.realpath(this.outputFile)}catch{return}if(!(await o.promises.lstat(e)).isFile())return;let t=await o.promises.readFile(e,{encoding:"utf8"});if(""!==t)try{let e=JSON.parse(t);if(new n.ExecutableResponse(e).isValid())return new n.ExecutableResponse(e);return}catch(e){if(e instanceof n.ExecutableResponseError)throw e;throw new n.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let e=0;e{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.PluggableAuthClient=r.ExecutableError=void 0;let n=e.r(1668),i=e.r(21475),o=e.r(33946);var s=e.r(33946);Object.defineProperty(r,"ExecutableError",{enumerable:!0,get:function(){return s.ExecutableError}});class a extends n.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable||(this.command=e.credential_source.executable.command,!this.command))throw Error('No valid Pluggable Auth "credential_source" provided.');if(void 0===e.credential_source.executable.timeout_millis)this.timeoutMillis=3e4;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<5e3||this.timeoutMillis>12e4)throw Error("Timeout must be between 5000120000 milliseconds.");this.outputFile=e.credential_source.executable.output_file,this.handler=new o.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){let e;if("1"!==process.env.GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES)throw Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>1)throw Error("Version of executable is not currently supported, maximum supported version is 1.");if(!e.success)throw new o.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new i.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw Error("Executable response is expired.");return e.subjectToken}}r.PluggableAuthClient=a},87092,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ExternalAccountClient=void 0;let n=e.r(1668),i=e.r(984),o=e.r(85338),s=e.r(65006);r.ExternalAccountClient=class{constructor(){throw Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===n.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new o.AwsClient(e):e.credential_source?.executable?new s.PluggableAuthClient(e):new i.IdentityPoolClient(e):null}}},52589,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ExternalAccountAuthorizedUserClient=r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;let n=e.r(5567),i=e.r(15774),o=e.r(65065),s=e.r(88947),a=e.r(1668);r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";class l extends i.OAuthClientAuthHandler{#I;constructor(e){super(e),this.#I=e.tokenRefreshEndpoint}async refreshToken(e,t){let r={...l.RETRY_CONFIG,url:this.#I,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};n.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let e=await this.transporter.request(r),t=e.data;return t.res=e,t}catch(e){if(e instanceof o.GaxiosError&&e.response)throw(0,i.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}}class u extends n.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;const t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new l({tokenRefreshEndpoint:e.token_url??"https://sts.{universeDomain}/v1/oauthtoken".replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,"number"!=typeof e?.eagerRefreshThresholdMillis?this.eagerRefreshThresholdMillis=a.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(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=o.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,i=r.config.data instanceof s.Readable;if(!t&&(401===n||403===n)&&!i&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}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()+1e3*e.expires_in,res:e.res},void 0!==e.refresh_token&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}}r.ExternalAccountAuthorizedUserClient=u},5670,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleAuth=r.GoogleAuthExceptionMessages=void 0;let n=e.r(33405),i=e.r(22734),o=e.r(65065),s=e.r(37876),a=e.r(46786),l=e.r(14747),u=e.r(24715),c=e.r(72020),d=e.r(19820),p=e.r(68791),h=e.r(25922),f=e.r(87155),m=e.r(7534),g=e.r(87092),y=e.r(1668),_=e.r(5567),E=e.r(52589),v=e.r(71850);r.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. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://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.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"},r.GoogleAuth=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#w=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(r.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)return this.getProjectIdAsync();this.getProjectIdAsync().then(t=>e(null,t),e)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===r.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())return this._cachedProjectId=e,e;throw Error(r.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 s.universe("universe-domain"),e||=_.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=_.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,v.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=_.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let r;if("function"==typeof e?t=e:r=e,!t)return this.getApplicationDefaultAsync(r);this.getApplicationDefaultAsync(r).then(e=>t(null,e.credential,e.projectId),t)}async getApplicationDefaultAsync(e={}){let t;if(this.cachedCredential)return await this.#R(this.cachedCredential,null);if((t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e))||(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e)))return t instanceof h.JWT?t.scopes=this.scopes:t instanceof y.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#R(t);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#R(new c.Compute(e));throw Error(r.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async #R(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=s.getGCPResidency()||await s.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||0===t.length)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(e){throw e instanceof Error&&(e.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`),e}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let e=process.env.HOME;e&&(t=l.join(e,".config"))}return(t&&(t=l.join(t,"gcloud","application_default_credentials.json"),i.existsSync(t)||(t=null)),t)?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||0===e.length)throw Error("The file path is invalid.");try{if(e=i.realpathSync(e),!i.lstatSync(e).isFile())throw Error()}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}let r=i.createReadStream(e);return this.fromStream(r,t)}fromImpersonatedJSON(e){if(!e)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==m.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${m.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let n=(this.scopes||e.scopes||this.defaultScopes)??[];return new m.Impersonated({...e,sourceClient:t,targetPrincipal:r,targetScopes:Array.isArray(n)?n:[n]})}fromJSON(e,t={}){let r,n=(0,v.originalOrCamelOptions)(t).get("universe_domain");return e.type===f.USER_REFRESH_ACCOUNT_TYPE?(r=new f.UserRefreshClient(t)).fromJSON(e):e.type===m.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===y.EXTERNAL_ACCOUNT_TYPE?(r=g.ExternalAccountClient.fromJSON({...e,...t})).scopes=this.getAnyScopes():e.type===E.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new E.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,r=new h.JWT(t),this.setGapicJWTValues(r),r.fromJSON(e)),n&&(r.universeDomain=n),r}_cacheClientFromJSON(e,t){let r=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,t={},r){let n={};if("function"==typeof t?r=t:n=t,!r)return this.fromStreamAsync(e,n);this.fromStreamAsync(e,n).then(e=>r(null,e),r)}fromStreamAsync(e,t){return new Promise((r,n)=>{if(!e)throw Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",n).on("data",e=>i.push(e)).on("end",()=>{try{try{let e=JSON.parse(i.join("")),n=this._cacheClientFromJSON(e,t);return r(n)}catch(t){if(!this.keyFilename)throw t;let e=new h.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=e,this.setGapicJWTValues(e),r(e)}}catch(e){return n(e)}})})}fromAPIKey(e,t={}){return new h.JWT({...t,apiKey:e})}_isWindows(){let e=a.platform();return!!e&&!!(e.length>=3)&&"win"===e.substring(0,3).toLowerCase()}async getDefaultServiceProjectId(){return new Promise(e=>{(0,n.exec)("gcloud config config-helper --format json",(t,r)=>{if(!t&&r)try{let t=JSON.parse(r).configuration.properties.core.project;e(t);return}catch(e){}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 e=await this.getClient();if(e&&e.projectId)return e.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==y.EXTERNAL_ACCOUNT_TYPE)return null;let e=await this.getClient();return await e.getProjectId()}async getGCEProjectId(){try{return await s.project("project-id")}catch(e){return null}}getCredentials(e){if(!e)return this.getCredentialsAsync();this.getCredentialsAsync().then(t=>e(null,t),e)}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof m.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof y.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[e,t]=await Promise.all([s.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw Error(r.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#w=this.#w||this.#N();try{return await this.#w}finally{this.#w=null}}async #N(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=l.resolve(this.keyFilename),t=i.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#R(e);return t}{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new d.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){let e=await this.getClient();return(await e.getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,r=await this.getClient(),n=await r.getRequestHeaders(t);return e.headers=o.Gaxios.mergeHeaders(e.headers,n),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,p.getEnv)()}async sign(e,t){let r=await this.getClient(),n=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${n}/v1/projects/-/serviceAccounts/`,r instanceof m.Impersonated)return(await r.sign(e)).signedBlob;let i=(0,u.createCrypto)();if(r instanceof h.JWT&&r.key)return await i.sign(r.key,e);let o=await this.getCredentials();if(!o.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(i,o.client_email,e,t)}async signBlob(e,t,r,n){let i=new URL(n+`${t}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}},88850,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.IAMAuth=void 0,r.IAMAuth=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}},35244,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.DownscopedClient=r.EXPIRATION_TIME_OFFSET=r.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;let n=e.r(65065),i=e.r(88947),o=e.r(5567),s=e.r(91007);r.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,r.EXPIRATION_TIME_OFFSET=3e5;class a extends o.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof o.AuthClient?{}:e),e instanceof o.AuthClient?(this.authClient=e,this.credentialAccessBoundary=t):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),0===this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length)throw Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>r.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${r.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(const e of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(0===e.availablePermissions.length)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){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(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response))}async requestAsync(e,t=!1){let r;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,o=r.config.data instanceof i.Readable;if(!t&&(401===n||403===n)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t=await this.stsCredential.exchangeToken({grantType:"urn:ietf:params:oauth:grant-type:token-exchange",requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:"urn:ietf:params:oauth:token-type:access_token"},void 0,this.credentialAccessBoundary),r=this.authClient.credentials?.expiry_date||null,n=t.expires_in?new Date().getTime()+1e3*t.expires_in:r;return this.cachedDownscopedAccessToken={access_token:t.access_token,expiry_date:n,res:t.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}}r.DownscopedClient=a},1798,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.PassThroughClient=void 0;let n=e.r(5567);class i extends n.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}r.PassThroughClient=i},40259,(e,t,r)=>{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.GoogleAuth=r.auth=r.PassThroughClient=r.ExternalAccountAuthorizedUserClient=r.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=r.ExecutableError=r.PluggableAuthClient=r.DownscopedClient=r.BaseExternalAccountClient=r.ExternalAccountClient=r.IdentityPoolClient=r.AwsRequestSigner=r.AwsClient=r.UserRefreshClient=r.LoginTicket=r.ClientAuthentication=r.OAuth2Client=r.CodeChallengeMethod=r.Impersonated=r.JWT=r.JWTAccess=r.IdTokenClient=r.IAMAuth=r.GCPEnv=r.Compute=r.DEFAULT_UNIVERSE=r.AuthClient=r.gaxios=r.gcpMetadata=void 0;let o=e.r(5670);Object.defineProperty(r,"GoogleAuth",{enumerable:!0,get:function(){return o.GoogleAuth}}),r.gcpMetadata=e.r(37876),r.gaxios=e.r(65065);var s=e.r(5567);Object.defineProperty(r,"AuthClient",{enumerable:!0,get:function(){return s.AuthClient}}),Object.defineProperty(r,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return s.DEFAULT_UNIVERSE}});var a=e.r(72020);Object.defineProperty(r,"Compute",{enumerable:!0,get:function(){return a.Compute}});var l=e.r(68791);Object.defineProperty(r,"GCPEnv",{enumerable:!0,get:function(){return l.GCPEnv}});var u=e.r(88850);Object.defineProperty(r,"IAMAuth",{enumerable:!0,get:function(){return u.IAMAuth}});var c=e.r(19820);Object.defineProperty(r,"IdTokenClient",{enumerable:!0,get:function(){return c.IdTokenClient}});var d=e.r(95479);Object.defineProperty(r,"JWTAccess",{enumerable:!0,get:function(){return d.JWTAccess}});var p=e.r(25922);Object.defineProperty(r,"JWT",{enumerable:!0,get:function(){return p.JWT}});var h=e.r(7534);Object.defineProperty(r,"Impersonated",{enumerable:!0,get:function(){return h.Impersonated}});var f=e.r(43812);Object.defineProperty(r,"CodeChallengeMethod",{enumerable:!0,get:function(){return f.CodeChallengeMethod}}),Object.defineProperty(r,"OAuth2Client",{enumerable:!0,get:function(){return f.OAuth2Client}}),Object.defineProperty(r,"ClientAuthentication",{enumerable:!0,get:function(){return f.ClientAuthentication}});var m=e.r(45219);Object.defineProperty(r,"LoginTicket",{enumerable:!0,get:function(){return m.LoginTicket}});var g=e.r(87155);Object.defineProperty(r,"UserRefreshClient",{enumerable:!0,get:function(){return g.UserRefreshClient}});var y=e.r(85338);Object.defineProperty(r,"AwsClient",{enumerable:!0,get:function(){return y.AwsClient}});var _=e.r(3168);Object.defineProperty(r,"AwsRequestSigner",{enumerable:!0,get:function(){return _.AwsRequestSigner}});var E=e.r(984);Object.defineProperty(r,"IdentityPoolClient",{enumerable:!0,get:function(){return E.IdentityPoolClient}});var v=e.r(87092);Object.defineProperty(r,"ExternalAccountClient",{enumerable:!0,get:function(){return v.ExternalAccountClient}});var T=e.r(1668);Object.defineProperty(r,"BaseExternalAccountClient",{enumerable:!0,get:function(){return T.BaseExternalAccountClient}});var A=e.r(35244);Object.defineProperty(r,"DownscopedClient",{enumerable:!0,get:function(){return A.DownscopedClient}});var S=e.r(65006);Object.defineProperty(r,"PluggableAuthClient",{enumerable:!0,get:function(){return S.PluggableAuthClient}}),Object.defineProperty(r,"ExecutableError",{enumerable:!0,get:function(){return S.ExecutableError}});var b=e.r(52589);Object.defineProperty(r,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return b.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(r,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return b.ExternalAccountAuthorizedUserClient}});var C=e.r(1798);Object.defineProperty(r,"PassThroughClient",{enumerable:!0,get:function(){return C.PassThroughClient}}),i(e.r(12408),r),r.auth=new o.GoogleAuth},24868,(e,t,r)=>{t.exports=e.x("fs/promises",()=>require("fs/promises"))},88646,(e,t,r)=>{t.exports=e.x("node:stream/promises",()=>require("node:stream/promises"))},6461,(e,t,r)=>{t.exports=e.x("zlib",()=>require("zlib"))},2198,(e,t,r)=>{"use strict";let n=["nodebuffer","arraybuffer","fragments"],i="u">typeof Blob;i&&n.push("blob"),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},54875,(e,t,r)=>{"use strict";let{EMPTY_BUFFER:n}=e.r(2198),i=Buffer[Symbol.species];function o(e,t,r,n,i){for(let o=0;o{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,r,n,i,s){s<48?o(t,r,n,i,s):e.mask(t,r,n,i,s)},t.exports.unmask=function(t,r){t.length<32?s(t,r):e.unmask(t,r)}}catch(e){}},71630,(e,t,r)=>{"use strict";let n=Symbol("kDone"),i=Symbol("kRun");t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}},18768,(e,t,r)=>{"use strict";let n,i=e.r(6461),o=e.r(54875),s=e.r(71630),{kStatusCode:a}=e.r(2198),l=Buffer[Symbol.species],u=Buffer.from([0,0,255,255]),c=Symbol("permessage-deflate"),d=Symbol("total-length"),p=Symbol("callback"),h=Symbol("buffers"),f=Symbol("error");function m(e){this[h].push(e),this[d]+=e.length}function g(e){(this[d]+=e.length,this[c]._maxPayload<1||this[d]<=this[c]._maxPayload)?this[h].push(e):(this[f]=RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][a]=1009,this.removeListener("data",g),this.reset())}function y(e){(this[c]._inflate=null,this[f])?this[p](this[f]):(e[a]=1007,this[p](e))}t.exports=class{constructor(e,t,r){this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,n||(n=new s(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}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:null==this._options.clientMaxWindowBits&&(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[p];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||!!e.client_max_window_bits));if(!r)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:(!0===r.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==r)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=r})}),e}decompress(e,t,r){n.add(n=>{this._decompress(e,t,(e,t)=>{n(),r(e,t)})})}compress(e,t,r){n.add(n=>{this._compress(e,t,(e,t)=>{n(),r(e,t)})})}_decompress(e,t,r){let n=this._isServer?"client":"server";if(!this._inflate){let e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[d]=0,this._inflate[h]=[],this._inflate.on("error",y),this._inflate.on("data",g)}this._inflate[p]=r,this._inflate.write(e),t&&this._inflate.write(u),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,r(e);return}let i=o.concat(this._inflate[h],this._inflate[d]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[d]=0,this._inflate[h]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(e,t,r){let n=this._isServer?"server":"client";if(!this._deflate){let e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[d]=0,this._deflate[h]=[],this._deflate.on("data",m)}this._deflate[p]=r,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=o.concat(this._deflate[h],this._deflate[d]);t&&(e=new l(e.buffer,e.byteOffset,e.length-4)),this._deflate[p]=null,this._deflate[d]=0,this._deflate[h]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},69650,(e,t,r)=>{"use strict";let{isUtf8:n}=e.r(874),{hasBlob:i}=e.r(2198);function o(e){let t=e.length,r=0;for(;r=t||(192&e[r+1])!=128||(192&e[r+2])!=128||224===e[r]&&(224&e[r+1])==128||237===e[r]&&(224&e[r+1])==160)return!1;r+=3}else{if((248&e[r])!=240||r+3>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||(192&e[r+3])!=128||240===e[r]&&(240&e[r+1])==128||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:o,tokenChars:[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]},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch(e){}},95371,(e,t,r)=>{"use strict";let{Writable:n}=e.r(88947),i=e.r(18768),{BINARY_TYPES:o,EMPTY_BUFFER:s,kStatusCode:a,kWebSocket:l}=e.r(2198),{concat:u,toArrayBuffer:c,unmask:d}=e.r(54875),{isValidStatusCode:p,isValidUTF8:h}=e.r(69650),f=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||o[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();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=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let r=(64&t[0])==64;if(r&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=r}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2: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 t=this.consume(8),r=t.readUInt32BE(0);r>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*r+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=s;if(this._payloadLength){if(this._bufferedBytes7)return void this.controlMessage(t,e);if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?u(r,t):"arraybuffer"===this._binaryType?c(u(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)}))}else{let n=u(r,t);if(!this._skipUTF8Validation&&!h(n))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,s),this.end();else{let r=e.readUInt16BE(0);if(!p(r))return void t(this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!h(n))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}))}createError(e,t,r,n,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[a]=n,o}}},53862,(e,t,r)=>{"use strict";let n,{Duplex:i}=e.r(88947),{randomFillSync:o}=e.r(54799),s=e.r(18768),{EMPTY_BUFFER:a,kWebSocket:l,NOOP:u}=e.r(2198),{isBlob:c,isValidStatusCode:d}=e.r(69650),{mask:p,toBuffer:h}=e.r(54875),f=Symbol("kByteLength"),m=Buffer.alloc(4),g=8192;class y{constructor(e,t,r){this._extensions=t||{},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=0,this.onerror=u,this[l]=void 0}static frame(e,t){let r,i,s=!1,a=2,l=!1;t.mask&&(r=t.maskBuffer||m,t.generateMask?t.generateMask(r):(8192===g&&(void 0===n&&(n=Buffer.alloc(8192)),o(n,0,8192),g=0),r[0]=n[g++],r[1]=n[g++],r[2]=n[g++],r[3]=n[g++]),l=(r[0]|r[1]|r[2]|r[3])==0,a=6),"string"==typeof e?i=(!t.mask||l)&&void 0!==t[f]?t[f]:(e=Buffer.from(e)).length:(i=e.length,s=t.mask&&t.readOnly&&!l);let u=i;i>=65536?(a+=8,u=127):i>125&&(a+=2,u=126);let c=Buffer.allocUnsafe(s?i+a:a);return(c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=u,126===u?c.writeUInt16BE(i,2):127===u&&(c[2]=c[3]=0,c.writeUIntBE(i,4,6)),t.mask)?(c[1]|=128,c[a-4]=r[0],c[a-3]=r[1],c[a-2]=r[2],c[a-1]=r[3],l)?[c,e]:s?(p(e,r,c,a,i),[c]):(p(e,r,e,0,i),[c,e]):[c,e]}close(e,t,r,n){let i;if(void 0===e)i=a;else if("number"==typeof e&&d(e))if(void 0!==t&&t.length){let r=Buffer.byteLength(t);if(r>123)throw RangeError("The message must not be greater than 123 bytes");(i=Buffer.allocUnsafe(2+r)).writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0);else throw TypeError("First argument must be a valid error code number");let o={[f]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(y.frame(i,o),n)}ping(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):c(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[f]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}pong(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):c(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[f]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}send(e,t,r){let n,i,o=this._extensions[s.extensionName],a=t.binary?2:1,l=t.compress;"string"==typeof e?(n=Buffer.byteLength(e),i=!1):c(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=n>=o._threshold),this._compress=l):(l=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:l};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,t,r,n){this._bufferedBytes+=r[f],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(_,this,e,n);return}this._bufferedBytes-=r[f];let i=h(e);t?this.dispatch(i,t,r,n):(this._state=0,this.sendFrame(y.frame(i,r),n),this.dequeue())}).catch(e=>{process.nextTick(E,this,e,n)})}dispatch(e,t,r,n){if(!t)return void this.sendFrame(y.frame(e,r),n);let i=this._extensions[s.extensionName];this._bufferedBytes+=r[f],this._state=1,i.compress(e,r.fin,(e,t)=>{this._socket.destroyed?_(this,Error("The socket was closed while data was being compressed"),n):(this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),n),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function _(e,t,r){"function"==typeof r&&r(t);for(let r=0;r{"use strict";let{kForOnEventAttribute:n,kListener:i}=e.r(2198),o=Symbol("kCode"),s=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),u=Symbol("kReason"),c=Symbol("kTarget"),d=Symbol("kType"),p=Symbol("kWasClean");class h{constructor(e){this[c]=null,this[d]=e}get target(){return this[c]}get type(){return this[d]}}Object.defineProperty(h.prototype,"target",{enumerable:!0}),Object.defineProperty(h.prototype,"type",{enumerable:!0});class f extends h{constructor(e,t={}){super(e),this[o]=void 0===t.code?0:t.code,this[u]=void 0===t.reason?"":t.reason,this[p]=void 0!==t.wasClean&&t.wasClean}get code(){return this[o]}get reason(){return this[u]}get wasClean(){return this[p]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class m extends h{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[l]}}Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});class g extends h{constructor(e,t={}){super(e),this[s]=void 0===t.data?null:t.data}get data(){return this[s]}}function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}Object.defineProperty(g.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:f,ErrorEvent:m,Event:h,EventTarget:{addEventListener(e,t,r={}){let o;for(let o of this.listeners(e))if(!r[n]&&o[i]===t&&!o[n])return;if("message"===e)o=function(e,r){let n=new g("message",{data:r?e:e.toString()});n[c]=this,y(t,this,n)};else if("close"===e)o=function(e,r){let n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[c]=this,y(t,this,n)};else if("error"===e)o=function(e){let r=new m("error",{error:e,message:e.message});r[c]=this,y(t,this,r)};else{if("open"!==e)return;o=function(){let e=new h("open");e[c]=this,y(t,this,e)}}o[n]=!!r[n],o[i]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[i]===t&&!r[n]){this.removeListener(e,r);break}}},MessageEvent:g}},38877,(e,t,r)=>{"use strict";let{tokenChars:n}=e.r(69650);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,r,o=Object.create(null),s=Object.create(null),a=!1,l=!1,u=!1,c=-1,d=-1,p=-1,h=0;for(;h{"use strict";let n=e.r(27699),i=e.r(24836),o=e.r(21517),s=e.r(4446),a=e.r(55004),{randomBytes:l,createHash:u}=e.r(54799),{Duplex:c,Readable:d}=e.r(88947),{URL:p}=e.r(92509),h=e.r(18768),f=e.r(95371),m=e.r(53862),{isBlob:g}=e.r(69650),{BINARY_TYPES:y,CLOSE_TIMEOUT:_,EMPTY_BUFFER:E,GUID:v,kForOnEventAttribute:T,kListener:A,kStatusCode:S,kWebSocket:b,NOOP:C}=e.r(2198),{EventTarget:{addEventListener:O,removeEventListener:I}}=e.r(63812),{format:w,parse:R}=e.r(38877),{toBuffer:N}=e.r(54875),k=Symbol("kAborted"),P=[8,13],x=["CONNECTING","OPEN","CLOSING","CLOSED"],U=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class D extends n{constructor(e,t,r){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=E,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=D.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),function e(t,r,n,s){let a,c,d,f,m={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:P[1],maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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=m.autoPong,t._closeTimeout=m.closeTimeout,!P.includes(m.protocolVersion))throw RangeError(`Unsupported protocol version: ${m.protocolVersion} (supported versions: ${P.join(", ")})`);if(r instanceof p)a=r;else try{a=new p(r)}catch(e){throw SyntaxError(`Invalid URL: ${r}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),t._url=a.href;let g="wss:"===a.protocol,y="ws+unix:"===a.protocol;if("ws:"===a.protocol||g||y?y&&!a.pathname?c="The URL's pathname is empty":a.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',c){let e=SyntaxError(c);if(0!==t._redirects)return void M(t,e);throw e}let E=g?443:80,T=l(16).toString("base64"),A=g?i.request:o.request,S=new Set;if(m.createConnection=m.createConnection||(g?j:L),m.defaultPort=m.defaultPort||E,m.port=a.port||E,m.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,m.headers={...m.headers,"Sec-WebSocket-Version":m.protocolVersion,"Sec-WebSocket-Key":T,Connection:"Upgrade",Upgrade:"websocket"},m.path=a.pathname+a.search,m.timeout=m.handshakeTimeout,m.perMessageDeflate&&(d=new h(!0!==m.perMessageDeflate?m.perMessageDeflate:{},!1,m.maxPayload),m.headers["Sec-WebSocket-Extensions"]=w({[h.extensionName]:d.offer()})),n.length){for(let e of n){if("string"!=typeof e||!U.test(e)||S.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");S.add(e)}m.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(m.origin&&(m.protocolVersion<13?m.headers["Sec-WebSocket-Origin"]=m.origin:m.headers.Origin=m.origin),(a.username||a.password)&&(m.auth=`${a.username}:${a.password}`),y){let e=m.path.split(":");m.socketPath=e[0],m.path=e[1]}if(m.followRedirects){if(0===t._redirects){t._originalIpc=y,t._originalSecure=g,t._originalHostOrSocketPath=y?m.socketPath:a.host;let e=s&&s.headers;if(s={...s,headers:{}},e)for(let[t,r]of Object.entries(e))s.headers[t.toLowerCase()]=r}else if(0===t.listenerCount("redirect")){let e=y?!!t._originalIpc&&m.socketPath===t._originalHostOrSocketPath:!t._originalIpc&&a.host===t._originalHostOrSocketPath;e&&(!t._originalSecure||g)||(delete m.headers.authorization,delete m.headers.cookie,e||delete m.headers.host,m.auth=void 0)}m.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(m.auth).toString("base64")),f=t._req=A(m),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=A(m);m.timeout&&f.on("timeout",()=>{G(t,f,"Opening handshake has timed out")}),f.on("error",e=>{null===f||f[k]||(f=t._req=null,M(t,e))}),f.on("response",i=>{let o=i.headers.location,a=i.statusCode;if(o&&m.followRedirects&&a>=300&&a<400){let i;if(++t._redirects>m.maxRedirects)return void G(t,f,"Maximum redirects exceeded");f.abort();try{i=new p(o,r)}catch(e){M(t,SyntaxError(`Invalid URL: ${o}`));return}e(t,i,n,s)}else t.emit("unexpected-response",f,i)||G(t,f,`Unexpected server response: ${i.statusCode}`)}),f.on("upgrade",(e,r,n)=>{let i;if(t.emit("upgrade",e),t.readyState!==D.CONNECTING)return;f=t._req=null;let o=e.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void G(t,r,"Invalid Upgrade header");let s=u("sha1").update(T+v).digest("base64");if(e.headers["sec-websocket-accept"]!==s)return void G(t,r,"Invalid Sec-WebSocket-Accept header");let a=e.headers["sec-websocket-protocol"];if(void 0!==a?S.size?S.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":S.size&&(i="Server sent no subprotocol"),i)return void G(t,r,i);a&&(t._protocol=a);let l=e.headers["sec-websocket-extensions"];if(void 0!==l){let e;if(!d)return void G(t,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{e=R(l)}catch(e){G(t,r,"Invalid Sec-WebSocket-Extensions header");return}let n=Object.keys(e);if(1!==n.length||n[0]!==h.extensionName)return void G(t,r,"Server indicated an extension that was not requested");try{d.accept(e[h.extensionName])}catch(e){G(t,r,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[h.extensionName]=d}t.setSocket(r,n,{allowSynchronousEvents:m.allowSynchronousEvents,generateMask:m.generateMask,maxPayload:m.maxPayload,skipUTF8Validation:m.skipUTF8Validation})}),m.finishRequest?m.finishRequest(f,t):f.end()}(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.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,t,r){let n=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new m(e,this._extensions,r.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[b]=this,i[b]=this,e[b]=this,n.on("conclude",q),n.on("drain",H),n.on("error",B),n.on("message",$),n.on("ping",J),n.on("pong",W),i.onerror=Y,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",X),e.on("data",Q),e.on("end",Z),e.on("error",ee),this._readyState=D.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[h.extensionName]&&this._extensions[h.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING)return void G(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===D.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=D.CLOSING,this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),z(this)}}pause(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?F(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.ping(e||E,t,r))}pong(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?F(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.pong(e||E,t,r))}resume(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)return void F(this,e,r);let n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[h.extensionName]||(n.compress=!1),this._sender.send(e||E,n,r)}terminate(){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING)return void G(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=D.CLOSING,this._socket.destroy())}}}function M(e,t){e._readyState=D.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function L(e){return e.path=e.socketPath,s.connect(e)}function j(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=s.isIP(e.host)?"":e.host),a.connect(e)}function G(e,t,r){e._readyState=D.CLOSING;let n=Error(r);Error.captureStackTrace(n,G),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(M,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function F(e,t,r){if(t){let r=g(t)?t.size:N(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${x[e.readyState]})`);process.nextTick(r,t)}}function q(e,t){let r=this[b];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[b]&&(r._socket.removeListener("data",Q),process.nextTick(K,r._socket),1005===e?r.close():r.close(e,t))}function H(){let e=this[b];e.isPaused||e._socket.resume()}function B(e){let t=this[b];void 0!==t._socket[b]&&(t._socket.removeListener("data",Q),process.nextTick(K,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function V(){this[b].emitClose()}function $(e,t){this[b].emit("message",e,t)}function J(e){let t=this[b];t._autoPong&&t.pong(e,!this._isServer,C),t.emit("ping",e)}function W(e){this[b].emit("pong",e)}function K(e){e.resume()}function Y(e){let t=this[b];t.readyState!==D.CLOSED&&(t.readyState===D.OPEN&&(t._readyState=D.CLOSING,z(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function z(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function X(){let e=this[b];if(this.removeListener("close",X),this.removeListener("data",Q),this.removeListener("end",Z),e._readyState=D.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&0!==this._readableState.length){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[b]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",V),e._receiver.on("finish",V))}function Q(e){this[b]._receiver.write(e)||this.pause()}function Z(){let e=this[b];e._readyState=D.CLOSING,e._receiver.end(),this.end()}function ee(){let e=this[b];this.removeListener("error",ee),this.on("error",C),e&&(e._readyState=D.CLOSING,this.destroy())}Object.defineProperty(D,"CONNECTING",{enumerable:!0,value:x.indexOf("CONNECTING")}),Object.defineProperty(D.prototype,"CONNECTING",{enumerable:!0,value:x.indexOf("CONNECTING")}),Object.defineProperty(D,"OPEN",{enumerable:!0,value:x.indexOf("OPEN")}),Object.defineProperty(D.prototype,"OPEN",{enumerable:!0,value:x.indexOf("OPEN")}),Object.defineProperty(D,"CLOSING",{enumerable:!0,value:x.indexOf("CLOSING")}),Object.defineProperty(D.prototype,"CLOSING",{enumerable:!0,value:x.indexOf("CLOSING")}),Object.defineProperty(D,"CLOSED",{enumerable:!0,value:x.indexOf("CLOSED")}),Object.defineProperty(D.prototype,"CLOSED",{enumerable:!0,value:x.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(D.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[T])return t[A];return null},set(t){for(let t of this.listeners(e))if(t[T]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[T]:!0})}})}),D.prototype.addEventListener=O,D.prototype.removeEventListener=I,t.exports=D},51710,(e,t,r)=>{"use strict";e.r(44875);let{Duplex:n}=e.r(88947);function i(e){e.emit("close")}function o(){!this.destroyed&&this._writableState.finished&&this.destroy()}function s(e){this.removeListener("error",s),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let r=!0,a=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){let n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(i,a);return}let o=!1;e.once("error",function(e){o=!0,n(e)}),e.once("close",function(){o||n(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,r,n)}):e.send(t,n)},a.on("end",o),a.on("error",s),a}},99595,(e,t,r)=>{"use strict";let{tokenChars:n}=e.r(69650);t.exports={parse:function(e){let t=new Set,r=-1,i=-1,o=0;for(;o{"use strict";let n=e.r(27699),i=e.r(21517),{Duplex:o}=e.r(88947),{createHash:s}=e.r(54799),a=e.r(38877),l=e.r(18768),u=e.r(99595),c=e.r(44875),{CLOSE_TIMEOUT:d,GUID:p,kWebSocket:h}=e.r(2198),f=/^[+/0-9A-Za-z]{22}==$/;function m(e){e._state=2,e.emit("close")}function g(){this.destroy()}function y(e,t,r,n){r=r||i.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r `+Object.keys(n).map(e=>`${e}: ${n[e]}`).join("\r\n")+"\r\n\r\n"+r)}function _(e,t,r,n,i,o){if(e.listenerCount("wsClientError")){let n=Error(i);Error.captureStackTrace(n,_),e.emit("wsClientError",n,r,t)}else y(r,n,i,o)}t.exports=class extends n{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let r=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(m,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",g);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void _(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void _(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!f.test(i))return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==s&&8!==s)return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void y(t,400);let c=e.headers["sec-websocket-protocol"],d=new Set;if(void 0!==c)try{d=u.parse(c)}catch(r){_(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&void 0!==p){let r=new l(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=a.parse(p);e[l.extensionName]&&(r.accept(e[l.extensionName]),h[l.extensionName]=r)}catch(r){_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let o={origin:e.headers[`${8===s?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,s,a,l)=>{if(!o)return y(t,s||401,a,l);this.completeUpgrade(h,i,d,e,t,r,n)});if(!this.options.verifyClient(o))return y(t,401)}this.completeUpgrade(h,i,d,e,t,r,n)}completeUpgrade(e,t,r,n,i,o,u){if(!i.readable||!i.writable)return i.destroy();if(i[h])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return y(i,503);let c=s("sha1").update(t+p).digest("base64"),d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),f._protocol=e)}if(e[l.extensionName]){let t=e[l.extensionName].params,r=a.format({[l.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${r}`),f._extensions=e}this.emit("headers",d,n),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",g),f.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,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(m,this)})),u(f,n)}}},94666,e=>{"use strict";let t,r,n,i,o;var s,a,l,u,c,d,p,h,f,m,g,y,_,E,v,T,A,S,b,C,O,I,w,R,N,k,P,x,U,D,M,L,j,G,F,q,H,B,V,$,J,W,K,Y,z,X,Q,Z,ee,et,er,en,ei,eo,es,ea,el,eu,ec,ed,ep,eh,ef,em,eg,ey,e_,eE,ev,eT,eA,eS,eb,eC,eO,eI,ew,eR,eN,ek,eP,ex,eU,eD,eM,eL,ej,eG,eF,eq,eH,eB,eV,e$,eJ,eW,eK,eY,ez,eX,eQ,eZ,e0,e1,e2,e4,e6,e8,e5,e3,e7,e9,te,tt,tr,tn,ti,to,ts,ta=e.i(53577),tl=e.i(40259),tu=e.i(22734),tc=e.i(24868),td=e.i(81111),tp=e.i(88646);e.i(51710),e.i(95371),e.i(53862);var th=e.i(44875);e.i(88430),th.default;var tf=e.i(14747);class tm{}function tg(e,t){return e.replace(/\{([^}]+)\}/g,(e,r)=>{if(Object.prototype.hasOwnProperty.call(t,r)){let e=t[r];return null!=e?String(e):""}throw Error(`Key '${r}' not found in valueMap.`)})}function ty(e,t,r){for(let n=0;n({}));else throw Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[o])){let i=e[o];if(Array.isArray(r))for(let e=0;et_(e,t.slice(n+1),r))}}e=e[i]}return e}catch(e){if(e instanceof TypeError)return r;throw e}}function tE(e){if("string"!=typeof e)throw Error("fromImageBytes must be a string");return e}function tv(e){var t;let r,n,i,o,s={},a=t_(e,["name"]);null!=a&&ty(s,["name"],a);let l=t_(e,["metadata"]);null!=l&&ty(s,["metadata"],l);let u=t_(e,["done"]);null!=u&&ty(s,["done"],u);let c=t_(e,["error"]);null!=c&&ty(s,["error"],c);let d=t_(e,["response"]);return null!=d&&ty(s,["response"],(r={},null!=(n=t_(t=d,["sdkHttpResponse"]))&&ty(r,["sdkHttpResponse"],n),null!=(i=t_(t,["parent"]))&&ty(r,["parent"],i),null!=(o=t_(t,["documentName"]))&&ty(r,["documentName"],o),r)),s}(s=ed||(ed={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",s.OUTCOME_OK="OUTCOME_OK",s.OUTCOME_FAILED="OUTCOME_FAILED",s.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(a=ep||(ep={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",a.PYTHON="PYTHON",(l=eh||(eh={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",l.SILENT="SILENT",l.WHEN_IDLE="WHEN_IDLE",l.INTERRUPT="INTERRUPT",(u=ef||(ef={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",u.STRING="STRING",u.NUMBER="NUMBER",u.INTEGER="INTEGER",u.BOOLEAN="BOOLEAN",u.ARRAY="ARRAY",u.OBJECT="OBJECT",u.NULL="NULL",(c=em||(em={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",c.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",c.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",c.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",c.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",c.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",c.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(d=eg||(eg={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",d.SIMPLE_SEARCH="SIMPLE_SEARCH",d.ELASTIC_SEARCH="ELASTIC_SEARCH",(p=ey||(ey={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",p.NO_AUTH="NO_AUTH",p.API_KEY_AUTH="API_KEY_AUTH",p.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",p.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",p.OAUTH="OAUTH",p.OIDC_AUTH="OIDC_AUTH",(h=e_||(e_={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",h.HTTP_IN_QUERY="HTTP_IN_QUERY",h.HTTP_IN_HEADER="HTTP_IN_HEADER",h.HTTP_IN_PATH="HTTP_IN_PATH",h.HTTP_IN_BODY="HTTP_IN_BODY",h.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(f=eE||(eE={})).UNSPECIFIED="UNSPECIFIED",f.BLOCKING="BLOCKING",f.NON_BLOCKING="NON_BLOCKING",(m=ev||(ev={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",m.MODE_DYNAMIC="MODE_DYNAMIC",(g=eT||(eT={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",g.AUTO="AUTO",g.ANY="ANY",g.NONE="NONE",g.VALIDATED="VALIDATED",(y=eA||(eA={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",y.LOW="LOW",y.MEDIUM="MEDIUM",y.HIGH="HIGH",y.MINIMAL="MINIMAL",(_=eS||(eS={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",_.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",_.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",_.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",_.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",_.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",_.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",_.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",_.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",_.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",_.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(E=eb||(eb={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",E.SEVERITY="SEVERITY",E.PROBABILITY="PROBABILITY",(v=eC||(eC={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",v.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",v.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",v.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",v.BLOCK_NONE="BLOCK_NONE",v.OFF="OFF",(T=eO||(eO={})).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",(A=eI||(eI={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",A.NEGLIGIBLE="NEGLIGIBLE",A.LOW="LOW",A.MEDIUM="MEDIUM",A.HIGH="HIGH",(S=ew||(ew={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",S.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",S.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",S.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",S.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(b=eR||(eR={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",b.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",b.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",b.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",b.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(C=eN||(eN={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",C.SAFETY="SAFETY",C.OTHER="OTHER",C.BLOCKLIST="BLOCKLIST",C.PROHIBITED_CONTENT="PROHIBITED_CONTENT",C.IMAGE_SAFETY="IMAGE_SAFETY",C.MODEL_ARMOR="MODEL_ARMOR",C.JAILBREAK="JAILBREAK",(O=ek||(ek={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",O.ON_DEMAND="ON_DEMAND",O.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(I=eP||(eP={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",I.TEXT="TEXT",I.IMAGE="IMAGE",I.AUDIO="AUDIO",(w=ex||(ex={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",w.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",w.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",w.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(R=eU||(eU={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",R.TUNING_MODE_FULL="TUNING_MODE_FULL",R.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(N=eD||(eD={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",N.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",N.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",N.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",N.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",N.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",N.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(k=eM||(eM={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",k.JOB_STATE_QUEUED="JOB_STATE_QUEUED",k.JOB_STATE_PENDING="JOB_STATE_PENDING",k.JOB_STATE_RUNNING="JOB_STATE_RUNNING",k.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",k.JOB_STATE_FAILED="JOB_STATE_FAILED",k.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",k.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",k.JOB_STATE_PAUSED="JOB_STATE_PAUSED",k.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",k.JOB_STATE_UPDATING="JOB_STATE_UPDATING",k.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(P=eL||(eL={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",P.TUNING_TASK_I2V="TUNING_TASK_I2V",P.TUNING_TASK_T2V="TUNING_TASK_T2V",P.TUNING_TASK_R2V="TUNING_TASK_R2V",(x=ej||(ej={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",x.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",x.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",x.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",x.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(eG||(eG={})).COLLECTION="COLLECTION",(U=eF||(eF={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",U.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",U.BALANCED="BALANCED",U.PRIORITIZE_COST="PRIORITIZE_COST",(D=eq||(eq={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",D.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(M=eH||(eH={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",M.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",M.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(L=eB||(eB={})).PREDICT="PREDICT",L.EMBED_CONTENT="EMBED_CONTENT",(j=eV||(eV={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",j.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",j.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",j.BLOCK_NONE="BLOCK_NONE",(G=e$||(e$={})).DONT_ALLOW="DONT_ALLOW",G.ALLOW_ADULT="ALLOW_ADULT",G.ALLOW_ALL="ALLOW_ALL",(F=eJ||(eJ={})).auto="auto",F.en="en",F.ja="ja",F.ko="ko",F.hi="hi",F.zh="zh",F.pt="pt",F.es="es",(q=eW||(eW={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",q.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",q.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",q.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",q.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(H=eK||(eK={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",H.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",H.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",H.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(B=eY||(eY={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",B.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",B.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",B.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(V=ez||(ez={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",V.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",V.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",V.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",V.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",V.EDIT_MODE_STYLE="EDIT_MODE_STYLE",V.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",V.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",($=eX||(eX={})).FOREGROUND="FOREGROUND",$.BACKGROUND="BACKGROUND",$.PROMPT="PROMPT",$.SEMANTIC="SEMANTIC",$.INTERACTIVE="INTERACTIVE",(J=eQ||(eQ={})).ASSET="ASSET",J.STYLE="STYLE",(W=eZ||(eZ={})).INSERT="INSERT",W.REMOVE="REMOVE",W.REMOVE_STATIC="REMOVE_STATIC",W.OUTPAINT="OUTPAINT",(K=e0||(e0={})).OPTIMIZED="OPTIMIZED",K.LOSSLESS="LOSSLESS",(Y=e1||(e1={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",Y.PREFERENCE_TUNING="PREFERENCE_TUNING",Y.DISTILLATION="DISTILLATION",(z=e2||(e2={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",z.STATE_PENDING="STATE_PENDING",z.STATE_ACTIVE="STATE_ACTIVE",z.STATE_FAILED="STATE_FAILED",(X=e4||(e4={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",X.PROCESSING="PROCESSING",X.ACTIVE="ACTIVE",X.FAILED="FAILED",(Q=e6||(e6={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",Q.UPLOADED="UPLOADED",Q.GENERATED="GENERATED",Q.REGISTERED="REGISTERED",(Z=e8||(e8={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",Z.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",Z.RESPONSE_REJECTED="RESPONSE_REJECTED",Z.NEED_MORE_INPUT="NEED_MORE_INPUT",(ee=e5||(e5={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",ee.TEXT="TEXT",ee.IMAGE="IMAGE",ee.VIDEO="VIDEO",ee.AUDIO="AUDIO",ee.DOCUMENT="DOCUMENT",(et=e3||(e3={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",et.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",et.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(er=e7||(e7={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",er.ACTIVITY_START="ACTIVITY_START",er.ACTIVITY_END="ACTIVITY_END",(en=e9||(e9={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",en.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",en.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(ei=te||(te={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",ei.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",ei.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(eo=tt||(tt={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",eo.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",eo.NO_INTERRUPTION="NO_INTERRUPTION",(es=tr||(tr={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",es.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",es.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",(ea=tn||(tn={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",ea.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",ea.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",ea.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",ea.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",ea.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",ea.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",ea.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",ea.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",ea.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",ea.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",ea.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",ea.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(el=ti||(ti={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",el.QUALITY="QUALITY",el.DIVERSITY="DIVERSITY",el.VOCALIZATION="VOCALIZATION",(eu=to||(to={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",eu.PLAY="PLAY",eu.PAUSE="PAUSE",eu.STOP="STOP",eu.RESET_CONTEXT="RESET_CONTEXT";class tT{constructor(e){const t={};for(const r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class tA{get text(){var e,t,r,n,i,o,s,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let l="",u=!1,c=[];for(let e of null!=(a=null==(s=null==(o=null==(i=this.candidates)?void 0:i[0])?void 0:o.content)?void 0:s.parts)?a:[]){for(let[t,r]of Object.entries(e))"text"!==t&&"thought"!==t&&"thoughtSignature"!==t&&(null!==r||void 0!==r)&&c.push(t);if("string"==typeof e.text){if("boolean"==typeof e.thought&&e.thought)continue;u=!0,l+=e.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,t,r,n,i,o,s,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let l="",u=[];for(let e of null!=(a=null==(s=null==(o=null==(i=this.candidates)?void 0:i[0])?void 0:o.content)?void 0:s.parts)?a:[]){for(let[t,r]of Object.entries(e))"inlineData"!==t&&(null!==r||void 0!==r)&&u.push(t);e.inlineData&&"string"==typeof e.inlineData.data&&(l+=atob(e.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,t,r,n,i,o,s,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let l=null==(a=null==(s=null==(o=null==(i=this.candidates)?void 0:i[0])?void 0:o.content)?void 0:s.parts)?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);if((null==l?void 0:l.length)!==0)return l}get executableCode(){var e,t,r,n,i,o,s,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let u=null==(a=null==(s=null==(o=null==(i=this.candidates)?void 0:i[0])?void 0:o.content)?void 0:s.parts)?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.code}get codeExecutionResult(){var e,t,r,n,i,o,s,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let u=null==(a=null==(s=null==(o=null==(i=this.candidates)?void 0:i[0])?void 0:o.content)?void 0:s.parts)?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.output}}class tS{}class tb{}class tC{}class tO{}class tI{}class tw{}class tR{}class tN{}class tk{}class tP{}class tx{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r,n=new tx;if(t){let t,n,i,o,s,a;t={},null!=(n=t_(e,["name"]))&&ty(t,["name"],n),null!=(i=t_(e,["metadata"]))&&ty(t,["metadata"],i),null!=(o=t_(e,["done"]))&&ty(t,["done"],o),null!=(s=t_(e,["error"]))&&ty(t,["error"],s),null!=(a=t_(e,["response"]))&&ty(t,["response"],function(e){let t={},r=t_(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a;return r={},null!=(n=t_(e,["_self"]))&&ty(r,["video"],(i={},null!=(o=t_(t=n,["gcsUri"]))&&ty(i,["uri"],o),null!=(s=t_(t,["bytesBase64Encoded"]))&&ty(i,["videoBytes"],tE(s)),null!=(a=t_(t,["mimeType"]))&&ty(i,["mimeType"],a),i)),r})),ty(t,["generatedVideos"],e)}let n=t_(e,["raiMediaFilteredCount"]);null!=n&&ty(t,["raiMediaFilteredCount"],n);let i=t_(e,["raiMediaFilteredReasons"]);return null!=i&&ty(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}else{let t,n,i,o,s,a;t={},null!=(n=t_(e,["name"]))&&ty(t,["name"],n),null!=(i=t_(e,["metadata"]))&&ty(t,["metadata"],i),null!=(o=t_(e,["done"]))&&ty(t,["done"],o),null!=(s=t_(e,["error"]))&&ty(t,["error"],s),null!=(a=t_(e,["response","generateVideoResponse"]))&&ty(t,["response"],function(e){let t={},r=t_(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a;return r={},null!=(n=t_(e,["video"]))&&ty(r,["video"],(i={},null!=(o=t_(t=n,["uri"]))&&ty(i,["uri"],o),null!=(s=t_(t,["encodedVideo"]))&&ty(i,["videoBytes"],tE(s)),null!=(a=t_(t,["encoding"]))&&ty(i,["mimeType"],a),i)),r})),ty(t,["generatedVideos"],e)}let n=t_(e,["raiMediaFilteredCount"]);null!=n&&ty(t,["raiMediaFilteredCount"],n);let i=t_(e,["raiMediaFilteredReasons"]);return null!=i&&ty(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}return Object.assign(n,r),n}}class tU{}class tD{}class tM{}class tL{}class tj{}class tG{}class tF{}class tq{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){var r;let n,i,o,s,a,l,u,c,d,p,h=new tq;return Object.assign(h,(a={},null!=(l=t_(e,["name"]))&&ty(a,["name"],l),null!=(u=t_(e,["metadata"]))&&ty(a,["metadata"],u),null!=(c=t_(e,["done"]))&&ty(a,["done"],c),null!=(d=t_(e,["error"]))&&ty(a,["error"],d),null!=(p=t_(e,["response"]))&&ty(a,["response"],(n={},null!=(i=t_(r=p,["sdkHttpResponse"]))&&ty(n,["sdkHttpResponse"],i),null!=(o=t_(r,["parent"]))&&ty(n,["parent"],o),null!=(s=t_(r,["documentName"]))&&ty(n,["documentName"],s),n)),a)),h}}class tH{}class tB{}class tV{}class t${}class tJ{}class tW{get text(){var e,t,r;let n="",i=!1,o=[];for(let s of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(s))"text"!==e&&"thought"!==e&&null!==t&&o.push(e);if("string"==typeof s.text){if("boolean"==typeof s.thought&&s.thought)continue;i=!0,n+=s.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.`),i?n:void 0}get data(){var e,t,r;let n="",i=[];for(let o of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(o))"inlineData"!==e&&null!==t&&i.push(e);o.inlineData&&"string"==typeof o.inlineData.data&&(n+=atob(o.inlineData.data))}return i.length>0&&console.warn(`there are non-data parts ${i} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}}class tK{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class tY{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r=new tY;return Object.assign(r,tv(e)),r}}function tz(e,t){if(!t||"string"!=typeof t)throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else{if(!(t.indexOf("/")>=0))return`publishers/google/models/${t}`;let e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function tX(e,t){let r=tz(e,t);return r?r.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${r}`:r.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${r}`:r:""}function tQ(e){return Array.isArray(e)?e.map(e=>tZ(e)):[tZ(e)]}function tZ(e){if("object"==typeof e&&null!==e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function t0(e){let t=tZ(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function t1(e){let t=tZ(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function t2(e){if(null==e)throw Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function t4(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>t2(e)):[t2(e)]}function t6(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function t8(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function t5(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function t3(e){if(null==e)throw Error("ContentUnion is required");return t6(e)?e:{role:"user",parts:t4(e)}}function t7(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=t3(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=t3(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>t3(e)):[t3(t)]}function t9(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("contents are required");if(!Array.isArray(e)){if(t8(e)||t5(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[t3(e)]}let t=[],r=[],n=t6(e[0]);for(let i of e){let e=t6(i);if(e!=n)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(e)t.push(i);else if(t8(i)||t5(i))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else r.push(i)}return n||t.push({role:"user",parts:t4(r)}),t}function re(e){let t={},r=["items"],n=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let o=e.anyOf;for(let[s,a]of(null!=o&&2==o.length&&("null"===o[0].type?(t.nullable=!0,e=o[1]):"null"===o[1].type&&(t.nullable=!0,e=o[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);let r=e.filter(e=>"null"!==e);if(1===r.length)t.type=Object.values(ef).includes(r[0].toUpperCase())?r[0].toUpperCase():ef.TYPE_UNSPECIFIED;else for(let e of(t.anyOf=[],r))t.anyOf.push({type:Object.values(ef).includes(e.toUpperCase())?e.toUpperCase():ef.TYPE_UNSPECIFIED})}(e.type,t),Object.entries(e)))if(null!=a)if("type"==s){if("null"===a)throw Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(ef).includes(a.toUpperCase())?a.toUpperCase():ef.TYPE_UNSPECIFIED}else if(r.includes(s))t[s]=re(a);else if(n.includes(s)){let e=[];for(let r of a){if("null"==r.type){t.nullable=!0;continue}e.push(re(r))}t[s]=e}else if(i.includes(s)){let e={};for(let[t,r]of Object.entries(a))e[t]=re(r);t[s]=e}else{if("additionalProperties"===s)continue;t[s]=a}return t}function rt(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function rr(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function rn(e){if(e.functionDeclarations)for(let t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=re(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=re(t.response));return e}function ri(e){if(null==e)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let r of e)t.push(r);return t}function ro(e,t){if("string"!=typeof t)throw Error("name must be a string");return function(e,t,r,n=1){let i=!t.startsWith(`${r}/`)&&t.split("/").length===n;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${r}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(i)return`projects/${e.getProject()}/locations/${e.getLocation()}/${r}/${t}`;else return t;return i?`${r}/${t}`:t}(e,t,"cachedContents")}function rs(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function ra(e){return null!=e&&"object"==typeof e&&"video"in e}function rl(e){return null!=e&&"object"==typeof e&&"uri"in e}function ru(e){var t;let r;if(null!=e&&"object"==typeof e&&"name"in e&&(r=e.name),!rl(e)||void 0!==(r=e.uri)){if(!ra(e)||void 0!==(r=null==(t=e.video)?void 0:t.uri)){if("string"==typeof e&&(r=e),void 0===r)throw Error("Could not extract file name from the provided input.");if(r.startsWith("https://")){let e=r.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw Error(`Could not extract file name from URI ${r}`);r=e[0]}else r.startsWith("files/")&&(r=r.split("files/")[1]);return r}}}function rc(e,t){return e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels"}function rd(e){for(let n of["models","tunedModels","publisherModels"]){var t,r;if(t=e,r=n,null!==t&&"object"==typeof t&&r in t)return e[n]}return[]}function rp(e,t){let r;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))r={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))r={format:"bigquery",bigqueryUri:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))r={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");r={inlinedRequests:t}}else r=t;let n=[r.gcsUri,r.bigqueryUri].filter(Boolean).length,i=[r.inlinedRequests,r.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==n)throw Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(n>0||1!==i)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return r}function rh(e){if("object"!=typeof e||null===e)return{};let t=e.inlinedResponses;if("object"!=typeof t||null===t)return e;let r=t.inlinedResponses;if(!Array.isArray(r)||0===r.length)return e;let n=!1;for(let e of r){if("object"!=typeof e||null===e)continue;let t=e.response;if("object"==typeof t&&null!==t&&void 0!==t.embedding){n=!0;break}}return n&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),e}function rf(e,t){if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw Error(`Invalid batch job name: ${t}.`)}function rm(e){if("BATCH_STATE_UNSPECIFIED"===e)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===e)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===e)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===e)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===e)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===e)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===e)return"JOB_STATE_EXPIRED";else return e}function rg(e){let t={},r=t_(e,["name"]);null!=r&&ty(t,["name"],r);let n=t_(e,["metadata","displayName"]);null!=n&&ty(t,["displayName"],n);let i=t_(e,["metadata","state"]);null!=i&&ty(t,["state"],rm(i));let o=t_(e,["metadata","createTime"]);null!=o&&ty(t,["createTime"],o);let s=t_(e,["metadata","endTime"]);null!=s&&ty(t,["endTime"],s);let a=t_(e,["metadata","updateTime"]);null!=a&&ty(t,["updateTime"],a);let l=t_(e,["metadata","model"]);null!=l&&ty(t,["model"],l);let u=t_(e,["metadata","output"]);return null!=u&&ty(t,["dest"],function(e){let t={},r=t_(e,["responsesFile"]);null!=r&&ty(t,["fileName"],r);let n=t_(e,["inlinedResponses","inlinedResponses"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o;return r={},null!=(n=t_(t=e,["response"]))&&ty(r,["response"],function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["content"]);null!=r&&ty(t,["content"],r);let n=t_(e,["citationMetadata"]);null!=n&&ty(t,["citationMetadata"],function(e){let t={},r=t_(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["citations"],e)}return t}(n));let i=t_(e,["tokenCount"]);null!=i&&ty(t,["tokenCount"],i);let o=t_(e,["finishReason"]);null!=o&&ty(t,["finishReason"],o);let s=t_(e,["groundingMetadata"]);null!=s&&ty(t,["groundingMetadata"],s);let a=t_(e,["avgLogprobs"]);null!=a&&ty(t,["avgLogprobs"],a);let l=t_(e,["index"]);null!=l&&ty(t,["index"],l);let u=t_(e,["logprobsResult"]);null!=u&&ty(t,["logprobsResult"],u);let c=t_(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["safetyRatings"],e)}let d=t_(e,["urlContextMetadata"]);return null!=d&&ty(t,["urlContextMetadata"],d),t})(e))),ty(t,["candidates"],e)}let i=t_(e,["modelVersion"]);null!=i&&ty(t,["modelVersion"],i);let o=t_(e,["promptFeedback"]);null!=o&&ty(t,["promptFeedback"],o);let s=t_(e,["responseId"]);null!=s&&ty(t,["responseId"],s);let a=t_(e,["usageMetadata"]);return null!=a&&ty(t,["usageMetadata"],a),t}(n)),null!=(i=t_(t,["metadata"]))&&ty(r,["metadata"],i),null!=(o=t_(t,["error"]))&&ty(r,["error"],o),r})),ty(t,["inlinedResponses"],e)}let i=t_(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["inlinedEmbedContentResponses"],e)}return t}(rh(u))),t}function ry(e){var t,r;let n,i,o,s,a,l,u,c,d={},p=t_(e,["name"]);null!=p&&ty(d,["name"],p);let h=t_(e,["displayName"]);null!=h&&ty(d,["displayName"],h);let f=t_(e,["state"]);null!=f&&ty(d,["state"],rm(f));let m=t_(e,["error"]);null!=m&&ty(d,["error"],m);let g=t_(e,["createTime"]);null!=g&&ty(d,["createTime"],g);let y=t_(e,["startTime"]);null!=y&&ty(d,["startTime"],y);let _=t_(e,["endTime"]);null!=_&&ty(d,["endTime"],_);let E=t_(e,["updateTime"]);null!=E&&ty(d,["updateTime"],E);let v=t_(e,["model"]);null!=v&&ty(d,["model"],v);let T=t_(e,["inputConfig"]);null!=T&&ty(d,["src"],(n={},null!=(i=t_(r=T,["instancesFormat"]))&&ty(n,["format"],i),null!=(o=t_(r,["gcsSource","uris"]))&&ty(n,["gcsUri"],o),null!=(s=t_(r,["bigquerySource","inputUri"]))&&ty(n,["bigqueryUri"],s),n));let A=t_(e,["outputConfig"]);null!=A&&ty(d,["dest"],(t=rh(A),a={},null!=(l=t_(t,["predictionsFormat"]))&&ty(a,["format"],l),null!=(u=t_(t,["gcsDestination","outputUriPrefix"]))&&ty(a,["gcsUri"],u),null!=(c=t_(t,["bigqueryDestination","outputUri"]))&&ty(a,["bigqueryUri"],c),a));let S=t_(e,["completionStats"]);return null!=S&&ty(d,["completionStats"],S),d}function r_(e){let t={},r=t_(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p,h;return r={},null!=(n=t_(t=e,["mediaResolution"]))&&ty(r,["mediaResolution"],n),null!=(i=t_(t,["codeExecutionResult"]))&&ty(r,["codeExecutionResult"],i),null!=(o=t_(t,["executableCode"]))&&ty(r,["executableCode"],o),null!=(s=t_(t,["fileData"]))&&ty(r,["fileData"],function(e){let t={};if(void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=t_(e,["fileUri"]);null!=r&&ty(t,["fileUri"],r);let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(s)),null!=(a=t_(t,["functionCall"]))&&ty(r,["functionCall"],function(e){let t={},r=t_(e,["id"]);null!=r&&ty(t,["id"],r);let n=t_(e,["args"]);null!=n&&ty(t,["args"],n);let i=t_(e,["name"]);if(null!=i&&ty(t,["name"],i),void 0!==t_(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==t_(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=t_(t,["functionResponse"]))&&ty(r,["functionResponse"],l),null!=(u=t_(t,["inlineData"]))&&ty(r,["inlineData"],function(e){let t={},r=t_(e,["data"]);if(null!=r&&ty(t,["data"],r),void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(u)),null!=(c=t_(t,["text"]))&&ty(r,["text"],c),null!=(d=t_(t,["thought"]))&&ty(r,["thought"],d),null!=(p=t_(t,["thoughtSignature"]))&&ty(r,["thoughtSignature"],p),null!=(h=t_(t,["videoMetadata"]))&&ty(r,["videoMetadata"],h),r})),ty(t,["parts"],e)}let n=t_(e,["role"]);return null!=n&&ty(t,["role"],n),t}function rE(e,t){let r={},n=t_(t,["model"]);null!=n&&ty(r,["_url","model"],tz(e,n));let i=t_(t,["src"]);null!=i&&ty(r,["batch","inputConfig"],function(e,t){let r={};if(void 0!==t_(t,["format"]))throw Error("format parameter is not supported in Gemini API.");if(void 0!==t_(t,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==t_(t,["bigqueryUri"]))throw Error("bigqueryUri parameter is not supported in Gemini API.");let n=t_(t,["fileName"]);null!=n&&ty(r,["fileName"],n);let i=t_(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>(function(e,t){let r={},n=t_(t,["model"]);null!=n&&ty(r,["request","model"],tz(e,n));let i=t_(t,["contents"]);if(null!=i){let e=t9(i);Array.isArray(e)&&(e=e.map(e=>r_(e))),ty(r,["request","contents"],e)}let o=t_(t,["metadata"]);null!=o&&ty(r,["metadata"],o);let s=t_(t,["config"]);return null!=s&&ty(r,["request","generationConfig"],function(e,t,r){var n;let i,o,s,a={},l=t_(t,["systemInstruction"]);void 0!==r&&null!=l&&ty(r,["systemInstruction"],r_(t3(l)));let u=t_(t,["temperature"]);null!=u&&ty(a,["temperature"],u);let c=t_(t,["topP"]);null!=c&&ty(a,["topP"],c);let d=t_(t,["topK"]);null!=d&&ty(a,["topK"],d);let p=t_(t,["candidateCount"]);null!=p&&ty(a,["candidateCount"],p);let h=t_(t,["maxOutputTokens"]);null!=h&&ty(a,["maxOutputTokens"],h);let f=t_(t,["stopSequences"]);null!=f&&ty(a,["stopSequences"],f);let m=t_(t,["responseLogprobs"]);null!=m&&ty(a,["responseLogprobs"],m);let g=t_(t,["logprobs"]);null!=g&&ty(a,["logprobs"],g);let y=t_(t,["presencePenalty"]);null!=y&&ty(a,["presencePenalty"],y);let _=t_(t,["frequencyPenalty"]);null!=_&&ty(a,["frequencyPenalty"],_);let E=t_(t,["seed"]);null!=E&&ty(a,["seed"],E);let v=t_(t,["responseMimeType"]);null!=v&&ty(a,["responseMimeType"],v);let T=t_(t,["responseSchema"]);null!=T&&ty(a,["responseSchema"],re(T));let A=t_(t,["responseJsonSchema"]);if(null!=A&&ty(a,["responseJsonSchema"],A),void 0!==t_(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==t_(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let S=t_(t,["safetySettings"]);if(void 0!==r&&null!=S){let e=S;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["category"]);if(null!=r&&ty(t,["category"],r),void 0!==t_(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=t_(e,["threshold"]);return null!=n&&ty(t,["threshold"],n),t})(e))),ty(r,["safetySettings"],e)}let b=t_(t,["tools"]);if(void 0!==r&&null!=b){let e=ri(b);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==t_(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let r=t_(e,["computerUse"]);null!=r&&ty(t,["computerUse"],r);let n=t_(e,["fileSearch"]);null!=n&&ty(t,["fileSearch"],n);let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],function(e){let t={},r=t_(e,["searchTypes"]);if(null!=r&&ty(t,["searchTypes"],r),void 0!==t_(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==t_(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let n=t_(e,["timeRangeFilter"]);return null!=n&&ty(t,["timeRangeFilter"],n),t}(i));let o=t_(e,["codeExecution"]);if(null!=o&&ty(t,["codeExecution"],o),void 0!==t_(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let s=t_(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["functionDeclarations"],e)}let a=t_(e,["googleMaps"]);null!=a&&ty(t,["googleMaps"],function(e){let t={};if(void 0!==t_(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=t_(e,["enableWidget"]);return null!=r&&ty(t,["enableWidget"],r),t}(a));let l=t_(e,["googleSearchRetrieval"]);null!=l&&ty(t,["googleSearchRetrieval"],l);let u=t_(e,["urlContext"]);null!=u&&ty(t,["urlContext"],u);let c=t_(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["mcpServers"],e)}return t})(rn(e)))),ty(r,["tools"],e)}let C=t_(t,["toolConfig"]);if(void 0!==r&&null!=C&&ty(r,["toolConfig"],(i={},null!=(o=t_(n=C,["retrievalConfig"]))&&ty(i,["retrievalConfig"],o),null!=(s=t_(n,["functionCallingConfig"]))&&ty(i,["functionCallingConfig"],function(e){let t={},r=t_(e,["allowedFunctionNames"]);null!=r&&ty(t,["allowedFunctionNames"],r);let n=t_(e,["mode"]);if(null!=n&&ty(t,["mode"],n),void 0!==t_(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),i)),void 0!==t_(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=t_(t,["cachedContent"]);void 0!==r&&null!=O&&ty(r,["cachedContent"],ro(e,O));let I=t_(t,["responseModalities"]);null!=I&&ty(a,["responseModalities"],I);let w=t_(t,["mediaResolution"]);null!=w&&ty(a,["mediaResolution"],w);let R=t_(t,["speechConfig"]);if(null!=R&&ty(a,["speechConfig"],rt(R)),void 0!==t_(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let N=t_(t,["thinkingConfig"]);null!=N&&ty(a,["thinkingConfig"],N);let k=t_(t,["imageConfig"]);null!=k&&ty(a,["imageConfig"],function(e){let t={},r=t_(e,["aspectRatio"]);null!=r&&ty(t,["aspectRatio"],r);let n=t_(e,["imageSize"]);if(null!=n&&ty(t,["imageSize"],n),void 0!==t_(e,["personGeneration"]))throw Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==t_(e,["prominentPeople"]))throw Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==t_(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==t_(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}(k));let P=t_(t,["enableEnhancedCivicAnswers"]);if(null!=P&&ty(a,["enableEnhancedCivicAnswers"],P),void 0!==t_(t,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is not supported in Gemini API.");return a}(e,s,t_(r,["request"],{}))),r})(e,t))),ty(r,["requests","requests"],t)}return r}(e,rp(e,i)));let o=t_(t,["config"]);return null!=o&&function(e,t){let r=t_(e,["displayName"]);if(void 0!==t&&null!=r&&ty(t,["batch","displayName"],r),void 0!==t_(e,["dest"]))throw Error("dest parameter is not supported in Gemini API.")}(o,r),r}(ec=ts||(ts={})).PAGED_ITEM_BATCH_JOBS="batchJobs",ec.PAGED_ITEM_MODELS="models",ec.PAGED_ITEM_TUNING_JOBS="tuningJobs",ec.PAGED_ITEM_FILES="files",ec.PAGED_ITEM_CACHED_CONTENTS="cachedContents",ec.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",ec.PAGED_ITEM_DOCUMENTS="documents";class rv{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let o={config:{}};(o=r&&0!==Object.keys(r).length?"object"==typeof r?Object.assign({},r):r:{config:{}}).config&&(o.config.pageToken=t.nextPageToken),this.paramsInternal=o,this.pageInternalSize=null!=(i=null==(n=o.config)?void 0:n.pageSize)?i: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())return{value:void 0,done:!0};else await this.nextPage();let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return(null==(e=this.params.config)?void 0:e.pageToken)!==void 0}}class rT extends tm{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rv(ts.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=rE(this.apiClient,e),r=tg("{model}:batchGenerateContent",t._url),n=t.batch.inputConfig.requests,i=n.requests,o=[];for(let e of i){let t=Object.assign({},e);if(t.systemInstruction){let e=t.systemInstruction;delete t.systemInstruction;let r=t.request;r.systemInstruction=e,t.request=r}o.push(t)}return n.requests=o,delete t.config,delete t._url,delete t._query,{path:r,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){let r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),void 0===r.dest){let t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?r.dest=`${t.slice(0,-6)}/dest`:r.dest=`${t}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,i,o;let s="",a={};if(this.apiClient.isVertexAI()){let n,i,l,u,c,d,p=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["model"],tz(o,i)),null!=(l=t_(e,["src"]))&&ty(n,["inputConfig"],function(e){let t={},r=t_(e,["format"]);null!=r&&ty(t,["instancesFormat"],r);let n=t_(e,["gcsUri"]);null!=n&&ty(t,["gcsSource","uris"],n);let i=t_(e,["bigqueryUri"]);if(null!=i&&ty(t,["bigquerySource","inputUri"],i),void 0!==t_(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==t_(e,["inlinedRequests"]))throw Error("inlinedRequests parameter is not supported in Vertex AI.");return t}(rp(o,l))),null!=(u=t_(e,["config"]))&&(c=t_(u,["displayName"]),void 0!==n&&null!=c&&ty(n,["displayName"],c),d=t_(u,["dest"]),void 0!==n&&null!=d&&ty(n,["outputConfig"],function(e){let t={},r=t_(e,["format"]);null!=r&&ty(t,["predictionsFormat"],r);let n=t_(e,["gcsUri"]);null!=n&&ty(t,["gcsDestination","outputUriPrefix"],n);let i=t_(e,["bigqueryUri"]);if(null!=i&&ty(t,["bigqueryDestination","outputUri"],i),void 0!==t_(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==t_(e,["inlinedResponses"]))throw Error("inlinedResponses parameter is not supported in Vertex AI.");if(void 0!==t_(e,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return t}(function(e){if("string"!=typeof e)return e;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw Error(`Unsupported destination: ${e}`)}(d)))),n);return s=tg("batchPredictionJobs",p._url),a=p._query,delete p._url,delete p._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(p),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>ry(e))}{let t=rE(this.apiClient,e);return s=tg("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rg(e))}}async createEmbeddingsInternal(e){var t,r,n,i,o;let s="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let l,u,c,d,p,h,f,m,g=(n=this.apiClient,d={},null!=(p=t_(e,["model"]))&&ty(d,["_url","model"],tz(n,p)),null!=(h=t_(e,["src"]))&&ty(d,["batch","inputConfig"],(i=n,l={},null!=(u=t_(o=h,["fileName"]))&&ty(l,["file_name"],u),null!=(c=t_(o,["inlinedRequests"]))&&ty(l,["requests"],function(e,t){let r={},n=t_(t,["contents"]);if(null!=n){let t=t7(e,n);Array.isArray(t)&&(t=t.map(e=>e)),ty(r,["requests[]","request","content"],t)}let i=t_(t,["config"]);return null!=i&&(ty(r,["_self"],function(e,t){let r=t_(e,["taskType"]);void 0!==t&&null!=r&&ty(t,["requests[]","taskType"],r);let n=t_(e,["title"]);void 0!==t&&null!=n&&ty(t,["requests[]","title"],n);let i=t_(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&ty(t,["requests[]","outputDimensionality"],i),void 0!==t_(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==t_(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.");return{}}(i,r)),!function(e,t){for(let[r,n]of Object.entries(t)){let t=r.split("."),i=n.split("."),o=new Set,s=-1;for(let e=0;es)for(let e=s;e=r.length||"object"!=typeof t||null===t)return;let s=r[i];if(s.endsWith("[]")){let a=s.slice(0,-2);if(a in t&&Array.isArray(t[a]))for(let s of t[a])e(s,r,n,i+1,o)}else if("*"===s){if("object"==typeof t&&null!==t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith("_")&&!o.has(e)),r={};for(let n of e)r[n]=t[n];for(let[e,o]of Object.entries(r)){let r=[];for(let t of n.slice(i))"*"===t?r.push(e):r.push(t);ty(t,r,o)}for(let r of e)delete t[r]}}else s in t&&e(t[s],r,n,i+1,o)}(e,t,i,0,o)}}(r,{"requests[].*":"requests[].request.*"})),r}(i,c)),l)),null!=(f=t_(e,["config"]))&&(m=t_(f,["displayName"]),void 0!==d&&null!=m&&ty(d,["batch","displayName"],m)),d);return s=tg("{model}:asyncBatchEmbedContent",g._url),a=g._query,delete g._url,delete g._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rg(e))}}async get(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],rf(o,i)),n);return a=tg("batchPredictionJobs/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>ry(e))}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],rf(s,r)),t);return a=tg("batches/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rg(e))}}async cancel(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],rf(o,i)),n);a=tg("batchPredictionJobs/{name}:cancel",s._url),l=s._query,delete s._url,delete s._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}else{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],rf(s,r)),t);a=tg("batches/{name}:cancel",o._url),l=o._query,delete o._url,delete o._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal})}}async listInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=t_(e,["config"]))&&(a=t_(i,["pageSize"]),void 0!==n&&null!=a&&ty(n,["_query","pageSize"],a),l=t_(i,["pageToken"]),void 0!==n&&null!=l&&ty(n,["_query","pageToken"],l),u=t_(i,["filter"]),void 0!==n&&null!=u&&ty(n,["_query","filter"],u)),n);return o=tg("batchPredictionJobs",c._url),s=c._query,delete c._url,delete c._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ry(e))),ty(t,["batchJobs"],e)}return t}(e),r=new tJ;return Object.assign(r,t),r})}{let t,r,a=(t={},null!=(r=t_(e,["config"]))&&function(e,t){let r=t_(e,["pageSize"]);void 0!==t&&null!=r&&ty(t,["_query","pageSize"],r);let n=t_(e,["pageToken"]);if(void 0!==t&&null!=n&&ty(t,["_query","pageToken"],n),void 0!==t_(e,["filter"]))throw Error("filter parameter is not supported in Gemini API.")}(r,t),t);return o=tg("batches",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rg(e))),ty(t,["batchJobs"],e)}return t}(e),r=new tJ;return Object.assign(r,t),r})}}async delete(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],rf(o,i)),n);return a=tg("batchPredictionJobs/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,o;return t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),null!=(n=t_(e,["name"]))&&ty(t,["name"],n),null!=(i=t_(e,["done"]))&&ty(t,["done"],i),null!=(o=t_(e,["error"]))&&ty(t,["error"],o),t})}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],rf(s,r)),t);return a=tg("batches/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,o;return t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),null!=(n=t_(e,["name"]))&&ty(t,["name"],n),null!=(i=t_(e,["done"]))&&ty(t,["done"],i),null!=(o=t_(e,["error"]))&&ty(t,["error"],o),t})}}}function rA(e){let t={},r=t_(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p,h;return r={},null!=(n=t_(t=e,["mediaResolution"]))&&ty(r,["mediaResolution"],n),null!=(i=t_(t,["codeExecutionResult"]))&&ty(r,["codeExecutionResult"],i),null!=(o=t_(t,["executableCode"]))&&ty(r,["executableCode"],o),null!=(s=t_(t,["fileData"]))&&ty(r,["fileData"],function(e){let t={};if(void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=t_(e,["fileUri"]);null!=r&&ty(t,["fileUri"],r);let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(s)),null!=(a=t_(t,["functionCall"]))&&ty(r,["functionCall"],function(e){let t={},r=t_(e,["id"]);null!=r&&ty(t,["id"],r);let n=t_(e,["args"]);null!=n&&ty(t,["args"],n);let i=t_(e,["name"]);if(null!=i&&ty(t,["name"],i),void 0!==t_(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==t_(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=t_(t,["functionResponse"]))&&ty(r,["functionResponse"],l),null!=(u=t_(t,["inlineData"]))&&ty(r,["inlineData"],function(e){let t={},r=t_(e,["data"]);if(null!=r&&ty(t,["data"],r),void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(u)),null!=(c=t_(t,["text"]))&&ty(r,["text"],c),null!=(d=t_(t,["thought"]))&&ty(r,["thought"],d),null!=(p=t_(t,["thoughtSignature"]))&&ty(r,["thoughtSignature"],p),null!=(h=t_(t,["videoMetadata"]))&&ty(r,["videoMetadata"],h),r})),ty(t,["parts"],e)}let n=t_(e,["role"]);return null!=n&&ty(t,["role"],n),t}class rS extends tm{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rv(ts.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s,u=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["model"],tX(o,i)),null!=(s=t_(e,["config"]))&&function(e,t){let r=t_(e,["ttl"]);void 0!==t&&null!=r&&ty(t,["ttl"],r);let n=t_(e,["expireTime"]);void 0!==t&&null!=n&&ty(t,["expireTime"],n);let i=t_(e,["displayName"]);void 0!==t&&null!=i&&ty(t,["displayName"],i);let o=t_(e,["contents"]);if(void 0!==t&&null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["contents"],e)}let s=t_(e,["systemInstruction"]);void 0!==t&&null!=s&&ty(t,["systemInstruction"],t3(s));let a=t_(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["retrieval"]);null!=r&&ty(t,["retrieval"],r);let n=t_(e,["computerUse"]);if(null!=n&&ty(t,["computerUse"],n),void 0!==t_(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],i);let o=t_(e,["codeExecution"]);null!=o&&ty(t,["codeExecution"],o);let s=t_(e,["enterpriseWebSearch"]);null!=s&&ty(t,["enterpriseWebSearch"],s);let a=t_(e,["functionDeclarations"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["description"]);null!=r&&ty(t,["description"],r);let n=t_(e,["name"]);null!=n&&ty(t,["name"],n);let i=t_(e,["parameters"]);null!=i&&ty(t,["parameters"],i);let o=t_(e,["parametersJsonSchema"]);null!=o&&ty(t,["parametersJsonSchema"],o);let s=t_(e,["response"]);null!=s&&ty(t,["response"],s);let a=t_(e,["responseJsonSchema"]);if(null!=a&&ty(t,["responseJsonSchema"],a),void 0!==t_(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");return t})(e))),ty(t,["functionDeclarations"],e)}let l=t_(e,["googleMaps"]);null!=l&&ty(t,["googleMaps"],l);let u=t_(e,["googleSearchRetrieval"]);null!=u&&ty(t,["googleSearchRetrieval"],u);let c=t_(e,["urlContext"]);if(null!=c&&ty(t,["urlContext"],c),void 0!==t_(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Vertex AI.");return t})(e))),ty(t,["tools"],e)}let l=t_(e,["toolConfig"]);void 0!==t&&null!=l&&ty(t,["toolConfig"],l);let u=t_(e,["kmsKeyName"]);void 0!==t&&null!=u&&ty(t,["encryption_spec","kmsKeyName"],u)}(s,n),n);return a=tg("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,o,u=(s=this.apiClient,t={},null!=(r=t_(e,["model"]))&&ty(t,["model"],tX(s,r)),null!=(o=t_(e,["config"]))&&function(e,t){var r;let n,i,o,s=t_(e,["ttl"]);void 0!==t&&null!=s&&ty(t,["ttl"],s);let a=t_(e,["expireTime"]);void 0!==t&&null!=a&&ty(t,["expireTime"],a);let l=t_(e,["displayName"]);void 0!==t&&null!=l&&ty(t,["displayName"],l);let u=t_(e,["contents"]);if(void 0!==t&&null!=u){let e=t9(u);Array.isArray(e)&&(e=e.map(e=>rA(e))),ty(t,["contents"],e)}let c=t_(e,["systemInstruction"]);void 0!==t&&null!=c&&ty(t,["systemInstruction"],rA(t3(c)));let d=t_(e,["tools"]);if(void 0!==t&&null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==t_(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let r=t_(e,["computerUse"]);null!=r&&ty(t,["computerUse"],r);let n=t_(e,["fileSearch"]);null!=n&&ty(t,["fileSearch"],n);let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],function(e){let t={},r=t_(e,["searchTypes"]);if(null!=r&&ty(t,["searchTypes"],r),void 0!==t_(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==t_(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let n=t_(e,["timeRangeFilter"]);return null!=n&&ty(t,["timeRangeFilter"],n),t}(i));let o=t_(e,["codeExecution"]);if(null!=o&&ty(t,["codeExecution"],o),void 0!==t_(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let s=t_(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["functionDeclarations"],e)}let a=t_(e,["googleMaps"]);null!=a&&ty(t,["googleMaps"],function(e){let t={};if(void 0!==t_(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=t_(e,["enableWidget"]);return null!=r&&ty(t,["enableWidget"],r),t}(a));let l=t_(e,["googleSearchRetrieval"]);null!=l&&ty(t,["googleSearchRetrieval"],l);let u=t_(e,["urlContext"]);null!=u&&ty(t,["urlContext"],u);let c=t_(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["mcpServers"],e)}return t})(e))),ty(t,["tools"],e)}let p=t_(e,["toolConfig"]);if(void 0!==t&&null!=p&&ty(t,["toolConfig"],(n={},null!=(i=t_(r=p,["retrievalConfig"]))&&ty(n,["retrievalConfig"],i),null!=(o=t_(r,["functionCallingConfig"]))&&ty(n,["functionCallingConfig"],function(e){let t={},r=t_(e,["allowedFunctionNames"]);null!=r&&ty(t,["allowedFunctionNames"],r);let n=t_(e,["mode"]);if(null!=n&&ty(t,["mode"],n),void 0!==t_(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o)),n)),void 0!==t_(e,["kmsKeyName"]))throw Error("kmsKeyName parameter is not supported in Gemini API.")}(o,t),t);return a=tg("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],ro(o,i)),n);return a=tg("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],ro(s,r)),t);return a=tg("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],ro(o,i)),n);return a=tg("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tM;return Object.assign(i,n),i})}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],ro(s,r)),t);return a=tg("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tM;return Object.assign(i,n),i})}}async update(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s,u,c,d=(o=this.apiClient,n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],ro(o,i)),null!=(s=t_(e,["config"]))&&(u=t_(s,["ttl"]),void 0!==n&&null!=u&&ty(n,["ttl"],u),c=t_(s,["expireTime"]),void 0!==n&&null!=c&&ty(n,["expireTime"],c)),n);return a=tg("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,o,u,c,d=(s=this.apiClient,t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],ro(s,r)),null!=(o=t_(e,["config"]))&&(u=t_(o,["ttl"]),void 0!==t&&null!=u&&ty(t,["ttl"],u),c=t_(o,["expireTime"]),void 0!==t&&null!=c&&ty(t,["expireTime"],c)),t);return a=tg("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async listInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a,l,u=(n={},null!=(i=t_(e,["config"]))&&(a=t_(i,["pageSize"]),void 0!==n&&null!=a&&ty(n,["_query","pageSize"],a),l=t_(i,["pageToken"]),void 0!==n&&null!=l&&ty(n,["_query","pageToken"],l)),n);return o=tg("cachedContents",u._url),s=u._query,delete u._url,delete u._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["cachedContents"],e)}return t}(e),r=new tL;return Object.assign(r,t),r})}{let t,r,a,l,u=(t={},null!=(r=t_(e,["config"]))&&(a=t_(r,["pageSize"]),void 0!==t&&null!=a&&ty(t,["_query","pageSize"],a),l=t_(r,["pageToken"]),void 0!==t&&null!=l&&ty(t,["_query","pageToken"],l)),t);return o=tg("cachedContents",u._url),s=u._query,delete u._url,delete u._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["cachedContents"],e)}return t}(e),r=new tL;return Object.assign(r,t),r})}}}function rb(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);it.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function rC(e){return this instanceof rC?(this.v=e,this):new rC(e)}function rO(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){i[e]&&(n[e]=function(t){return new Promise(function(r,n){o.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var r;(r=i[e](t)).value instanceof rC?Promise.resolve(r.value.v).then(l,u):c(o[0][2],r)}catch(e){c(o[0][3],e)}}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function rI(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){var o,s,a;o=n,s=i,a=(t=e[r](t)).done,Promise.resolve(t.value).then(function(e){o({value:e,done:a})},s)})}}}function rw(e){if(void 0===e.parts||0===e.parts.length)return!1;for(let t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function rR(e){if(void 0===e||0===e.length)return[];let t=[],r=e.length,n=0;for(;n{var e,t,i;let o=await n,s=null==(t=null==(e=o.candidates)?void 0:e[0])?void 0:t.content,a=o.automaticFunctionCallingHistory,l=this.getHistory(!0).length,u=[];null!=a&&(u=null!=(i=a.slice(l))?i:[]),this.recordHistory(r,s?[s]:[],u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;let r=t3(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});this.sendPromise=n.then(()=>void 0).catch(()=>void 0);let i=await n;return this.processStreamResponse(i,r)}getHistory(e=!1){return structuredClone(e?rR(this.history):this.history)}processStreamResponse(e,t){return rO(this,arguments,function*(){let r=[];try{for(var n,i,o,s,a,l,u,c=!0,d=rI(e);!(n=(u=yield rC(d.next())).done);c=!0){if(s=u.value,c=!1,function(e){var t;if(void 0==e.candidates||0===e.candidates.length)return!1;let r=null==(t=e.candidates[0])?void 0:t.content;return void 0!==r&&rw(r)}(s)){let e=null==(l=null==(a=s.candidates)?void 0:a[0])?void 0:l.content;void 0!==e&&r.push(e)}yield yield rC(s)}}catch(e){i={error:e}}finally{try{!c&&!n&&(o=d.return)&&(yield rC(o.call(d)))}finally{if(i)throw i.error}}this.recordHistory(t,r)})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(e=>void 0!==e.role)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...rR(r)):this.history.push(e),this.history.push(...n)}}class rP extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,rP.prototype)}}class rx extends tm{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rv(ts.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u=(o={},null!=(s=t_(e,["config"]))&&(a=t_(s,["pageSize"]),void 0!==o&&null!=a&&ty(o,["_query","pageSize"],a),l=t_(s,["pageToken"]),void 0!==o&&null!=l&&ty(o,["_query","pageToken"],l)),o);return n=tg("files",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["files"],e)}return t}(e),r=new tH;return Object.assign(r,t),r})}}async createInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["file"]))&&ty(o,["file"],s),o);return n=tg("upload/v1beta/files",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tB;return Object.assign(i,n),i})}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","file"],ru(s)),o);return n=tg("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","file"],ru(s)),o);return n=tg("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tV;return Object.assign(i,n),i})}}async registerFilesInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["uris"]))&&ty(o,["uris"],s),o);return n=tg("files:register",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["files"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["files"],e)}return t}(e),r=new t$;return Object.assign(r,t),r})}}}function rU(e){let t={},r=t_(e,["data"]);if(null!=r&&ty(t,["data"],r),void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}function rD(e,t){let r={},n=t_(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p,h;return r={},null!=(n=t_(t=e,["mediaResolution"]))&&ty(r,["mediaResolution"],n),null!=(i=t_(t,["codeExecutionResult"]))&&ty(r,["codeExecutionResult"],i),null!=(o=t_(t,["executableCode"]))&&ty(r,["executableCode"],o),null!=(s=t_(t,["fileData"]))&&ty(r,["fileData"],function(e,t){let r={};if(void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=t_(e,["fileUri"]);null!=n&&ty(r,["fileUri"],n);let i=t_(e,["mimeType"]);return null!=i&&ty(r,["mimeType"],i),r}(s)),null!=(a=t_(t,["functionCall"]))&&ty(r,["functionCall"],function(e,t){let r={},n=t_(e,["id"]);null!=n&&ty(r,["id"],n);let i=t_(e,["args"]);null!=i&&ty(r,["args"],i);let o=t_(e,["name"]);if(null!=o&&ty(r,["name"],o),void 0!==t_(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==t_(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return r}(a)),null!=(l=t_(t,["functionResponse"]))&&ty(r,["functionResponse"],l),null!=(u=t_(t,["inlineData"]))&&ty(r,["inlineData"],function(e,t){let r={},n=t_(e,["data"]);if(null!=n&&ty(r,["data"],n),void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let i=t_(e,["mimeType"]);return null!=i&&ty(r,["mimeType"],i),r}(u)),null!=(c=t_(t,["text"]))&&ty(r,["text"],c),null!=(d=t_(t,["thought"]))&&ty(r,["thought"],d),null!=(p=t_(t,["thoughtSignature"]))&&ty(r,["thoughtSignature"],p),null!=(h=t_(t,["videoMetadata"]))&&ty(r,["videoMetadata"],h),r})),ty(r,["parts"],e)}let i=t_(e,["role"]);return null!=i&&ty(r,["role"],i),r}function rM(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>rD(e))),ty(n,["contents"],e)}let s=t_(t,["config"]);return null!=s&&ty(n,["generationConfig"],function(e,t,r,n){var i;let o,s,a,l={},u=t_(t,["systemInstruction"]);void 0!==r&&null!=u&&ty(r,["systemInstruction"],rD(t3(u)));let c=t_(t,["temperature"]);null!=c&&ty(l,["temperature"],c);let d=t_(t,["topP"]);null!=d&&ty(l,["topP"],d);let p=t_(t,["topK"]);null!=p&&ty(l,["topK"],p);let h=t_(t,["candidateCount"]);null!=h&&ty(l,["candidateCount"],h);let f=t_(t,["maxOutputTokens"]);null!=f&&ty(l,["maxOutputTokens"],f);let m=t_(t,["stopSequences"]);null!=m&&ty(l,["stopSequences"],m);let g=t_(t,["responseLogprobs"]);null!=g&&ty(l,["responseLogprobs"],g);let y=t_(t,["logprobs"]);null!=y&&ty(l,["logprobs"],y);let _=t_(t,["presencePenalty"]);null!=_&&ty(l,["presencePenalty"],_);let E=t_(t,["frequencyPenalty"]);null!=E&&ty(l,["frequencyPenalty"],E);let v=t_(t,["seed"]);null!=v&&ty(l,["seed"],v);let T=t_(t,["responseMimeType"]);null!=T&&ty(l,["responseMimeType"],T);let A=t_(t,["responseSchema"]);null!=A&&ty(l,["responseSchema"],re(A));let S=t_(t,["responseJsonSchema"]);if(null!=S&&ty(l,["responseJsonSchema"],S),void 0!==t_(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==t_(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let b=t_(t,["safetySettings"]);if(void 0!==r&&null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r={},n=t_(e,["category"]);if(null!=n&&ty(r,["category"],n),void 0!==t_(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let i=t_(e,["threshold"]);return null!=i&&ty(r,["threshold"],i),r})(e))),ty(r,["safetySettings"],e)}let C=t_(t,["tools"]);if(void 0!==r&&null!=C){let e=ri(C);Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r={};if(void 0!==t_(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=t_(e,["computerUse"]);null!=n&&ty(r,["computerUse"],n);let i=t_(e,["fileSearch"]);null!=i&&ty(r,["fileSearch"],i);let o=t_(e,["googleSearch"]);null!=o&&ty(r,["googleSearch"],function(e,t){let r={},n=t_(e,["searchTypes"]);if(null!=n&&ty(r,["searchTypes"],n),void 0!==t_(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==t_(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let i=t_(e,["timeRangeFilter"]);return null!=i&&ty(r,["timeRangeFilter"],i),r}(o));let s=t_(e,["codeExecution"]);if(null!=s&&ty(r,["codeExecution"],s),void 0!==t_(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=t_(e,["functionDeclarations"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["functionDeclarations"],e)}let l=t_(e,["googleMaps"]);null!=l&&ty(r,["googleMaps"],function(e,t){let r={};if(void 0!==t_(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let n=t_(e,["enableWidget"]);return null!=n&&ty(r,["enableWidget"],n),r}(l));let u=t_(e,["googleSearchRetrieval"]);null!=u&&ty(r,["googleSearchRetrieval"],u);let c=t_(e,["urlContext"]);null!=c&&ty(r,["urlContext"],c);let d=t_(e,["mcpServers"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["mcpServers"],e)}return r})(rn(e)))),ty(r,["tools"],e)}let O=t_(t,["toolConfig"]);if(void 0!==r&&null!=O&&ty(r,["toolConfig"],(o={},null!=(s=t_(i=O,["retrievalConfig"]))&&ty(o,["retrievalConfig"],s),null!=(a=t_(i,["functionCallingConfig"]))&&ty(o,["functionCallingConfig"],function(e,t){let r={},n=t_(e,["allowedFunctionNames"]);null!=n&&ty(r,["allowedFunctionNames"],n);let i=t_(e,["mode"]);if(null!=i&&ty(r,["mode"],i),void 0!==t_(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return r}(a)),o)),void 0!==t_(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let I=t_(t,["cachedContent"]);void 0!==r&&null!=I&&ty(r,["cachedContent"],ro(e,I));let w=t_(t,["responseModalities"]);null!=w&&ty(l,["responseModalities"],w);let R=t_(t,["mediaResolution"]);null!=R&&ty(l,["mediaResolution"],R);let N=t_(t,["speechConfig"]);if(null!=N&&ty(l,["speechConfig"],rt(N)),void 0!==t_(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let k=t_(t,["thinkingConfig"]);null!=k&&ty(l,["thinkingConfig"],k);let P=t_(t,["imageConfig"]);null!=P&&ty(l,["imageConfig"],function(e,t){let r={},n=t_(e,["aspectRatio"]);null!=n&&ty(r,["aspectRatio"],n);let i=t_(e,["imageSize"]);if(null!=i&&ty(r,["imageSize"],i),void 0!==t_(e,["personGeneration"]))throw Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==t_(e,["prominentPeople"]))throw Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==t_(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==t_(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return r}(P));let x=t_(t,["enableEnhancedCivicAnswers"]);if(null!=x&&ty(l,["enableEnhancedCivicAnswers"],x),void 0!==t_(t,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is not supported in Gemini API.");return l}(e,s,n)),n}function rL(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>e)),ty(n,["contents"],e)}let s=t_(t,["config"]);return null!=s&&ty(n,["generationConfig"],function(e,t,r,n){var i;let o,s,a,l,u,c,d,p={},h=t_(t,["systemInstruction"]);void 0!==r&&null!=h&&ty(r,["systemInstruction"],t3(h));let f=t_(t,["temperature"]);null!=f&&ty(p,["temperature"],f);let m=t_(t,["topP"]);null!=m&&ty(p,["topP"],m);let g=t_(t,["topK"]);null!=g&&ty(p,["topK"],g);let y=t_(t,["candidateCount"]);null!=y&&ty(p,["candidateCount"],y);let _=t_(t,["maxOutputTokens"]);null!=_&&ty(p,["maxOutputTokens"],_);let E=t_(t,["stopSequences"]);null!=E&&ty(p,["stopSequences"],E);let v=t_(t,["responseLogprobs"]);null!=v&&ty(p,["responseLogprobs"],v);let T=t_(t,["logprobs"]);null!=T&&ty(p,["logprobs"],T);let A=t_(t,["presencePenalty"]);null!=A&&ty(p,["presencePenalty"],A);let S=t_(t,["frequencyPenalty"]);null!=S&&ty(p,["frequencyPenalty"],S);let b=t_(t,["seed"]);null!=b&&ty(p,["seed"],b);let C=t_(t,["responseMimeType"]);null!=C&&ty(p,["responseMimeType"],C);let O=t_(t,["responseSchema"]);null!=O&&ty(p,["responseSchema"],re(O));let I=t_(t,["responseJsonSchema"]);null!=I&&ty(p,["responseJsonSchema"],I);let w=t_(t,["routingConfig"]);null!=w&&ty(p,["routingConfig"],w);let R=t_(t,["modelSelectionConfig"]);null!=R&&ty(p,["modelConfig"],R);let N=t_(t,["safetySettings"]);if(void 0!==r&&null!=N){let e=N;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["safetySettings"],e)}let k=t_(t,["tools"]);if(void 0!==r&&null!=k){let e=ri(k);Array.isArray(e)&&(e=e.map(e=>rK(rn(e)))),ty(r,["tools"],e)}let P=t_(t,["toolConfig"]);void 0!==r&&null!=P&&ty(r,["toolConfig"],P);let x=t_(t,["labels"]);void 0!==r&&null!=x&&ty(r,["labels"],x);let U=t_(t,["cachedContent"]);void 0!==r&&null!=U&&ty(r,["cachedContent"],ro(e,U));let D=t_(t,["responseModalities"]);null!=D&&ty(p,["responseModalities"],D);let M=t_(t,["mediaResolution"]);null!=M&&ty(p,["mediaResolution"],M);let L=t_(t,["speechConfig"]);null!=L&&ty(p,["speechConfig"],rt(L));let j=t_(t,["audioTimestamp"]);null!=j&&ty(p,["audioTimestamp"],j);let G=t_(t,["thinkingConfig"]);null!=G&&ty(p,["thinkingConfig"],G);let F=t_(t,["imageConfig"]);if(null!=F&&ty(p,["imageConfig"],(o={},null!=(s=t_(i=F,["aspectRatio"]))&&ty(o,["aspectRatio"],s),null!=(a=t_(i,["imageSize"]))&&ty(o,["imageSize"],a),null!=(l=t_(i,["personGeneration"]))&&ty(o,["personGeneration"],l),null!=(u=t_(i,["prominentPeople"]))&&ty(o,["prominentPeople"],u),null!=(c=t_(i,["outputMimeType"]))&&ty(o,["imageOutputOptions","mimeType"],c),null!=(d=t_(i,["outputCompressionQuality"]))&&ty(o,["imageOutputOptions","compressionQuality"],d),o)),void 0!==t_(t,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");let q=t_(t,["modelArmorConfig"]);return void 0!==r&&null!=q&&ty(r,["modelArmorConfig"],q),p}(e,s,n)),n}function rj(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r={},n=t_(e,["content"]);null!=n&&ty(r,["content"],n);let i=t_(e,["citationMetadata"]);null!=i&&ty(r,["citationMetadata"],function(e,t){let r={},n=t_(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["citations"],e)}return r}(i));let o=t_(e,["tokenCount"]);null!=o&&ty(r,["tokenCount"],o);let s=t_(e,["finishReason"]);null!=s&&ty(r,["finishReason"],s);let a=t_(e,["groundingMetadata"]);null!=a&&ty(r,["groundingMetadata"],a);let l=t_(e,["avgLogprobs"]);null!=l&&ty(r,["avgLogprobs"],l);let u=t_(e,["index"]);null!=u&&ty(r,["index"],u);let c=t_(e,["logprobsResult"]);null!=c&&ty(r,["logprobsResult"],c);let d=t_(e,["safetyRatings"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["safetyRatings"],e)}let p=t_(e,["urlContextMetadata"]);return null!=p&&ty(r,["urlContextMetadata"],p),r})(e))),ty(r,["candidates"],e)}let o=t_(e,["modelVersion"]);null!=o&&ty(r,["modelVersion"],o);let s=t_(e,["promptFeedback"]);null!=s&&ty(r,["promptFeedback"],s);let a=t_(e,["responseId"]);null!=a&&ty(r,["responseId"],a);let l=t_(e,["usageMetadata"]);return null!=l&&ty(r,["usageMetadata"],l),r}function rG(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["candidates"],e)}let o=t_(e,["createTime"]);null!=o&&ty(r,["createTime"],o);let s=t_(e,["modelVersion"]);null!=s&&ty(r,["modelVersion"],s);let a=t_(e,["promptFeedback"]);null!=a&&ty(r,["promptFeedback"],a);let l=t_(e,["responseId"]);null!=l&&ty(r,["responseId"],l);let u=t_(e,["usageMetadata"]);return null!=u&&ty(r,["usageMetadata"],u),r}function rF(e,t){let r={},n=t_(e,["_self"]);null!=n&&ty(r,["image"],rq(n));let i=t_(e,["raiFilteredReason"]);null!=i&&ty(r,["raiFilteredReason"],i);let o=t_(e,["_self"]);null!=o&&ty(r,["safetyAttributes"],rW(o));let s=t_(e,["prompt"]);return null!=s&&ty(r,["enhancedPrompt"],s),r}function rq(e,t){let r={},n=t_(e,["gcsUri"]);null!=n&&ty(r,["gcsUri"],n);let i=t_(e,["bytesBase64Encoded"]);null!=i&&ty(r,["imageBytes"],tE(i));let o=t_(e,["mimeType"]);return null!=o&&ty(r,["mimeType"],o),r}function rH(e,t){let r={};if(void 0!==t_(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");let n=t_(e,["imageBytes"]);null!=n&&ty(r,["bytesBase64Encoded"],tE(n));let i=t_(e,["mimeType"]);return null!=i&&ty(r,["mimeType"],i),r}function rB(e,t){let r={},n=t_(e,["gcsUri"]);null!=n&&ty(r,["gcsUri"],n);let i=t_(e,["imageBytes"]);null!=i&&ty(r,["bytesBase64Encoded"],tE(i));let o=t_(e,["mimeType"]);return null!=o&&ty(r,["mimeType"],o),r}function rV(e,t){var r;let n,i,o,s,a={},l=t_(e,["name"]);null!=l&&ty(a,["name"],l);let u=t_(e,["displayName"]);null!=u&&ty(a,["displayName"],u);let c=t_(e,["description"]);null!=c&&ty(a,["description"],c);let d=t_(e,["version"]);null!=d&&ty(a,["version"],d);let p=t_(e,["_self"]);null!=p&&ty(a,["tunedModelInfo"],(n={},null!=(i=t_(r=p,["baseModel"]))&&ty(n,["baseModel"],i),null!=(o=t_(r,["createTime"]))&&ty(n,["createTime"],o),null!=(s=t_(r,["updateTime"]))&&ty(n,["updateTime"],s),n));let h=t_(e,["inputTokenLimit"]);null!=h&&ty(a,["inputTokenLimit"],h);let f=t_(e,["outputTokenLimit"]);null!=f&&ty(a,["outputTokenLimit"],f);let m=t_(e,["supportedGenerationMethods"]);null!=m&&ty(a,["supportedActions"],m);let g=t_(e,["temperature"]);null!=g&&ty(a,["temperature"],g);let y=t_(e,["maxTemperature"]);null!=y&&ty(a,["maxTemperature"],y);let _=t_(e,["topP"]);null!=_&&ty(a,["topP"],_);let E=t_(e,["topK"]);null!=E&&ty(a,["topK"],E);let v=t_(e,["thinking"]);return null!=v&&ty(a,["thinking"],v),a}function r$(e,t){var r;let n,i,o,s,a={},l=t_(e,["name"]);null!=l&&ty(a,["name"],l);let u=t_(e,["displayName"]);null!=u&&ty(a,["displayName"],u);let c=t_(e,["description"]);null!=c&&ty(a,["description"],c);let d=t_(e,["versionId"]);null!=d&&ty(a,["version"],d);let p=t_(e,["deployedModels"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>{let t,r,n;return t={},null!=(r=t_(e,["endpoint"]))&&ty(t,["name"],r),null!=(n=t_(e,["deployedModelId"]))&&ty(t,["deployedModelId"],n),t})),ty(a,["endpoints"],e)}let h=t_(e,["labels"]);null!=h&&ty(a,["labels"],h);let f=t_(e,["_self"]);null!=f&&ty(a,["tunedModelInfo"],(n={},null!=(i=t_(r=f,["labels","google-vertex-llm-tuning-base-model-id"]))&&ty(n,["baseModel"],i),null!=(o=t_(r,["createTime"]))&&ty(n,["createTime"],o),null!=(s=t_(r,["updateTime"]))&&ty(n,["updateTime"],s),n));let m=t_(e,["defaultCheckpointId"]);null!=m&&ty(a,["defaultCheckpointId"],m);let g=t_(e,["checkpoints"]);if(null!=g){let e=g;Array.isArray(e)&&(e=e.map(e=>e)),ty(a,["checkpoints"],e)}return a}function rJ(e,t){let r={},n=t_(e,["safetyAttributes","categories"]);null!=n&&ty(r,["categories"],n);let i=t_(e,["safetyAttributes","scores"]);null!=i&&ty(r,["scores"],i);let o=t_(e,["contentType"]);return null!=o&&ty(r,["contentType"],o),r}function rW(e,t){let r={},n=t_(e,["safetyAttributes","categories"]);null!=n&&ty(r,["categories"],n);let i=t_(e,["safetyAttributes","scores"]);null!=i&&ty(r,["scores"],i);let o=t_(e,["contentType"]);return null!=o&&ty(r,["contentType"],o),r}function rK(e,t){let r={},n=t_(e,["retrieval"]);null!=n&&ty(r,["retrieval"],n);let i=t_(e,["computerUse"]);if(null!=i&&ty(r,["computerUse"],i),void 0!==t_(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=t_(e,["googleSearch"]);null!=o&&ty(r,["googleSearch"],o);let s=t_(e,["codeExecution"]);null!=s&&ty(r,["codeExecution"],s);let a=t_(e,["enterpriseWebSearch"]);null!=a&&ty(r,["enterpriseWebSearch"],a);let l=t_(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r={},n=t_(e,["description"]);null!=n&&ty(r,["description"],n);let i=t_(e,["name"]);null!=i&&ty(r,["name"],i);let o=t_(e,["parameters"]);null!=o&&ty(r,["parameters"],o);let s=t_(e,["parametersJsonSchema"]);null!=s&&ty(r,["parametersJsonSchema"],s);let a=t_(e,["response"]);null!=a&&ty(r,["response"],a);let l=t_(e,["responseJsonSchema"]);if(null!=l&&ty(r,["responseJsonSchema"],l),void 0!==t_(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");return r})(e))),ty(r,["functionDeclarations"],e)}let u=t_(e,["googleMaps"]);null!=u&&ty(r,["googleMaps"],u);let c=t_(e,["googleSearchRetrieval"]);null!=c&&ty(r,["googleSearchRetrieval"],c);let d=t_(e,["urlContext"]);if(null!=d&&ty(r,["urlContext"],d),void 0!==t_(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Vertex AI.");return r}function rY(e,t){let r={},n=t_(e,["uri"]);null!=n&&ty(r,["uri"],n);let i=t_(e,["videoBytes"]);null!=i&&ty(r,["encodedVideo"],tE(i));let o=t_(e,["mimeType"]);return null!=o&&ty(r,["encoding"],o),r}function rz(e,t){let r={},n=t_(e,["uri"]);null!=n&&ty(r,["gcsUri"],n);let i=t_(e,["videoBytes"]);null!=i&&ty(r,["bytesBase64Encoded"],tE(i));let o=t_(e,["mimeType"]);return null!=o&&ty(r,["mimeType"],o),r}function rX(e,t){let r=t_(e,["mimeType"]);void 0!==t&&null!=r&&ty(t,["mimeType"],r);let n=t_(e,["displayName"]);void 0!==t&&null!=n&&ty(t,["displayName"],n);let i=t_(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["customMetadata"],e)}let o=t_(e,["chunkingConfig"]);return void 0!==t&&null!=o&&ty(t,["chunkingConfig"],o),{}}let rQ="x-goog-api-client",rZ=[408,429,500,502,503,504];class r0{constructor(e){var t,r,n;this.clientOptions=Object.assign({},e),this.customBaseUrl=null==(t=e.httpOptions)?void 0:t.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));const i={};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 Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const t=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!t?(i.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||"global"===this.clientOptions.location?i.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&(i.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),i.apiVersion=null!=(r=this.clientOptions.apiVersion)?r:"v1beta1"}else{if(!this.clientOptions.apiKey)throw new rP({message:"API key must be set when using the Gemini API.",status:403});i.apiVersion=null!=(n=this.clientOptions.apiVersion)?n:"v1beta",i.baseUrl="https://generativelanguage.googleapis.com/"}i.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=i,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(i,e.httpOptions))}isVertexAI(){var e;return null!=(e=this.clientOptions.vertexai)&&e}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&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw Error("HTTP options are not correctly set.");let t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=new URL(this.getBaseUrl());return e.protocol="http:"==e.protocol?"ws":"wss",e.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,r){let n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),""!==e&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===eG.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(let[t,r]of Object.entries(e.queryParams))n.searchParams.append(t,String(r));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.unaryApiCall(n,i,e.httpMethod)}patchHttpOptions(e,t){let r=JSON.parse(JSON.stringify(e));for(let[e,n]of Object.entries(t))"object"==typeof n?r[e]=Object.assign(Object.assign({},r[e]),n):void 0!==n&&(r[e]=n);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);n.searchParams.has("alt")&&"sse"===n.searchParams.get("alt")||n.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.streamApiCall(n,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,r,n){if(t&&t.timeout||n){let r=new AbortController,i=r.signal;if(t.timeout&&(null==t?void 0:t.timeout)>0){let e=setTimeout(()=>r.abort(),t.timeout);e&&"function"==typeof e.unref&&e.unref()}n&&n.addEventListener("abort",()=>{r.abort()}),e.signal=i}return t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let r={};if("string"==typeof e.body&&e.body.length>0)try{let t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");r=t}catch(e){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}e.body=JSON.stringify(function e(t,r){let n=Object.assign({},t);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)){let i=r[t],o=n[t];i&&"object"==typeof i&&!Array.isArray(i)&&o&&"object"==typeof o&&!Array.isArray(o)?n[t]=e(o,i):(o&&i&&typeof o!=typeof i&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${t}". Original type: ${typeof o}, New type: ${typeof i}. Overwriting.`),n[t]=i)}return n}(r,t))}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await r1(e),new tT(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}async streamApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await r1(e),this.processStreamResponse(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}processStreamResponse(e){return rO(this,arguments,function*(){var t;let r=null==(t=null==e?void 0:e.body)?void 0:t.getReader(),n=new TextDecoder("utf-8");if(!r)throw Error("Response body is empty");try{let t="",i="data:",o=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:s,value:a}=yield rC(r.read());if(s){if(t.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let l=n.decode(a,{stream:!0});try{let e=JSON.parse(l);if("error"in e){let t=JSON.parse(JSON.stringify(e.error)),r=t.status,n=t.code,i=`got status: ${r}. ${JSON.stringify(e)}`;if(n>=400&&n<600)throw new rP({message:i,status:n})}}catch(e){if("ApiError"===e.name)throw e}t+=l;let u=-1,c=0;for(;;){for(let e of(u=-1,c=0,o)){let r=t.indexOf(e);-1!==r&&(-1===u||r{let r=await fetch(e,t);if(r.ok)return r;if(rZ.includes(r.status))throw Error(`Retryable HTTP Error: ${r.statusText}`);throw new ta.AbortError(`Non-retryable exception ${r.statusText} sending request`)};return(0,ta.default)(i,{retries:(null!=(r=n.attempts)?r:5)-1})}getDefaultHeaders(){let e={},t="google-genai-sdk/1.43.0 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[rQ]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){let r=new Headers;if(e&&e.headers){for(let[t,n]of Object.entries(e.headers))r.append(t,n);e.timeout&&e.timeout>0&&r.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(r,t),r}getFileName(e){var t;let r="";return"string"==typeof e&&(r=null!=(t=(r=e.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?t:""),r}async uploadFile(e,t){var r;let n={};null!=t&&(n.mimeType=t.mimeType,n.name=t.name,n.displayName=t.displayName),n.name&&!n.name.startsWith("files/")&&(n.name=`files/${n.name}`);let i=this.clientOptions.uploader,o=await i.stat(e);n.sizeBytes=String(o.size);let s=null!=(r=null==t?void 0:t.mimeType)?r:o.type;if(void 0===s||""===s)throw Error("Can not determine mimeType. Please provide mimeType in the config.");n.mimeType=s;let a={file:n},l=this.getFileName(e),u=tg("upload/v1beta/files",a._url),c=await this.fetchUploadUrl(u,n.sizeBytes,n.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,c,this)}async uploadFileToFileSearchStore(e,t,r){var n;let i=this.clientOptions.uploader,o=await i.stat(t),s=String(o.size),a=null!=(n=null==r?void 0:r.mimeType)?n:o.type;if(void 0===a||""===a)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=r&&rX(r,c);let d=await this.fetchUploadUrl(l,s,a,u,c,null==r?void 0:r.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){let t=this.clientOptions.downloader;await t.download(e,this)}async fetchUploadUrl(e,t,r,n,i,o){var s;let a={};a=o||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${r}`},n?{"X-Goog-Upload-File-Name":n}:{})};let l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=null==(s=null==l?void 0:l.headers)?void 0:s["x-goog-upload-url"];if(void 0===u)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}}async function r1(e){var t;if(void 0===e)throw Error("response is undefined");if(!e.ok){let r=e.status,n=JSON.stringify((null==(t=e.headers.get("content-type"))?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}});if(r>=400&&r<600)throw new rP({message:n,status:r});throw Error(n)}}function r2(e){for(let r of e){var t;if(null!==(t=r)&&"object"==typeof t&&t instanceof r6||"object"==typeof r&&"inputSchema"in r)return!0}return!1}function r4(e){var t;let r=null!=(t=e[rQ])?t:"";e[rQ]=(r+" mcp_used/unknown").trimStart()}class r6{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new r6(e,t)}async initialize(){var e,t,r,n;if(this.mcpTools.length>0)return;let i={},o=[];for(let u of this.mcpClients)try{for(var s,a=!0,l=(t=void 0,rI(function(e){return rO(this,arguments,function*(e,t=100){let r,n=0;for(;n{},c=new Promise(e=>{u=e}),d=e.callbacks,p=this.apiClient,h={onopen:function(){u({})},onmessage:e=>{r8(p,d.onmessage,e)},onerror:null!=(t=null==d?void 0:d.onerror)?t:function(e){},onclose:null!=(r=null==d?void 0:d.onclose)?r:function(e){}},f=this.webSocketFactory.create(l,(n={},s.forEach((e,t)=>{n[t]=e}),n),h);f.connect(),await c;let m=tz(this.apiClient,e.model);return f.send(JSON.stringify({setup:{model:m}})),new r3(f,this.apiClient)}}class r3{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let t=function(e){let t={},r=t_(e,["weightedPrompts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){let t,r;e.musicGenerationConfig||(e.musicGenerationConfig={});let n=(t={},null!=(r=t_(e,["musicGenerationConfig"]))&&ty(t,["musicGenerationConfig"],r),t);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){this.conn.send(JSON.stringify({playbackControl:e}))}play(){this.sendPlaybackControl(to.PLAY)}pause(){this.sendPlaybackControl(to.PAUSE)}stop(){this.sendPlaybackControl(to.STOP)}resetContext(){this.sendPlaybackControl(to.RESET_CONTEXT)}close(){this.conn.close()}}async function r7(e,t,r){let n=new tW,i=JSON.parse(r.data instanceof Blob?await r.data.text():r.data instanceof ArrayBuffer?new TextDecoder().decode(r.data):r.data);if(e.isVertexAI()){let e,t,r,o,s,a,l,u,c,d,p,h;Object.assign(n,(e={},null!=(t=t_(i,["setupComplete"]))&&ty(e,["setupComplete"],t),null!=(r=t_(i,["serverContent"]))&&ty(e,["serverContent"],r),null!=(o=t_(i,["toolCall"]))&&ty(e,["toolCall"],o),null!=(s=t_(i,["toolCallCancellation"]))&&ty(e,["toolCallCancellation"],s),null!=(a=t_(i,["usageMetadata"]))&&ty(e,["usageMetadata"],function(e){let t={},r=t_(e,["promptTokenCount"]);null!=r&&ty(t,["promptTokenCount"],r);let n=t_(e,["cachedContentTokenCount"]);null!=n&&ty(t,["cachedContentTokenCount"],n);let i=t_(e,["candidatesTokenCount"]);null!=i&&ty(t,["responseTokenCount"],i);let o=t_(e,["toolUsePromptTokenCount"]);null!=o&&ty(t,["toolUsePromptTokenCount"],o);let s=t_(e,["thoughtsTokenCount"]);null!=s&&ty(t,["thoughtsTokenCount"],s);let a=t_(e,["totalTokenCount"]);null!=a&&ty(t,["totalTokenCount"],a);let l=t_(e,["promptTokensDetails"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["promptTokensDetails"],e)}let u=t_(e,["cacheTokensDetails"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["cacheTokensDetails"],e)}let c=t_(e,["candidatesTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["responseTokensDetails"],e)}let d=t_(e,["toolUsePromptTokensDetails"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["toolUsePromptTokensDetails"],e)}let p=t_(e,["trafficType"]);return null!=p&&ty(t,["trafficType"],p),t}(a)),null!=(l=t_(i,["goAway"]))&&ty(e,["goAway"],l),null!=(u=t_(i,["sessionResumptionUpdate"]))&&ty(e,["sessionResumptionUpdate"],u),null!=(c=t_(i,["voiceActivityDetectionSignal"]))&&ty(e,["voiceActivityDetectionSignal"],c),null!=(d=t_(i,["voiceActivity"]))&&ty(e,["voiceActivity"],(p={},null!=(h=t_(d,["type"]))&&ty(p,["voiceActivityType"],h),p)),e))}else Object.assign(n,i);t(n)}class r9{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r,this.music=new r5(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,r,n,i,o,s,a,l;let u,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),p=this.apiClient.getApiVersion(),h=this.apiClient.getHeaders();e.config&&e.config.tools&&r2(e.config.tools)&&r4(h);let f=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(h);if(this.apiClient.isVertexAI()){let e=this.apiClient.getProject(),t=this.apiClient.getLocation(),r=this.apiClient.getApiKey();this.apiClient.getCustomBaseUrl()&&!(e&&t||r)?u=d:(u=`${d}/ws/google.cloud.aiplatform.${p}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u))}else{let e=this.apiClient.getApiKey(),t="BidiGenerateContent",r="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==p&&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."),t="BidiGenerateContentConstrained",r="access_token"),u=`${d}/ws/google.ai.generativelanguage.${p}.GenerativeService.${t}?${r}=${e}`}let m=()=>{},g=new Promise(e=>{m=e}),y=e.callbacks,_=this.apiClient,E={onopen:function(){var e;null==(e=null==y?void 0:y.onopen)||e.call(y),m({})},onmessage:e=>{r7(_,y.onmessage,e)},onerror:null!=(t=null==y?void 0:y.onerror)?t:function(e){},onclose:null!=(r=null==y?void 0:y.onclose)?r:function(e){}},v=this.webSocketFactory.create(u,(c={},f.forEach((e,t)=>{c[t]=e}),c),E);v.connect(),await g;let T=tz(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&T.startsWith("publishers/")){let e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(T=`projects/${e}/locations/${t}/`+T)}let A={};this.apiClient.isVertexAI()&&(null==(n=e.config)?void 0:n.responseModalities)===void 0&&(void 0===e.config?e.config={responseModalities:[eP.AUDIO]}:e.config.responseModalities=[eP.AUDIO]),(null==(i=e.config)?void 0:i.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=null!=(s=null==(o=e.config)?void 0:o.tools)?s:[],b=[];for(let e of S)this.isCallableTool(e)?b.push(await e.tool()):b.push(e);b.length>0&&(e.config.tools=b);let C={model:T,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI()){let e,t,r;a=this.apiClient,e={},null!=(t=t_(C,["model"]))&&ty(e,["setup","model"],tz(a,t)),null!=(r=t_(C,["config"]))&&ty(e,["config"],function(e,t){let r=t_(e,["generationConfig"]);void 0!==t&&null!=r&&ty(t,["setup","generationConfig"],function(e){let t={},r=t_(e,["modelSelectionConfig"]);null!=r&&ty(t,["modelConfig"],r);let n=t_(e,["responseJsonSchema"]);null!=n&&ty(t,["responseJsonSchema"],n);let i=t_(e,["audioTimestamp"]);null!=i&&ty(t,["audioTimestamp"],i);let o=t_(e,["candidateCount"]);null!=o&&ty(t,["candidateCount"],o);let s=t_(e,["enableAffectiveDialog"]);null!=s&&ty(t,["enableAffectiveDialog"],s);let a=t_(e,["frequencyPenalty"]);null!=a&&ty(t,["frequencyPenalty"],a);let l=t_(e,["logprobs"]);null!=l&&ty(t,["logprobs"],l);let u=t_(e,["maxOutputTokens"]);null!=u&&ty(t,["maxOutputTokens"],u);let c=t_(e,["mediaResolution"]);null!=c&&ty(t,["mediaResolution"],c);let d=t_(e,["presencePenalty"]);null!=d&&ty(t,["presencePenalty"],d);let p=t_(e,["responseLogprobs"]);null!=p&&ty(t,["responseLogprobs"],p);let h=t_(e,["responseMimeType"]);null!=h&&ty(t,["responseMimeType"],h);let f=t_(e,["responseModalities"]);null!=f&&ty(t,["responseModalities"],f);let m=t_(e,["responseSchema"]);null!=m&&ty(t,["responseSchema"],m);let g=t_(e,["routingConfig"]);null!=g&&ty(t,["routingConfig"],g);let y=t_(e,["seed"]);null!=y&&ty(t,["seed"],y);let _=t_(e,["speechConfig"]);null!=_&&ty(t,["speechConfig"],_);let E=t_(e,["stopSequences"]);null!=E&&ty(t,["stopSequences"],E);let v=t_(e,["temperature"]);null!=v&&ty(t,["temperature"],v);let T=t_(e,["thinkingConfig"]);null!=T&&ty(t,["thinkingConfig"],T);let A=t_(e,["topK"]);null!=A&&ty(t,["topK"],A);let S=t_(e,["topP"]);if(null!=S&&ty(t,["topP"],S),void 0!==t_(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}(r));let n=t_(e,["responseModalities"]);void 0!==t&&null!=n&&ty(t,["setup","generationConfig","responseModalities"],n);let i=t_(e,["temperature"]);void 0!==t&&null!=i&&ty(t,["setup","generationConfig","temperature"],i);let o=t_(e,["topP"]);void 0!==t&&null!=o&&ty(t,["setup","generationConfig","topP"],o);let s=t_(e,["topK"]);void 0!==t&&null!=s&&ty(t,["setup","generationConfig","topK"],s);let a=t_(e,["maxOutputTokens"]);void 0!==t&&null!=a&&ty(t,["setup","generationConfig","maxOutputTokens"],a);let l=t_(e,["mediaResolution"]);void 0!==t&&null!=l&&ty(t,["setup","generationConfig","mediaResolution"],l);let u=t_(e,["seed"]);void 0!==t&&null!=u&&ty(t,["setup","generationConfig","seed"],u);let c=t_(e,["speechConfig"]);void 0!==t&&null!=c&&ty(t,["setup","generationConfig","speechConfig"],rr(c));let d=t_(e,["thinkingConfig"]);void 0!==t&&null!=d&&ty(t,["setup","generationConfig","thinkingConfig"],d);let p=t_(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&ty(t,["setup","generationConfig","enableAffectiveDialog"],p);let h=t_(e,["systemInstruction"]);void 0!==t&&null!=h&&ty(t,["setup","systemInstruction"],t3(h));let f=t_(e,["tools"]);if(void 0!==t&&null!=f){let e=ri(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["retrieval"]);null!=r&&ty(t,["retrieval"],r);let n=t_(e,["computerUse"]);if(null!=n&&ty(t,["computerUse"],n),void 0!==t_(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],i);let o=t_(e,["codeExecution"]);null!=o&&ty(t,["codeExecution"],o);let s=t_(e,["enterpriseWebSearch"]);null!=s&&ty(t,["enterpriseWebSearch"],s);let a=t_(e,["functionDeclarations"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=t_(e,["description"]);null!=r&&ty(t,["description"],r);let n=t_(e,["name"]);null!=n&&ty(t,["name"],n);let i=t_(e,["parameters"]);null!=i&&ty(t,["parameters"],i);let o=t_(e,["parametersJsonSchema"]);null!=o&&ty(t,["parametersJsonSchema"],o);let s=t_(e,["response"]);null!=s&&ty(t,["response"],s);let a=t_(e,["responseJsonSchema"]);if(null!=a&&ty(t,["responseJsonSchema"],a),void 0!==t_(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");return t})(e))),ty(t,["functionDeclarations"],e)}let l=t_(e,["googleMaps"]);null!=l&&ty(t,["googleMaps"],l);let u=t_(e,["googleSearchRetrieval"]);null!=u&&ty(t,["googleSearchRetrieval"],u);let c=t_(e,["urlContext"]);if(null!=c&&ty(t,["urlContext"],c),void 0!==t_(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Vertex AI.");return t})(rn(e)))),ty(t,["setup","tools"],e)}let m=t_(e,["sessionResumption"]);void 0!==t&&null!=m&&ty(t,["setup","sessionResumption"],m);let g=t_(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&ty(t,["setup","inputAudioTranscription"],g);let y=t_(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&ty(t,["setup","outputAudioTranscription"],y);let _=t_(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&ty(t,["setup","realtimeInputConfig"],_);let E=t_(e,["contextWindowCompression"]);void 0!==t&&null!=E&&ty(t,["setup","contextWindowCompression"],E);let v=t_(e,["proactivity"]);void 0!==t&&null!=v&&ty(t,["setup","proactivity"],v);let T=t_(e,["explicitVadSignal"]);return void 0!==t&&null!=T&&ty(t,["setup","explicitVadSignal"],T),{}}(r,e)),A=e}else{let e,t,r;l=this.apiClient,e={},null!=(t=t_(C,["model"]))&&ty(e,["setup","model"],tz(l,t)),null!=(r=t_(C,["config"]))&&ty(e,["config"],function(e,t){let r=t_(e,["generationConfig"]);void 0!==t&&null!=r&&ty(t,["setup","generationConfig"],r);let n=t_(e,["responseModalities"]);void 0!==t&&null!=n&&ty(t,["setup","generationConfig","responseModalities"],n);let i=t_(e,["temperature"]);void 0!==t&&null!=i&&ty(t,["setup","generationConfig","temperature"],i);let o=t_(e,["topP"]);void 0!==t&&null!=o&&ty(t,["setup","generationConfig","topP"],o);let s=t_(e,["topK"]);void 0!==t&&null!=s&&ty(t,["setup","generationConfig","topK"],s);let a=t_(e,["maxOutputTokens"]);void 0!==t&&null!=a&&ty(t,["setup","generationConfig","maxOutputTokens"],a);let l=t_(e,["mediaResolution"]);void 0!==t&&null!=l&&ty(t,["setup","generationConfig","mediaResolution"],l);let u=t_(e,["seed"]);void 0!==t&&null!=u&&ty(t,["setup","generationConfig","seed"],u);let c=t_(e,["speechConfig"]);void 0!==t&&null!=c&&ty(t,["setup","generationConfig","speechConfig"],rr(c));let d=t_(e,["thinkingConfig"]);void 0!==t&&null!=d&&ty(t,["setup","generationConfig","thinkingConfig"],d);let p=t_(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&ty(t,["setup","generationConfig","enableAffectiveDialog"],p);let h=t_(e,["systemInstruction"]);void 0!==t&&null!=h&&ty(t,["setup","systemInstruction"],function(e){let t={},r=t_(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p,h;return r={},null!=(n=t_(t=e,["mediaResolution"]))&&ty(r,["mediaResolution"],n),null!=(i=t_(t,["codeExecutionResult"]))&&ty(r,["codeExecutionResult"],i),null!=(o=t_(t,["executableCode"]))&&ty(r,["executableCode"],o),null!=(s=t_(t,["fileData"]))&&ty(r,["fileData"],function(e){let t={};if(void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=t_(e,["fileUri"]);null!=r&&ty(t,["fileUri"],r);let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(s)),null!=(a=t_(t,["functionCall"]))&&ty(r,["functionCall"],function(e){let t={},r=t_(e,["id"]);null!=r&&ty(t,["id"],r);let n=t_(e,["args"]);null!=n&&ty(t,["args"],n);let i=t_(e,["name"]);if(null!=i&&ty(t,["name"],i),void 0!==t_(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==t_(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=t_(t,["functionResponse"]))&&ty(r,["functionResponse"],l),null!=(u=t_(t,["inlineData"]))&&ty(r,["inlineData"],rU(u)),null!=(c=t_(t,["text"]))&&ty(r,["text"],c),null!=(d=t_(t,["thought"]))&&ty(r,["thought"],d),null!=(p=t_(t,["thoughtSignature"]))&&ty(r,["thoughtSignature"],p),null!=(h=t_(t,["videoMetadata"]))&&ty(r,["videoMetadata"],h),r})),ty(t,["parts"],e)}let n=t_(e,["role"]);return null!=n&&ty(t,["role"],n),t}(t3(h)));let f=t_(e,["tools"]);if(void 0!==t&&null!=f){let e=ri(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==t_(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let r=t_(e,["computerUse"]);null!=r&&ty(t,["computerUse"],r);let n=t_(e,["fileSearch"]);null!=n&&ty(t,["fileSearch"],n);let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],function(e){let t={},r=t_(e,["searchTypes"]);if(null!=r&&ty(t,["searchTypes"],r),void 0!==t_(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==t_(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let n=t_(e,["timeRangeFilter"]);return null!=n&&ty(t,["timeRangeFilter"],n),t}(i));let o=t_(e,["codeExecution"]);if(null!=o&&ty(t,["codeExecution"],o),void 0!==t_(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let s=t_(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["functionDeclarations"],e)}let a=t_(e,["googleMaps"]);null!=a&&ty(t,["googleMaps"],function(e){let t={};if(void 0!==t_(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=t_(e,["enableWidget"]);return null!=r&&ty(t,["enableWidget"],r),t}(a));let l=t_(e,["googleSearchRetrieval"]);null!=l&&ty(t,["googleSearchRetrieval"],l);let u=t_(e,["urlContext"]);null!=u&&ty(t,["urlContext"],u);let c=t_(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["mcpServers"],e)}return t})(rn(e)))),ty(t,["setup","tools"],e)}let m=t_(e,["sessionResumption"]);void 0!==t&&null!=m&&ty(t,["setup","sessionResumption"],function(e){let t={},r=t_(e,["handle"]);if(null!=r&&ty(t,["handle"],r),void 0!==t_(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=t_(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&ty(t,["setup","inputAudioTranscription"],g);let y=t_(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&ty(t,["setup","outputAudioTranscription"],y);let _=t_(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&ty(t,["setup","realtimeInputConfig"],_);let E=t_(e,["contextWindowCompression"]);void 0!==t&&null!=E&&ty(t,["setup","contextWindowCompression"],E);let v=t_(e,["proactivity"]);if(void 0!==t&&null!=v&&ty(t,["setup","proactivity"],v),void 0!==t_(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(r,e)),A=e}return delete A.config,v.send(JSON.stringify(A)),new nt(v,this.apiClient)}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}}let ne={turnComplete:!0};class nt{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let r=[];try{r=t9(t.turns),e.isVertexAI()||(r=r.map(e=>rD(e)))}catch(e){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:r,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let r=[];if(null==t.functionResponses||0===(r=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses]).length)throw Error("functionResponses is required.");for(let t of r){if("object"!=typeof t||null===t||!("name"in t)||!("response"in t))throw Error(`Could not parse function response, type '${typeof t}'.`);if(!e.isVertexAI()&&!("id"in t))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},ne),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:function(e){let t={},r=t_(e,["media"]);if(null!=r){let e=tQ(r);Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["mediaChunks"],e)}let n=t_(e,["audio"]);null!=n&&ty(t,["audio"],t1(n));let i=t_(e,["audioStreamEnd"]);null!=i&&ty(t,["audioStreamEnd"],i);let o=t_(e,["video"]);null!=o&&ty(t,["video"],t0(o));let s=t_(e,["text"]);null!=s&&ty(t,["text"],s);let a=t_(e,["activityStart"]);null!=a&&ty(t,["activityStart"],a);let l=t_(e,["activityEnd"]);return null!=l&&ty(t,["activityEnd"],l),t}(e)}:{realtimeInput:function(e){let t={},r=t_(e,["media"]);if(null!=r){let e=tQ(r);Array.isArray(e)&&(e=e.map(e=>rU(e))),ty(t,["mediaChunks"],e)}let n=t_(e,["audio"]);null!=n&&ty(t,["audio"],rU(t1(n)));let i=t_(e,["audioStreamEnd"]);null!=i&&ty(t,["audioStreamEnd"],i);let o=t_(e,["video"]);null!=o&&ty(t,["video"],rU(t0(o)));let s=t_(e,["text"]);null!=s&&ty(t,["text"],s);let a=t_(e,["activityStart"]);null!=a&&ty(t,["activityStart"],a);let l=t_(e,["activityEnd"]);return null!=l&&ty(t,["activityEnd"],l),t}(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function nr(e){var t,r,n;if(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.disable)return!0;let i=!1;for(let t of null!=(r=null==e?void 0:e.tools)?r:[])if(nn(t)){i=!0;break}if(!i)return!0;let o=null==(n=null==e?void 0:e.automaticFunctionCalling)?void 0:n.maximumRemoteCalls;return(!(!o||!(o<0)&&Number.isInteger(o))||0==o)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",o),!0)}function nn(e){return"callTool"in e&&"function"==typeof e.callTool}function ni(e){var t;let r=[];return(null==(t=null==e?void 0:e.config)?void 0:t.tools)&&e.config.tools.forEach((e,t)=>{nn(e)||e.functionDeclarations&&e.functionDeclarations.length>0&&r.push(t)}),r}function no(e){var t;return!(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.ignoreCallHistory)}class ns extends tm{constructor(e){super(),this.apiClient=e,this.embedContent=async e=>{if(!this.apiClient.isVertexAI())return await this.embedContentInternal(e);if(e.model.includes("gemini")&&"gemini-embedding-001"!==e.model||e.model.includes("maas")){let t=t9(e.contents);if(t.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let r=Object.assign(Object.assign({},e),{content:t[0],embeddingApiType:eB.EMBED_CONTENT});return await this.embedContentInternal(r)}{let t=Object.assign(Object.assign({},e),{embeddingApiType:eB.PREDICT});return await this.embedContentInternal(t)}},this.generateContent=async e=>{var t,r,n,i,o,s,a,l;let u,c,d=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!(null!=(l=null==(a=null==(s=e.config)?void 0:s.tools)?void 0:a.some(e=>nn(e)))&&l)||nr(e.config))return await this.generateContentInternal(d);let p=ni(e);if(p.length>0){let e=p.map(e=>`tools[${e}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let h=t9(d.contents),f=null!=(n=null==(r=null==(t=d.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,m=0;for(;m{var t,r,n,i,o;if(this.maybeMoveToResponseJsonSchem(e),nr(e.config)){let t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}let s=ni(e);if(s.length>0){let e=s.map(e=>`tools[${e}]`).join(", ");throw Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let a=null==(n=null==(r=null==(t=null==e?void 0:e.config)?void 0:t.toolConfig)?void 0:r.functionCallingConfig)?void 0:n.streamFunctionCallArguments,l=null==(o=null==(i=null==e?void 0:e.config)?void 0:i.automaticFunctionCalling)?void 0:o.disable;if(a&&!l)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{var t;let r,n=[];if(null==e?void 0:e.generatedImages)for(let i of e.generatedImages)i&&(null==i?void 0:i.safetyAttributes)&&(null==(t=null==i?void 0:i.safetyAttributes)?void 0:t.contentType)==="Positive Prompt"?r=null==i?void 0:i.safetyAttributes:n.push(i);return r?{generatedImages:n,positivePromptSafetyAttributes:r,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:n,sdkHttpResponse:e.sdkHttpResponse}}),this.list=async e=>{var t;let r={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!r.config.queryBase)if(null==(t=r.config)?void 0:t.filter)throw Error("Filtering tuned models list for Vertex AI is not currently supported");else r.config.filter="labels.tune-type:*";return new rv(ts.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(r),r)},this.editImage=async e=>{let t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));let r={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(r)},this.generateVideos=async e=>{var t,r,n,i,o,s;if((e.prompt||e.image||e.video)&&e.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return!this.apiClient.isVertexAI()&&((null==(t=e.video)?void 0:t.uri)&&(null==(r=e.video)?void 0:r.videoBytes)?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:(null==(i=null==(n=e.source)?void 0:n.video)?void 0:i.uri)&&(null==(s=null==(o=e.source)?void 0:o.video)?void 0:s.videoBytes)&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}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 t,r,n;let i=null==(t=e.config)?void 0:t.tools;if(!i)return e;let o=await Promise.all(i.map(async e=>nn(e)?await e.tool():e)),s={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:o})};if(s.config.tools=o,e.config&&e.config.tools&&r2(e.config.tools)){let t=Object.assign({},null!=(n=null==(r=e.config.httpOptions)?void 0:r.headers)?n:{});0===Object.keys(t).length&&(t=this.apiClient.getDefaultHeaders()),r4(t),s.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:t})}return s}async initAfcToolsMap(e){var t,r,n;let i=new Map;for(let o of null!=(r=null==(t=e.config)?void 0:t.tools)?r:[])if(nn(o))for(let e of null!=(n=(await o.tool()).functionDeclarations)?n:[]){if(!e.name)throw Error("Function declaration name is required.");if(i.has(e.name))throw Error(`Duplicate tool declaration name: ${e.name}`);i.set(e.name,o)}return i}async processAfcStream(e){var t,r,n;let i=null!=(n=null==(r=null==(t=e.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,o=!1,s=0;return function(e,t,r){return rO(this,arguments,function*(){for(;s0){o=!0;let e=new tA;e.candidates=[{content:{role:"user",parts:y}}],yield yield rC(e);let t=[];t.push(..._),t.push({role:"user",parts:y});let n=t9(r.contents).concat(t);r.contents=n}else break}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n=rL(this.apiClient,e);return o=tg("{model}:generateContent",n._url),s=n._query,delete n._url,delete n._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rG(e),r=new tA;return Object.assign(r,t),r})}{let t=rM(this.apiClient,e);return o=tg("{model}:generateContent",t._url),s=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rj(e),r=new tA;return Object.assign(r,t),r})}}async generateContentStreamInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n=rL(this.apiClient,e);return o=tg("{model}:streamGenerateContent?alt=sse",n._url),s=n._query,delete n._url,delete n._query,this.apiClient.requestStream({path:o,queryParams:s,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(function(t){return rO(this,arguments,function*(){var r,n,i,o;try{for(var s,a=!0,l=rI(t);!(r=(s=yield rC(l.next())).done);a=!0){o=s.value,a=!1;let t=rG((yield rC(o.json())),e);t.sdkHttpResponse={headers:o.headers};let r=new tA;Object.assign(r,t),yield yield rC(r)}}catch(e){n={error:e}}finally{try{!a&&!r&&(i=l.return)&&(yield rC(i.call(l)))}finally{if(n)throw n.error}}})})}{let t=rM(this.apiClient,e);return o=tg("{model}:streamGenerateContent?alt=sse",t._url),s=t._query,delete t._url,delete t._query,this.apiClient.requestStream({path:o,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(function(t){return rO(this,arguments,function*(){var r,n,i,o;try{for(var s,a=!0,l=rI(t);!(r=(s=yield rC(l.next())).done);a=!0){o=s.value,a=!1;let t=rj((yield rC(o.json())),e);t.sdkHttpResponse={headers:o.headers};let r=new tA;Object.assign(r,t),yield yield rC(r)}}catch(e){n={error:e}}finally{try{!a&&!r&&(i=l.return)&&(yield rC(i.call(l)))}finally{if(n)throw n.error}}})})}}async embedContentInternal(e){var t,r,n,i,o;let s="",a={};if(this.apiClient.isVertexAI()){let n=function(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(r,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){let r=t_(t,["contents"]);if(null!=r){let t=t7(e,r);Array.isArray(t)&&(t=t.map(e=>e)),ty(n,["instances[]","content"],t)}}let s=t_(r,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"EMBED_CONTENT"===s){let e=t_(t,["content"]);null!=e&&ty(n,["content"],t3(e))}let a=t_(t,["config"]);return null!=a&&function(e,t,r){let n=t_(r,["embeddingApiType"]);if(void 0===n&&(n="PREDICT"),"PREDICT"===n){let r=t_(e,["taskType"]);void 0!==t&&null!=r&&ty(t,["instances[]","task_type"],r)}else if("EMBED_CONTENT"===n){let r=t_(e,["taskType"]);void 0!==t&&null!=r&&ty(t,["taskType"],r)}let i=t_(r,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"PREDICT"===i){let r=t_(e,["title"]);void 0!==t&&null!=r&&ty(t,["instances[]","title"],r)}else if("EMBED_CONTENT"===i){let r=t_(e,["title"]);void 0!==t&&null!=r&&ty(t,["title"],r)}let o=t_(r,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){let r=t_(e,["outputDimensionality"]);void 0!==t&&null!=r&&ty(t,["parameters","outputDimensionality"],r)}else if("EMBED_CONTENT"===o){let r=t_(e,["outputDimensionality"]);void 0!==t&&null!=r&&ty(t,["outputDimensionality"],r)}let s=t_(r,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){let r=t_(e,["mimeType"]);void 0!==t&&null!=r&&ty(t,["instances[]","mimeType"],r)}let a=t_(r,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"PREDICT"===a){let r=t_(e,["autoTruncate"]);void 0!==t&&null!=r&&ty(t,["parameters","autoTruncate"],r)}else if("EMBED_CONTENT"===a){let r=t_(e,["autoTruncate"]);void 0!==t&&null!=r&&ty(t,["autoTruncate"],r)}}(a,n,r),n}(this.apiClient,e,e);return s=tg((o=e.model).includes("gemini")&&"gemini-embedding-001"!==o||o.includes("maas")?"{model}:embedContent":"{model}:predict",n._url),a=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(t=>{let r=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["predictions[]","embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a;return r={},null!=(n=t_(e,["values"]))&&ty(r,["values"],n),null!=(i=t_(e,["statistics"]))&&ty(r,["statistics"],(o={},null!=(s=t_(t=i,["truncated"]))&&ty(o,["truncated"],s),null!=(a=t_(t,["token_count"]))&&ty(o,["tokenCount"],a),o)),r})),ty(r,["embeddings"],e)}let o=t_(e,["metadata"]);if(null!=o&&ty(r,["metadata"],o),t&&"EMBED_CONTENT"===t_(t,["embeddingApiType"])){let t=t_(e,["embedding"]),n=t_(e,["usageMetadata"]),i=t_(e,["truncated"]);if(t){let e={};n&&n.promptTokenCount&&(e.tokenCount=n.promptTokenCount),i&&(e.truncated=i),t.statistics=e,ty(r,["embeddings"],[t])}}return r}(t,e),n=new tS;return Object.assign(n,r),n})}{let t=function(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let t=t7(e,o);Array.isArray(t)&&(t=t.map(e=>e)),ty(n,["requests[]","content"],t)}let s=t_(t,["content"]);null!=s&&rD(t3(s));let a=t_(t,["config"]);null!=a&&function(e,t,r){let n=t_(e,["taskType"]);void 0!==t&&null!=n&&ty(t,["requests[]","taskType"],n);let i=t_(e,["title"]);void 0!==t&&null!=i&&ty(t,["requests[]","title"],i);let o=t_(e,["outputDimensionality"]);if(void 0!==t&&null!=o&&ty(t,["requests[]","outputDimensionality"],o),void 0!==t_(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==t_(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.")}(a,n);let l=t_(t,["model"]);return void 0!==l&&ty(n,["requests[]","model"],tz(e,l)),n}(this.apiClient,e);return s=tg("{model}:batchEmbedContents",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["embeddings"],e)}let o=t_(e,["metadata"]);return null!=o&&ty(r,["metadata"],o),r}(e),r=new tS;return Object.assign(r,t),r})}}async generateImagesInternal(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s,u,c,d,p,h,f,m,g,y,_,E,v,T,A,S,b,C,O,I=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["_url","model"],tz(o,i)),null!=(s=t_(e,["prompt"]))&&ty(n,["instances[0]","prompt"],s),null!=(u=t_(e,["config"]))&&(c=t_(u,["outputGcsUri"]),void 0!==n&&null!=c&&ty(n,["parameters","storageUri"],c),d=t_(u,["negativePrompt"]),void 0!==n&&null!=d&&ty(n,["parameters","negativePrompt"],d),p=t_(u,["numberOfImages"]),void 0!==n&&null!=p&&ty(n,["parameters","sampleCount"],p),h=t_(u,["aspectRatio"]),void 0!==n&&null!=h&&ty(n,["parameters","aspectRatio"],h),f=t_(u,["guidanceScale"]),void 0!==n&&null!=f&&ty(n,["parameters","guidanceScale"],f),m=t_(u,["seed"]),void 0!==n&&null!=m&&ty(n,["parameters","seed"],m),g=t_(u,["safetyFilterLevel"]),void 0!==n&&null!=g&&ty(n,["parameters","safetySetting"],g),y=t_(u,["personGeneration"]),void 0!==n&&null!=y&&ty(n,["parameters","personGeneration"],y),_=t_(u,["includeSafetyAttributes"]),void 0!==n&&null!=_&&ty(n,["parameters","includeSafetyAttributes"],_),E=t_(u,["includeRaiReason"]),void 0!==n&&null!=E&&ty(n,["parameters","includeRaiReason"],E),v=t_(u,["language"]),void 0!==n&&null!=v&&ty(n,["parameters","language"],v),T=t_(u,["outputMimeType"]),void 0!==n&&null!=T&&ty(n,["parameters","outputOptions","mimeType"],T),A=t_(u,["outputCompressionQuality"]),void 0!==n&&null!=A&&ty(n,["parameters","outputOptions","compressionQuality"],A),S=t_(u,["addWatermark"]),void 0!==n&&null!=S&&ty(n,["parameters","addWatermark"],S),b=t_(u,["labels"]),void 0!==n&&null!=b&&ty(n,["labels"],b),C=t_(u,["imageSize"]),void 0!==n&&null!=C&&ty(n,["parameters","sampleImageSize"],C),O=t_(u,["enhancePrompt"]),void 0!==n&&null!=O&&ty(n,["parameters","enhancePrompt"],O)),n);return a=tg("{model}:predict",I._url),l=I._query,delete I._url,delete I._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(I),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["predictions"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rF(e))),ty(r,["generatedImages"],e)}let o=t_(e,["positivePromptSafetyAttributes"]);return null!=o&&ty(r,["positivePromptSafetyAttributes"],rW(o)),r}(e),r=new tb;return Object.assign(r,t),r})}{let t,r,o,u,c=(s=this.apiClient,t={},null!=(r=t_(e,["model"]))&&ty(t,["_url","model"],tz(s,r)),null!=(o=t_(e,["prompt"]))&&ty(t,["instances[0]","prompt"],o),null!=(u=t_(e,["config"]))&&function(e,t,r){if(void 0!==t_(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==t_(e,["negativePrompt"]))throw Error("negativePrompt parameter is not supported in Gemini API.");let n=t_(e,["numberOfImages"]);void 0!==t&&null!=n&&ty(t,["parameters","sampleCount"],n);let i=t_(e,["aspectRatio"]);void 0!==t&&null!=i&&ty(t,["parameters","aspectRatio"],i);let o=t_(e,["guidanceScale"]);if(void 0!==t&&null!=o&&ty(t,["parameters","guidanceScale"],o),void 0!==t_(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let s=t_(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&ty(t,["parameters","safetySetting"],s);let a=t_(e,["personGeneration"]);void 0!==t&&null!=a&&ty(t,["parameters","personGeneration"],a);let l=t_(e,["includeSafetyAttributes"]);void 0!==t&&null!=l&&ty(t,["parameters","includeSafetyAttributes"],l);let u=t_(e,["includeRaiReason"]);void 0!==t&&null!=u&&ty(t,["parameters","includeRaiReason"],u);let c=t_(e,["language"]);void 0!==t&&null!=c&&ty(t,["parameters","language"],c);let d=t_(e,["outputMimeType"]);void 0!==t&&null!=d&&ty(t,["parameters","outputOptions","mimeType"],d);let p=t_(e,["outputCompressionQuality"]);if(void 0!==t&&null!=p&&ty(t,["parameters","outputOptions","compressionQuality"],p),void 0!==t_(e,["addWatermark"]))throw Error("addWatermark parameter is not supported in Gemini API.");if(void 0!==t_(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let h=t_(e,["imageSize"]);if(void 0!==t&&null!=h&&ty(t,["parameters","sampleImageSize"],h),void 0!==t_(e,["enhancePrompt"]))throw Error("enhancePrompt parameter is not supported in Gemini API.")}(u,t),t);return a=tg("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["predictions"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{var t,r;let n,i,o,s,a,l,u;return n={},null!=(i=t_(t=e,["_self"]))&&ty(n,["image"],(o={},null!=(s=t_(r=i,["bytesBase64Encoded"]))&&ty(o,["imageBytes"],tE(s)),null!=(a=t_(r,["mimeType"]))&&ty(o,["mimeType"],a),o)),null!=(l=t_(t,["raiFilteredReason"]))&&ty(n,["raiFilteredReason"],l),null!=(u=t_(t,["_self"]))&&ty(n,["safetyAttributes"],rJ(u)),n})),ty(r,["generatedImages"],e)}let o=t_(e,["positivePromptSafetyAttributes"]);return null!=o&&ty(r,["positivePromptSafetyAttributes"],rJ(o)),r}(e),r=new tb;return Object.assign(r,t),r})}}async editImageInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let o=function(e,t,r){let n,i,o,s,a,l,u,c,d,p,h,f,m,g,y,_,E,v={},T=t_(t,["model"]);null!=T&&ty(v,["_url","model"],tz(e,T));let A=t_(t,["prompt"]);null!=A&&ty(v,["instances[0]","prompt"],A);let S=t_(t,["referenceImages"]);if(null!=S){let e=S;Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r,n,i,o,s,a,l,u={},c=t_(e,["referenceImage"]);null!=c&&ty(u,["referenceImage"],rB(c));let d=t_(e,["referenceId"]);null!=d&&ty(u,["referenceId"],d);let p=t_(e,["referenceType"]);null!=p&&ty(u,["referenceType"],p);let h=t_(e,["maskImageConfig"]);null!=h&&ty(u,["maskImageConfig"],(r={},null!=(n=t_(h,["maskMode"]))&&ty(r,["maskMode"],n),null!=(i=t_(h,["segmentationClasses"]))&&ty(r,["maskClasses"],i),null!=(o=t_(h,["maskDilation"]))&&ty(r,["dilation"],o),r));let f=t_(e,["controlImageConfig"]);null!=f&&ty(u,["controlImageConfig"],(s={},null!=(a=t_(f,["controlType"]))&&ty(s,["controlType"],a),null!=(l=t_(f,["enableControlImageComputation"]))&&ty(s,["computeControl"],l),s));let m=t_(e,["styleImageConfig"]);null!=m&&ty(u,["styleImageConfig"],m);let g=t_(e,["subjectImageConfig"]);return null!=g&&ty(u,["subjectImageConfig"],g),u})(e))),ty(v,["instances[0]","referenceImages"],e)}let b=t_(t,["config"]);return null!=b&&(n=t_(b,["outputGcsUri"]),void 0!==v&&null!=n&&ty(v,["parameters","storageUri"],n),i=t_(b,["negativePrompt"]),void 0!==v&&null!=i&&ty(v,["parameters","negativePrompt"],i),o=t_(b,["numberOfImages"]),void 0!==v&&null!=o&&ty(v,["parameters","sampleCount"],o),s=t_(b,["aspectRatio"]),void 0!==v&&null!=s&&ty(v,["parameters","aspectRatio"],s),a=t_(b,["guidanceScale"]),void 0!==v&&null!=a&&ty(v,["parameters","guidanceScale"],a),l=t_(b,["seed"]),void 0!==v&&null!=l&&ty(v,["parameters","seed"],l),u=t_(b,["safetyFilterLevel"]),void 0!==v&&null!=u&&ty(v,["parameters","safetySetting"],u),c=t_(b,["personGeneration"]),void 0!==v&&null!=c&&ty(v,["parameters","personGeneration"],c),d=t_(b,["includeSafetyAttributes"]),void 0!==v&&null!=d&&ty(v,["parameters","includeSafetyAttributes"],d),p=t_(b,["includeRaiReason"]),void 0!==v&&null!=p&&ty(v,["parameters","includeRaiReason"],p),h=t_(b,["language"]),void 0!==v&&null!=h&&ty(v,["parameters","language"],h),f=t_(b,["outputMimeType"]),void 0!==v&&null!=f&&ty(v,["parameters","outputOptions","mimeType"],f),m=t_(b,["outputCompressionQuality"]),void 0!==v&&null!=m&&ty(v,["parameters","outputOptions","compressionQuality"],m),g=t_(b,["addWatermark"]),void 0!==v&&null!=g&&ty(v,["parameters","addWatermark"],g),y=t_(b,["labels"]),void 0!==v&&null!=y&&ty(v,["labels"],y),_=t_(b,["editMode"]),void 0!==v&&null!=_&&ty(v,["parameters","editMode"],_),E=t_(b,["baseSteps"]),void 0!==v&&null!=E&&ty(v,["parameters","editConfig","baseSteps"],E)),v}(this.apiClient,e);return n=tg("{model}:predict",o._url),i=o._query,delete o._url,delete o._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["predictions"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rF(e))),ty(r,["generatedImages"],e)}return r}(e),r=new tC;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,r,n;let i="",o={};if(this.apiClient.isVertexAI()){let s,a,l,u,c,d,p,h,f,m,g,y,_,E,v,T,A=(n=this.apiClient,s={},null!=(a=t_(e,["model"]))&&ty(s,["_url","model"],tz(n,a)),null!=(l=t_(e,["image"]))&&ty(s,["instances[0]","image"],rB(l)),null!=(u=t_(e,["upscaleFactor"]))&&ty(s,["parameters","upscaleConfig","upscaleFactor"],u),null!=(c=t_(e,["config"]))&&(d=t_(c,["outputGcsUri"]),void 0!==s&&null!=d&&ty(s,["parameters","storageUri"],d),p=t_(c,["safetyFilterLevel"]),void 0!==s&&null!=p&&ty(s,["parameters","safetySetting"],p),h=t_(c,["personGeneration"]),void 0!==s&&null!=h&&ty(s,["parameters","personGeneration"],h),f=t_(c,["includeRaiReason"]),void 0!==s&&null!=f&&ty(s,["parameters","includeRaiReason"],f),m=t_(c,["outputMimeType"]),void 0!==s&&null!=m&&ty(s,["parameters","outputOptions","mimeType"],m),g=t_(c,["outputCompressionQuality"]),void 0!==s&&null!=g&&ty(s,["parameters","outputOptions","compressionQuality"],g),y=t_(c,["enhanceInputImage"]),void 0!==s&&null!=y&&ty(s,["parameters","upscaleConfig","enhanceInputImage"],y),_=t_(c,["imagePreservationFactor"]),void 0!==s&&null!=_&&ty(s,["parameters","upscaleConfig","imagePreservationFactor"],_),E=t_(c,["labels"]),void 0!==s&&null!=E&&ty(s,["labels"],E),v=t_(c,["numberOfImages"]),void 0!==s&&null!=v&&ty(s,["parameters","sampleCount"],v),T=t_(c,["mode"]),void 0!==s&&null!=T&&ty(s,["parameters","mode"],T)),s);return i=tg("{model}:predict",A._url),o=A._query,delete A._url,delete A._query,this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(A),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["predictions"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rF(e))),ty(r,["generatedImages"],e)}return r}(e),r=new tO;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,r,n;let i="",o={};if(this.apiClient.isVertexAI()){let s,a,l,u,c,d,p,h,f,m,g,y,_,E,v,T=(n=this.apiClient,s={},null!=(a=t_(e,["model"]))&&ty(s,["_url","model"],tz(n,a)),null!=(l=t_(e,["source"]))&&function(e,t,r){let n=t_(e,["prompt"]);void 0!==t&&null!=n&&ty(t,["instances[0]","prompt"],n);let i=t_(e,["personImage"]);void 0!==t&&null!=i&&ty(t,["instances[0]","personImage","image"],rB(i));let o=t_(e,["productImages"]);if(void 0!==t&&null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>{let t,r;return t={},null!=(r=t_(e,["productImage"]))&&ty(t,["image"],rB(r)),t})),ty(t,["instances[0]","productImages"],e)}}(l,s),null!=(u=t_(e,["config"]))&&(c=t_(u,["numberOfImages"]),void 0!==s&&null!=c&&ty(s,["parameters","sampleCount"],c),d=t_(u,["baseSteps"]),void 0!==s&&null!=d&&ty(s,["parameters","baseSteps"],d),p=t_(u,["outputGcsUri"]),void 0!==s&&null!=p&&ty(s,["parameters","storageUri"],p),h=t_(u,["seed"]),void 0!==s&&null!=h&&ty(s,["parameters","seed"],h),f=t_(u,["safetyFilterLevel"]),void 0!==s&&null!=f&&ty(s,["parameters","safetySetting"],f),m=t_(u,["personGeneration"]),void 0!==s&&null!=m&&ty(s,["parameters","personGeneration"],m),g=t_(u,["addWatermark"]),void 0!==s&&null!=g&&ty(s,["parameters","addWatermark"],g),y=t_(u,["outputMimeType"]),void 0!==s&&null!=y&&ty(s,["parameters","outputOptions","mimeType"],y),_=t_(u,["outputCompressionQuality"]),void 0!==s&&null!=_&&ty(s,["parameters","outputOptions","compressionQuality"],_),E=t_(u,["enhancePrompt"]),void 0!==s&&null!=E&&ty(s,["parameters","enhancePrompt"],E),v=t_(u,["labels"]),void 0!==s&&null!=v&&ty(s,["labels"],v)),s);return i=tg("{model}:predict",T._url),o=T._query,delete T._url,delete T._query,this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(T),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e,t){let r={},n=t_(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rF(e))),ty(r,["generatedImages"],e)}return r}(e),r=new tI;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,r,n,i,o;let s="",a={};if(this.apiClient.isVertexAI()){let l,u,c,d,p,h,f,m,g,y,_,E,v,T,A,S=(n=this.apiClient,h={},null!=(f=t_(e,["model"]))&&ty(h,["_url","model"],tz(n,f)),null!=(m=t_(e,["source"]))&&(i=m,o=h,c=t_(i,["prompt"]),void 0!==o&&null!=c&&ty(o,["instances[0]","prompt"],c),d=t_(i,["image"]),void 0!==o&&null!=d&&ty(o,["instances[0]","image"],rB(d)),p=t_(i,["scribbleImage"]),void 0!==o&&null!=p&&ty(o,["instances[0]","scribble"],(l={},null!=(u=t_(p,["image"]))&&ty(l,["image"],rB(u)),l))),null!=(g=t_(e,["config"]))&&(y=t_(g,["mode"]),void 0!==h&&null!=y&&ty(h,["parameters","mode"],y),_=t_(g,["maxPredictions"]),void 0!==h&&null!=_&&ty(h,["parameters","maxPredictions"],_),E=t_(g,["confidenceThreshold"]),void 0!==h&&null!=E&&ty(h,["parameters","confidenceThreshold"],E),v=t_(g,["maskDilation"]),void 0!==h&&null!=v&&ty(h,["parameters","maskDilation"],v),T=t_(g,["binaryColorThreshold"]),void 0!==h&&null!=T&&ty(h,["parameters","binaryColorThreshold"],T),A=t_(g,["labels"]),void 0!==h&&null!=A&&ty(h,["labels"],A)),h);return s=tg("{model}:predict",S._url),a=S._query,delete S._url,delete S._query,this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(S),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e,t){let r={},n=t_(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e,t){let r={},n=t_(e,["_self"]);null!=n&&ty(r,["mask"],rq(n));let i=t_(e,["labels"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["labels"],e)}return r})(e))),ty(r,["generatedMasks"],e)}return r}(e),r=new tw;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async get(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["_url","name"],tz(o,i)),n);return a=tg("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>r$(e))}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["model"]))&&ty(t,["_url","name"],tz(s,r)),t);return a=tg("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rV(e))}}async listInternal(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s,u,c,d,p=(o=this.apiClient,n={},null!=(i=t_(e,["config"]))&&(s=t_(i,["pageSize"]),void 0!==n&&null!=s&&ty(n,["_query","pageSize"],s),u=t_(i,["pageToken"]),void 0!==n&&null!=u&&ty(n,["_query","pageToken"],u),c=t_(i,["filter"]),void 0!==n&&null!=c&&ty(n,["_query","filter"],c),d=t_(i,["queryBase"]),void 0!==n&&null!=d&&ty(n,["_url","models_url"],rc(o,d))),n);return a=tg("{models_url}",p._url),l=p._query,delete p._url,delete p._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(p),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["nextPageToken"]);null!=i&&ty(r,["nextPageToken"],i);let o=t_(e,["_self"]);if(null!=o){let e=rd(o);Array.isArray(e)&&(e=e.map(e=>r$(e))),ty(r,["models"],e)}return r}(e),r=new tR;return Object.assign(r,t),r})}{let t,r,o,u,c,d,p=(s=this.apiClient,t={},null!=(r=t_(e,["config"]))&&(o=t_(r,["pageSize"]),void 0!==t&&null!=o&&ty(t,["_query","pageSize"],o),u=t_(r,["pageToken"]),void 0!==t&&null!=u&&ty(t,["_query","pageToken"],u),c=t_(r,["filter"]),void 0!==t&&null!=c&&ty(t,["_query","filter"],c),d=t_(r,["queryBase"]),void 0!==t&&null!=d&&ty(t,["_url","models_url"],rc(s,d))),t);return a=tg("{models_url}",p._url),l=p._query,delete p._url,delete p._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(p),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["nextPageToken"]);null!=i&&ty(r,["nextPageToken"],i);let o=t_(e,["_self"]);if(null!=o){let e=rd(o);Array.isArray(e)&&(e=e.map(e=>rV(e))),ty(r,["models"],e)}return r}(e),r=new tR;return Object.assign(r,t),r})}}async update(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s,u,c,d,p=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["_url","model"],tz(o,i)),null!=(s=t_(e,["config"]))&&(u=t_(s,["displayName"]),void 0!==n&&null!=u&&ty(n,["displayName"],u),c=t_(s,["description"]),void 0!==n&&null!=c&&ty(n,["description"],c),d=t_(s,["defaultCheckpointId"]),void 0!==n&&null!=d&&ty(n,["defaultCheckpointId"],d)),n);return a=tg("{model}",p._url),l=p._query,delete p._url,delete p._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(p),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>r$(e))}{let t,r,o,u,c,d,p=(s=this.apiClient,t={},null!=(r=t_(e,["model"]))&&ty(t,["_url","name"],tz(s,r)),null!=(o=t_(e,["config"]))&&(u=t_(o,["displayName"]),void 0!==t&&null!=u&&ty(t,["displayName"],u),c=t_(o,["description"]),void 0!==t&&null!=c&&ty(t,["description"],c),d=t_(o,["defaultCheckpointId"]),void 0!==t&&null!=d&&ty(t,["defaultCheckpointId"],d)),t);return a=tg("{name}",p._url),l=p._query,delete p._url,delete p._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(p),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rV(e))}}async delete(e){var t,r,n,i,o,s;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,s=(o=this.apiClient,n={},null!=(i=t_(e,["model"]))&&ty(n,["_url","name"],tz(o,i)),n);return a=tg("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tN;return Object.assign(i,n),i})}{let t,r,o=(s=this.apiClient,t={},null!=(r=t_(e,["model"]))&&ty(t,["_url","name"],tz(s,r)),t);return a=tg("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tN;return Object.assign(i,n),i})}}async countTokens(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n=function(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>e)),ty(n,["contents"],e)}let s=t_(t,["config"]);return null!=s&&function(e,t,r){let n=t_(e,["systemInstruction"]);void 0!==t&&null!=n&&ty(t,["systemInstruction"],t3(n));let i=t_(e,["tools"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rK(e))),ty(t,["tools"],e)}let o=t_(e,["generationConfig"]);void 0!==t&&null!=o&&ty(t,["generationConfig"],function(e,t){let r={},n=t_(e,["modelSelectionConfig"]);null!=n&&ty(r,["modelConfig"],n);let i=t_(e,["responseJsonSchema"]);null!=i&&ty(r,["responseJsonSchema"],i);let o=t_(e,["audioTimestamp"]);null!=o&&ty(r,["audioTimestamp"],o);let s=t_(e,["candidateCount"]);null!=s&&ty(r,["candidateCount"],s);let a=t_(e,["enableAffectiveDialog"]);null!=a&&ty(r,["enableAffectiveDialog"],a);let l=t_(e,["frequencyPenalty"]);null!=l&&ty(r,["frequencyPenalty"],l);let u=t_(e,["logprobs"]);null!=u&&ty(r,["logprobs"],u);let c=t_(e,["maxOutputTokens"]);null!=c&&ty(r,["maxOutputTokens"],c);let d=t_(e,["mediaResolution"]);null!=d&&ty(r,["mediaResolution"],d);let p=t_(e,["presencePenalty"]);null!=p&&ty(r,["presencePenalty"],p);let h=t_(e,["responseLogprobs"]);null!=h&&ty(r,["responseLogprobs"],h);let f=t_(e,["responseMimeType"]);null!=f&&ty(r,["responseMimeType"],f);let m=t_(e,["responseModalities"]);null!=m&&ty(r,["responseModalities"],m);let g=t_(e,["responseSchema"]);null!=g&&ty(r,["responseSchema"],g);let y=t_(e,["routingConfig"]);null!=y&&ty(r,["routingConfig"],y);let _=t_(e,["seed"]);null!=_&&ty(r,["seed"],_);let E=t_(e,["speechConfig"]);null!=E&&ty(r,["speechConfig"],E);let v=t_(e,["stopSequences"]);null!=v&&ty(r,["stopSequences"],v);let T=t_(e,["temperature"]);null!=T&&ty(r,["temperature"],T);let A=t_(e,["thinkingConfig"]);null!=A&&ty(r,["thinkingConfig"],A);let S=t_(e,["topK"]);null!=S&&ty(r,["topK"],S);let b=t_(e,["topP"]);if(null!=b&&ty(r,["topP"],b),void 0!==t_(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return r}(o))}(s,n),n}(this.apiClient,e);return o=tg("{model}:countTokens",n._url),s=n._query,delete n._url,delete n._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),null!=(n=t_(e,["totalTokens"]))&&ty(t,["totalTokens"],n),t),o=new tk;return Object.assign(o,i),o})}{let t=function(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>rD(e))),ty(n,["contents"],e)}let s=t_(t,["config"]);return null!=s&&function(e,t){if(void 0!==t_(e,["systemInstruction"]))throw Error("systemInstruction parameter is not supported in Gemini API.");if(void 0!==t_(e,["tools"]))throw Error("tools parameter is not supported in Gemini API.");if(void 0!==t_(e,["generationConfig"]))throw Error("generationConfig parameter is not supported in Gemini API.")}(s),n}(this.apiClient,e);return o=tg("{model}:countTokens",t._url),s=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,o=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),null!=(n=t_(e,["totalTokens"]))&&ty(t,["totalTokens"],n),null!=(i=t_(e,["cachedContentTokenCount"]))&&ty(t,["cachedContentTokenCount"],i),t),s=new tk;return Object.assign(s,o),s})}}async computeTokens(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let o=function(e,t,r){let n={},i=t_(t,["model"]);null!=i&&ty(n,["_url","model"],tz(e,i));let o=t_(t,["contents"]);if(null!=o){let e=t9(o);Array.isArray(e)&&(e=e.map(e=>e)),ty(n,["contents"],e)}return n}(this.apiClient,e);return n=tg("{model}:computeTokens",o._url),i=o._query,delete o._url,delete o._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["tokensInfo"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(r,["tokensInfo"],e)}return r}(e),r=new tP;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,r,n,i,o,s,a,l,u,c;let d="",p={};if(this.apiClient.isVertexAI()){let n,i,s,u,c,h,f,m,g,y,_=(o=this.apiClient,u={},null!=(c=t_(e,["model"]))&&ty(u,["_url","model"],tz(o,c)),null!=(h=t_(e,["prompt"]))&&ty(u,["instances[0]","prompt"],h),null!=(f=t_(e,["image"]))&&ty(u,["instances[0]","image"],rB(f)),null!=(m=t_(e,["video"]))&&ty(u,["instances[0]","video"],rz(m)),null!=(g=t_(e,["source"]))&&(a=g,l=u,n=t_(a,["prompt"]),void 0!==l&&null!=n&&ty(l,["instances[0]","prompt"],n),i=t_(a,["image"]),void 0!==l&&null!=i&&ty(l,["instances[0]","image"],rB(i)),s=t_(a,["video"]),void 0!==l&&null!=s&&ty(l,["instances[0]","video"],rz(s))),null!=(y=t_(e,["config"]))&&function(e,t,r){var n;let i,o,s,a=t_(e,["numberOfVideos"]);void 0!==t&&null!=a&&ty(t,["parameters","sampleCount"],a);let l=t_(e,["outputGcsUri"]);void 0!==t&&null!=l&&ty(t,["parameters","storageUri"],l);let u=t_(e,["fps"]);void 0!==t&&null!=u&&ty(t,["parameters","fps"],u);let c=t_(e,["durationSeconds"]);void 0!==t&&null!=c&&ty(t,["parameters","durationSeconds"],c);let d=t_(e,["seed"]);void 0!==t&&null!=d&&ty(t,["parameters","seed"],d);let p=t_(e,["aspectRatio"]);void 0!==t&&null!=p&&ty(t,["parameters","aspectRatio"],p);let h=t_(e,["resolution"]);void 0!==t&&null!=h&&ty(t,["parameters","resolution"],h);let f=t_(e,["personGeneration"]);void 0!==t&&null!=f&&ty(t,["parameters","personGeneration"],f);let m=t_(e,["pubsubTopic"]);void 0!==t&&null!=m&&ty(t,["parameters","pubsubTopic"],m);let g=t_(e,["negativePrompt"]);void 0!==t&&null!=g&&ty(t,["parameters","negativePrompt"],g);let y=t_(e,["enhancePrompt"]);void 0!==t&&null!=y&&ty(t,["parameters","enhancePrompt"],y);let _=t_(e,["generateAudio"]);void 0!==t&&null!=_&&ty(t,["parameters","generateAudio"],_);let E=t_(e,["lastFrame"]);void 0!==t&&null!=E&&ty(t,["instances[0]","lastFrame"],rB(E));let v=t_(e,["referenceImages"]);if(void 0!==t&&null!=v){let e=v;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=t_(t=e,["image"]))&&ty(r,["image"],rB(n)),null!=(i=t_(t,["referenceType"]))&&ty(r,["referenceType"],i),r})),ty(t,["instances[0]","referenceImages"],e)}let T=t_(e,["mask"]);void 0!==t&&null!=T&&ty(t,["instances[0]","mask"],(i={},null!=(o=t_(n=T,["image"]))&&ty(i,["_self"],rB(o)),null!=(s=t_(n,["maskMode"]))&&ty(i,["maskMode"],s),i));let A=t_(e,["compressionQuality"]);void 0!==t&&null!=A&&ty(t,["parameters","compressionQuality"],A)}(y,u),u);return d=tg("{model}:predictLongRunning",_._url),p=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:p,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,o,s,a=(t={},null!=(r=t_(e,["name"]))&&ty(t,["name"],r),null!=(n=t_(e,["metadata"]))&&ty(t,["metadata"],n),null!=(i=t_(e,["done"]))&&ty(t,["done"],i),null!=(o=t_(e,["error"]))&&ty(t,["error"],o),null!=(s=t_(e,["response"]))&&ty(t,["response"],function(e,t){let r={},n=t_(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a;return r={},null!=(n=t_(e,["_self"]))&&ty(r,["video"],(i={},null!=(o=t_(t=n,["gcsUri"]))&&ty(i,["uri"],o),null!=(s=t_(t,["bytesBase64Encoded"]))&&ty(i,["videoBytes"],tE(s)),null!=(a=t_(t,["mimeType"]))&&ty(i,["mimeType"],a),i)),r})),ty(r,["generatedVideos"],e)}let i=t_(e,["raiMediaFilteredCount"]);null!=i&&ty(r,["raiMediaFilteredCount"],i);let o=t_(e,["raiMediaFilteredReasons"]);return null!=o&&ty(r,["raiMediaFilteredReasons"],o),r}(s)),t),l=new tx;return Object.assign(l,a),l})}{let t,r,o,a,l,h,f,m,g,y,_=(s=this.apiClient,a={},null!=(l=t_(e,["model"]))&&ty(a,["_url","model"],tz(s,l)),null!=(h=t_(e,["prompt"]))&&ty(a,["instances[0]","prompt"],h),null!=(f=t_(e,["image"]))&&ty(a,["instances[0]","image"],rH(f)),null!=(m=t_(e,["video"]))&&ty(a,["instances[0]","video"],rY(m)),null!=(g=t_(e,["source"]))&&(u=g,c=a,t=t_(u,["prompt"]),void 0!==c&&null!=t&&ty(c,["instances[0]","prompt"],t),r=t_(u,["image"]),void 0!==c&&null!=r&&ty(c,["instances[0]","image"],rH(r)),o=t_(u,["video"]),void 0!==c&&null!=o&&ty(c,["instances[0]","video"],rY(o))),null!=(y=t_(e,["config"]))&&function(e,t,r){let n=t_(e,["numberOfVideos"]);if(void 0!==t&&null!=n&&ty(t,["parameters","sampleCount"],n),void 0!==t_(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==t_(e,["fps"]))throw Error("fps parameter is not supported in Gemini API.");let i=t_(e,["durationSeconds"]);if(void 0!==t&&null!=i&&ty(t,["parameters","durationSeconds"],i),void 0!==t_(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let o=t_(e,["aspectRatio"]);void 0!==t&&null!=o&&ty(t,["parameters","aspectRatio"],o);let s=t_(e,["resolution"]);void 0!==t&&null!=s&&ty(t,["parameters","resolution"],s);let a=t_(e,["personGeneration"]);if(void 0!==t&&null!=a&&ty(t,["parameters","personGeneration"],a),void 0!==t_(e,["pubsubTopic"]))throw Error("pubsubTopic parameter is not supported in Gemini API.");let l=t_(e,["negativePrompt"]);void 0!==t&&null!=l&&ty(t,["parameters","negativePrompt"],l);let u=t_(e,["enhancePrompt"]);if(void 0!==t&&null!=u&&ty(t,["parameters","enhancePrompt"],u),void 0!==t_(e,["generateAudio"]))throw Error("generateAudio parameter is not supported in Gemini API.");let c=t_(e,["lastFrame"]);void 0!==t&&null!=c&&ty(t,["instances[0]","lastFrame"],rH(c));let d=t_(e,["referenceImages"]);if(void 0!==t&&null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=t_(t=e,["image"]))&&ty(r,["image"],rH(n)),null!=(i=t_(t,["referenceType"]))&&ty(r,["referenceType"],i),r})),ty(t,["instances[0]","referenceImages"],e)}if(void 0!==t_(e,["mask"]))throw Error("mask parameter is not supported in Gemini API.");if(void 0!==t_(e,["compressionQuality"]))throw Error("compressionQuality parameter is not supported in Gemini API.")}(y,a),a);return d=tg("{model}:predictLongRunning",_._url),p=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:p,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,o,s,a=(t={},null!=(r=t_(e,["name"]))&&ty(t,["name"],r),null!=(n=t_(e,["metadata"]))&&ty(t,["metadata"],n),null!=(i=t_(e,["done"]))&&ty(t,["done"],i),null!=(o=t_(e,["error"]))&&ty(t,["error"],o),null!=(s=t_(e,["response","generateVideoResponse"]))&&ty(t,["response"],function(e,t){let r={},n=t_(e,["generatedSamples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a;return r={},null!=(n=t_(e,["video"]))&&ty(r,["video"],(i={},null!=(o=t_(t=n,["uri"]))&&ty(i,["uri"],o),null!=(s=t_(t,["encodedVideo"]))&&ty(i,["videoBytes"],tE(s)),null!=(a=t_(t,["encoding"]))&&ty(i,["mimeType"],a),i)),r})),ty(r,["generatedVideos"],e)}let i=t_(e,["raiMediaFilteredCount"]);null!=i&&ty(r,["raiMediaFilteredCount"],i);let o=t_(e,["raiMediaFilteredReasons"]);return null!=o&&ty(r,["raiMediaFilteredReasons"],o),r}(s)),t),l=new tx;return Object.assign(l,a),l})}}}class na extends tm{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=t_(e,["operationName"]))&&ty(n,["_url","operationName"],i),n);return o=tg("{operationName}",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}{let t,r,a=(t={},null!=(r=t_(e,["operationName"]))&&ty(t,["_url","operationName"],r),t);return o=tg("{operationName}",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json())}}async fetchPredictVideosOperationInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let o,s,a,l=(o={},null!=(s=t_(e,["operationName"]))&&ty(o,["operationName"],s),null!=(a=t_(e,["resourceName"]))&&ty(o,["_url","resourceName"],a),o);return n=tg("{resourceName}:fetchPredictOperation",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}throw Error("This method is only supported by the Vertex AI.")}}class nl extends tm{constructor(e){super(),this.apiClient=e}async create(e){var t,r,n,i,o;let s="",a={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let l,u,c,d,p,h,f,m,g,y,_=(n=this.apiClient,d={},null!=(p=t_(e,["config"]))&&ty(d,["config"],(h=t_(p,["expireTime"]),void 0!==d&&null!=h&&ty(d,["expireTime"],h),f=t_(p,["newSessionExpireTime"]),void 0!==d&&null!=f&&ty(d,["newSessionExpireTime"],f),m=t_(p,["uses"]),void 0!==d&&null!=m&&ty(d,["uses"],m),g=t_(p,["liveConnectConstraints"]),void 0!==d&&null!=g&&ty(d,["bidiGenerateContentSetup"],(i=n,l={},null!=(u=t_(o=g,["model"]))&&ty(l,["setup","model"],tz(i,u)),null!=(c=t_(o,["config"]))&&ty(l,["config"],function(e,t){let r=t_(e,["generationConfig"]);void 0!==t&&null!=r&&ty(t,["setup","generationConfig"],r);let n=t_(e,["responseModalities"]);void 0!==t&&null!=n&&ty(t,["setup","generationConfig","responseModalities"],n);let i=t_(e,["temperature"]);void 0!==t&&null!=i&&ty(t,["setup","generationConfig","temperature"],i);let o=t_(e,["topP"]);void 0!==t&&null!=o&&ty(t,["setup","generationConfig","topP"],o);let s=t_(e,["topK"]);void 0!==t&&null!=s&&ty(t,["setup","generationConfig","topK"],s);let a=t_(e,["maxOutputTokens"]);void 0!==t&&null!=a&&ty(t,["setup","generationConfig","maxOutputTokens"],a);let l=t_(e,["mediaResolution"]);void 0!==t&&null!=l&&ty(t,["setup","generationConfig","mediaResolution"],l);let u=t_(e,["seed"]);void 0!==t&&null!=u&&ty(t,["setup","generationConfig","seed"],u);let c=t_(e,["speechConfig"]);void 0!==t&&null!=c&&ty(t,["setup","generationConfig","speechConfig"],rr(c));let d=t_(e,["thinkingConfig"]);void 0!==t&&null!=d&&ty(t,["setup","generationConfig","thinkingConfig"],d);let p=t_(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&ty(t,["setup","generationConfig","enableAffectiveDialog"],p);let h=t_(e,["systemInstruction"]);void 0!==t&&null!=h&&ty(t,["setup","systemInstruction"],function(e){let t={},r=t_(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p,h;return r={},null!=(n=t_(t=e,["mediaResolution"]))&&ty(r,["mediaResolution"],n),null!=(i=t_(t,["codeExecutionResult"]))&&ty(r,["codeExecutionResult"],i),null!=(o=t_(t,["executableCode"]))&&ty(r,["executableCode"],o),null!=(s=t_(t,["fileData"]))&&ty(r,["fileData"],function(e){let t={};if(void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=t_(e,["fileUri"]);null!=r&&ty(t,["fileUri"],r);let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(s)),null!=(a=t_(t,["functionCall"]))&&ty(r,["functionCall"],function(e){let t={},r=t_(e,["id"]);null!=r&&ty(t,["id"],r);let n=t_(e,["args"]);null!=n&&ty(t,["args"],n);let i=t_(e,["name"]);if(null!=i&&ty(t,["name"],i),void 0!==t_(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==t_(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=t_(t,["functionResponse"]))&&ty(r,["functionResponse"],l),null!=(u=t_(t,["inlineData"]))&&ty(r,["inlineData"],function(e){let t={},r=t_(e,["data"]);if(null!=r&&ty(t,["data"],r),void 0!==t_(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=t_(e,["mimeType"]);return null!=n&&ty(t,["mimeType"],n),t}(u)),null!=(c=t_(t,["text"]))&&ty(r,["text"],c),null!=(d=t_(t,["thought"]))&&ty(r,["thought"],d),null!=(p=t_(t,["thoughtSignature"]))&&ty(r,["thoughtSignature"],p),null!=(h=t_(t,["videoMetadata"]))&&ty(r,["videoMetadata"],h),r})),ty(t,["parts"],e)}let n=t_(e,["role"]);return null!=n&&ty(t,["role"],n),t}(t3(h)));let f=t_(e,["tools"]);if(void 0!==t&&null!=f){let e=ri(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==t_(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let r=t_(e,["computerUse"]);null!=r&&ty(t,["computerUse"],r);let n=t_(e,["fileSearch"]);null!=n&&ty(t,["fileSearch"],n);let i=t_(e,["googleSearch"]);null!=i&&ty(t,["googleSearch"],function(e){let t={},r=t_(e,["searchTypes"]);if(null!=r&&ty(t,["searchTypes"],r),void 0!==t_(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==t_(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let n=t_(e,["timeRangeFilter"]);return null!=n&&ty(t,["timeRangeFilter"],n),t}(i));let o=t_(e,["codeExecution"]);if(null!=o&&ty(t,["codeExecution"],o),void 0!==t_(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let s=t_(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["functionDeclarations"],e)}let a=t_(e,["googleMaps"]);null!=a&&ty(t,["googleMaps"],function(e){let t={};if(void 0!==t_(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=t_(e,["enableWidget"]);return null!=r&&ty(t,["enableWidget"],r),t}(a));let l=t_(e,["googleSearchRetrieval"]);null!=l&&ty(t,["googleSearchRetrieval"],l);let u=t_(e,["urlContext"]);null!=u&&ty(t,["urlContext"],u);let c=t_(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["mcpServers"],e)}return t})(rn(e)))),ty(t,["setup","tools"],e)}let m=t_(e,["sessionResumption"]);void 0!==t&&null!=m&&ty(t,["setup","sessionResumption"],function(e){let t={},r=t_(e,["handle"]);if(null!=r&&ty(t,["handle"],r),void 0!==t_(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=t_(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&ty(t,["setup","inputAudioTranscription"],g);let y=t_(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&ty(t,["setup","outputAudioTranscription"],y);let _=t_(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&ty(t,["setup","realtimeInputConfig"],_);let E=t_(e,["contextWindowCompression"]);void 0!==t&&null!=E&&ty(t,["setup","contextWindowCompression"],E);let v=t_(e,["proactivity"]);if(void 0!==t&&null!=v&&ty(t,["setup","proactivity"],v),void 0!==t_(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(c,l)),l)),y=t_(p,["lockAdditionalFields"]),void 0!==d&&null!=y&&ty(d,["fieldMask"],y),{})),d);s=tg("auth_tokens",_._url),a=_._query,delete _.config,delete _._url,delete _._query;let E=function(e,t){let r=null,n=e.bidiGenerateContentSetup;if("object"==typeof n&&null!==n&&"setup"in n){let t=n.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,r=t):delete e.bidiGenerateContentSetup}else void 0!==n&&delete e.bidiGenerateContentSetup;let i=e.fieldMask;if(r){let n=function(e){let t=[];for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if("object"==typeof n&&null!=n&&Object.keys(n).length>0){let e=Object.keys(n).map(e=>`${r}.${e}`);t.push(...e)}else t.push(r)}return t.join(",")}(r);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&(null==t?void 0:t.lockAdditionalFields.length)===0)n?e.fieldMask=n:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){let t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],r=[];i.length>0&&(r=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));let o=[];n&&o.push(n),r.length>0&&o.push(...r),o.length>0?e.fieldMask=o.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(_,e.config);return this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(E),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}}class nu extends tm{constructor(e){super(),this.apiClient=e,this.list=async e=>new rv(ts.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","name"],s),o);return n=tg("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","name"],s),null!=(a=t_(e,["config"]))&&(l=t_(a,["force"]),void 0!==o&&null!=l&&ty(o,["_query","force"],l)),o);n=tg("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u,c=(o={},null!=(s=t_(e,["parent"]))&&ty(o,["_url","parent"],s),null!=(a=t_(e,["config"]))&&(l=t_(a,["pageSize"]),void 0!==o&&null!=l&&ty(o,["_query","pageSize"],l),u=t_(a,["pageToken"]),void 0!==o&&null!=u&&ty(o,["_query","pageToken"],u)),o);return n=tg("{parent}/documents",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["documents"],e)}return t}(e),r=new tj;return Object.assign(r,t),r})}}}class nc extends tm{constructor(e,t=new nu(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new rv(ts.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l=(o={},null!=(s=t_(e,["config"]))&&(a=t_(s,["displayName"]),void 0!==o&&null!=a&&ty(o,["displayName"],a)),o);return n=tg("fileSearchStores",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","name"],s),o);return n=tg("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u=(o={},null!=(s=t_(e,["name"]))&&ty(o,["_url","name"],s),null!=(a=t_(e,["config"]))&&(l=t_(a,["force"]),void 0!==o&&null!=l&&ty(o,["_query","force"],l)),o);n=tg("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u=(o={},null!=(s=t_(e,["config"]))&&(a=t_(s,["pageSize"]),void 0!==o&&null!=a&&ty(o,["_query","pageSize"],a),l=t_(s,["pageToken"]),void 0!==o&&null!=l&&ty(o,["_query","pageToken"],l)),o);return n=tg("fileSearchStores",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=t_(e,["sdkHttpResponse"]);null!=r&&ty(t,["sdkHttpResponse"],r);let n=t_(e,["nextPageToken"]);null!=n&&ty(t,["nextPageToken"],n);let i=t_(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["fileSearchStores"],e)}return t}(e),r=new tG;return Object.assign(r,t),r})}}async uploadToFileSearchStoreInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l=(o={},null!=(s=t_(e,["fileSearchStoreName"]))&&ty(o,["_url","file_search_store_name"],s),null!=(a=t_(e,["config"]))&&rX(a,o),o);return n=tg("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tF;return Object.assign(i,n),i})}}async importFile(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u=(o={},null!=(s=t_(e,["fileSearchStoreName"]))&&ty(o,["_url","file_search_store_name"],s),null!=(a=t_(e,["fileName"]))&&ty(o,["fileName"],a),null!=(l=t_(e,["config"]))&&function(e,t){let r=t_(e,["customMetadata"]);if(void 0!==t&&null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),ty(t,["customMetadata"],e)}let n=t_(e,["chunkingConfig"]);void 0!==t&&null!=n&&ty(t,["chunkingConfig"],n)}(l,o),o);return n=tg("{file_search_store_name}:importFile",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{var t;let r,n,i,o,s,a,l,u,c,d,p=(s={},null!=(a=t_(e,["name"]))&&ty(s,["name"],a),null!=(l=t_(e,["metadata"]))&&ty(s,["metadata"],l),null!=(u=t_(e,["done"]))&&ty(s,["done"],u),null!=(c=t_(e,["error"]))&&ty(s,["error"],c),null!=(d=t_(e,["response"]))&&ty(s,["response"],(r={},null!=(n=t_(t=d,["sdkHttpResponse"]))&&ty(r,["sdkHttpResponse"],n),null!=(i=t_(t,["parent"]))&&ty(r,["parent"],i),null!=(o=t_(t,["documentName"]))&&ty(r,["documentName"],o),r)),s),h=new tq;return Object.assign(h,p),h})}}}let nd=function(){let{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return nd=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function np(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let nh=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return Error(JSON.stringify(e))}catch(e){}}return Error(e)};class nf extends Error{}class nm extends nf{constructor(e,t,r,n){super(`${nm.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.error=t}static makeMessage(e,t,r){let n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){return e&&n?400===e?new nE(e,t,r,n):401===e?new nv(e,t,r,n):403===e?new nT(e,t,r,n):404===e?new nA(e,t,r,n):409===e?new nS(e,t,r,n):422===e?new nb(e,t,r,n):429===e?new nC(e,t,r,n):e>=500?new nO(e,t,r,n):new nm(e,t,r,n):new ny({message:r,cause:nh(t)})}}class ng extends nm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ny extends nm{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class n_ extends ny{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}}class nE extends nm{}class nv extends nm{}class nT extends nm{}class nA extends nm{}class nS extends nm{}class nb extends nm{}class nC extends nm{}class nO extends nm{}let nI=/^[a-z][a-z0-9+.-]*:/i,nw=e=>(nw=Array.isArray)(e),nR=nw,nN="0.0.1",nk=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",nP=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function nx(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function nU(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nD(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await (null==(r=(t=e[Symbol.asyncIterator]()).return)?void 0:r.call(t));let n=e.getReader(),i=n.cancel();n.releaseLock(),await i}let nM=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),nL=()=>{var e;if("u"parseInt(t.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function nj(e,t,r){return nL(),new File(e,null!=t?t:"unknown_file",r)}let nG=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function nF(e,t,r){var n;let i,o;if(nL(),null!=(i=e=await e)&&"object"==typeof i&&"string"==typeof i.name&&"number"==typeof i.lastModified&&nG(i))return e instanceof File?e:nj([await e.arrayBuffer()],e.name);if(null!=(o=e)&&"object"==typeof o&&"string"==typeof o.url&&"function"==typeof o.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),nj(await nq(n),t,r)}let s=await nq(e);if(t||(t=("object"==typeof(n=e)&&null!==n&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0),!(null==r?void 0:r.type)){let e=s.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return nj(s,t,r)}async function nq(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nG(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])try{for(var r,n,i,o,s,a,l=!0,u=rI(e);!(r=(a=await u.next()).done);l=!0)o=a.value,l=!1,t.push(...await nq(o))}catch(e){n={error:e}}finally{try{!l&&!r&&(i=u.return)&&await i.call(u)}finally{if(n)throw n.error}}else{let t=null==(s=null==e?void 0:e.constructor)?void 0:s.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class nH{constructor(e){this._client=e}}function nB(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}nH._key=[];let nV=Object.freeze(Object.create(null)),n$=((e=nB)=>function(t,...r){let n;if(1===t.length)return t[0];let i=!1,o=[],s=t.reduce((t,n,s)=>{var a,l,u;/[?#]/.test(n)&&(i=!0);let c=r[s],d=(i?encodeURIComponent:e)(""+c);return s!==r.length&&(null==c||"object"==typeof c&&c.toString===(null==(u=Object.getPrototypeOf(null!=(l=Object.getPrototypeOf(null!=(a=c.hasOwnProperty)?a:nV))?l:nV))?void 0:u.toString))&&(d=c+"",o.push({start:t.length+n.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),t+n+(s===r.length?"":d)},""),a=s.split(/[?#]/,1)[0],l=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(a));){let e=n[0].startsWith("/"),t=+!!e,r=e?n[0].slice(1):n[0];o.push({start:n.index+t,length:r.length,error:`Value "${r}" can't be safely passed as a path parameter`})}if(o.sort((e,t)=>e.start-t.start),o.length>0){let e=0,t=o.reduce((t,r)=>{let n=" ".repeat(r.start-e),i="^".repeat(r.length);return e=r.start+r.length,t+n+i},"");throw new nf(`Path parameters result in path with invalid segments: ${o.map(e=>e.error).join("\n")} ${s} ${t}`)}return s})(nB);class nJ extends nH{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=rb(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new nf("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new nf("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(n$`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(n$`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(n$`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:o=this._client.apiVersion}=i,s=rb(i,["api_version"]);return this._client.get(n$`/${o}/interactions/${e}`,Object.assign(Object.assign({query:s},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}nJ._key=Object.freeze(["interactions"]);class nW extends nJ{}function nK(e){let t;return(null!=r?r:r=(t=new globalThis.TextEncoder).encode.bind(t))(e)}function nY(e){let t;return(null!=n?n:n=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class nz{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?nK(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);let n=[];for(;null!=(t=function(e,t){for(let r=null!=t?t:0;r{if(e){if(Object.prototype.hasOwnProperty.call(nX,e))return e;n4(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nX))}`)}};function nZ(){}function n0(e,t,r){return!t||nX[e]>nX[r]?nZ:t[e].bind(t)}let n1={error:nZ,warn:nZ,info:nZ,debug:nZ},n2=new WeakMap;function n4(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return n1;let i=n2.get(r);if(i&&i[0]===n)return i[1];let o={error:n0("error",r,n),warn:n0("warn",r,n),info:n0("info",r,n),debug:n0("debug",r,n)};return n2.set(r,[n,o]),o}let n6=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class n8{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?n4(r):console;return new n8(function(){return rO(this,arguments,function*(){var r,o,s,a;if(n)throw new nf("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=rI(function(e,t){return rO(this,arguments,function*(){var r,n,i,o;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new nf("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new nf("Attempted to iterate over a response with no body")}let s=new n5,a=new nz,l=nU(e.body);try{for(var u,c=!0,d=rI(function(e){return rO(this,arguments,function*(){var t,r,n,i;let o=new Uint8Array;try{for(var s,a=!0,l=rI(e);!(t=(s=yield rC(l.next())).done);a=!0){let e;if(i=s.value,a=!1,null==i)continue;let t=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?nK(i):i,r=new Uint8Array(o.length+t.length);for(r.set(o),r.set(t,o.length),o=r;-1!==(e=function(e){for(let t=0;t0&&(yield yield rC(o))})}(l));!(r=(u=yield rC(d.next())).done);c=!0)for(let e of(o=u.value,c=!1,a.decode(o))){let t=s.decode(e);t&&(yield yield rC(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield rC(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=s.decode(e);t&&(yield yield rC(t))}})}(e,t));!(r=(u=yield rC(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield rC(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){o={error:e}}finally{try{!c&&!r&&(s=d.return)&&(yield rC(s.call(d)))}finally{if(o)throw o.error}}l=!0}catch(e){if(np(e))return yield rC(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new n8(function(){return rO(this,arguments,function*(){var r,i,o,s;if(n)throw new nf("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=rI(function(){return rO(this,arguments,function*(){var t,r,n,i;let o=new nz,s=nU(e);try{for(var a,l=!0,u=rI(s);!(t=(a=yield rC(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,o.decode(i)))yield yield rC(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield rC(n.call(u)))}finally{if(r)throw r.error}}for(let e of o.flush())yield yield rC(e)})}());!(r=(l=yield rC(c.next())).done);u=!0)s=l.value,u=!1,!a&&s&&(yield yield rC(JSON.parse(s)))}catch(e){i={error:e}}finally{try{!u&&!r&&(o=c.return)&&(yield rC(o.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(np(e))return yield rC(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new n8(()=>n(e),this.controller,this.client),new n8(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nx({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=nK(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class n5{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,o]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return o.startsWith(" ")&&(o=o.substring(1)),"event"===n?this.event=o:"data"===n&&this.data.push(o),null}}async function n3(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=t,s=await (async()=>{var n;if(t.options.stream)return(n4(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):n8.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),o=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();if((null==o?void 0:o.includes("application/json"))||(null==o?void 0:o.endsWith("+json"))){if("0"===r.headers.get("content-length"))return;return await r.json()}return await r.text()})();return n4(e).debug(`[${n}] response parsed`,n6({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}class n7 extends Promise{constructor(e,t,r=n3){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new n7(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let n9=Symbol("brand.privateNullableHeaders"),ie=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,o]of function*(e){let t;if(!e)return;if(n9 in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nR(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nR(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===o?(t.delete(i),r.add(n)):(t.append(i,o),r.delete(n))}}return{[n9]:!0,values:t,nulls:r}},it=e=>{var t,r,n,i,o,s;return void 0!==globalThis.process?null!=(n=null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())?n:void 0:void 0!==globalThis.Deno?null==(s=null==(o=null==(i=globalThis.Deno.env)?void 0:i.get)?void 0:o.call(i,e))?void 0:s.trim():void 0};class ir{constructor(e){var t,r,n,i,o,s,a,{baseURL:l=it("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=it("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;const d=Object.assign(Object.assign({apiKey:u,apiVersion:c},rb(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:ir.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;const p="warn";this.logLevel=p,this.logLevel=null!=(o=null!=(i=nQ(d.logLevel,"ClientOptions.logLevel",this))?i:nQ(it("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?o:p,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(s=d.maxRetries)?s:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nM,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.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"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw 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 t=ie([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return ie([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return ie([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new nf(`Cannot stringify type ${typeof t}; 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("&")}getUserAgent(){return`${this.constructor.name}/JS ${nN}`}defaultIdempotencyKey(){return`stainless-node-retry-${nd()}`}makeStatusError(e,t,r,n){return nm.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nI.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(o)&&(t=Object.assign(Object.assign({},o),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new n7(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,o;let s=await e,a=null!=(n=s.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(s);let{req:l,url:u,timeout:c}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:s});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),p=void 0===r?"":`, retryOf: ${r}`,h=Date.now();if(n4(this).debug(`[${d}] sending request`,n6({retryOfRequestLogID:r,method:s.method,url:u,options:s,headers:l.headers})),null==(i=s.signal)?void 0:i.aborted)throw new ng;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(nh),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(o=s.signal)?void 0:o.aborted)throw new ng;let n=np(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return n4(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),n4(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,n6({retryOfRequestLogID:r,url:u,durationMs:g-h,message:m.message})),this.retryRequest(s,t,null!=r?r:d);if(n4(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),n4(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,n6({retryOfRequestLogID:r,url:u,durationMs:g-h,message:m.message})),n)throw new n_;throw new ny({cause:m})}let y=`[${d}${p}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-h}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nD(m.body),n4(this).info(`${y} - ${e}`),n4(this).debug(`[${d}] response error (${e})`,n6({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-h})),this.retryRequest(s,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";n4(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>nh(e).message),o=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=o?void 0:i;throw n4(this).debug(`[${d}] response error (${n})`,n6({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-h})),this.makeStatusError(m.status,o,a,m.headers)}return n4(this).info(y),n4(this).debug(`[${d}] response start`,n6({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-h})),{response:m,options:s,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:h}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:o,method:s}=i,a=rb(i,["signal","method"]),l=this._makeAbort(n);o&&o.addEventListener("abort",l,{once:!0});let u=setTimeout(l,r),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,d=Object.assign(Object.assign(Object.assign({signal:n.signal},c?{duplex:"half"}:{}),{method:"GET"}),a);s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let o,s,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(o=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!o){let e=parseFloat(l);o=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(!(o&&0<=o&&o<6e4)){let r=null!=(i=e.maxRetries)?i:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (s=o,new Promise(e=>setTimeout(e,s))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let o=Object.assign({},e),{method:s,path:a,query:l,defaultBaseURL:u}=o,c=this.buildURL(a,l,u);"timeout"in o&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new nf(`${e} must be an integer`);if(t<0)throw new nf(`${e} must be a positive integer`)})("timeout",o.timeout),o.timeout=null!=(r=o.timeout)?r:this.timeout;let{bodyHeaders:d,body:p}=this.buildBody({options:o}),h=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:s,headers:h},o.signal&&{signal:o.signal}),globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"}),p&&{body:p}),null!=(n=this.fetchOptions)?n:{}),null!=(i=o.fetchOptions)?i:{}),url:c,timeout:o.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=await this.authHeaders(e),a=ie([o,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),null!=t?t:t=(()=>{var e,t,r,n,i;let o="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===o)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nN,"X-Stainless-OS":nP(Deno.build.os),"X-Stainless-Arch":nk(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:null!=(t=null==(e=Deno.version)?void 0:e.deno)?t:"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nN,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===o)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nN,"X-Stainless-OS":nP(null!=(r=globalThis.process.platform)?r:"unknown"),"X-Stainless-Arch":nk(null!=(n=globalThis.process.arch)?n:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":null!=(i=globalThis.process.version)?i:"unknown"};let s=function(){if("u"e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=ie([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)){let t;return{bodyHeaders:void 0,body:(t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nx({start(){},async pull(e){let{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=t.return)?void 0:e.call(t))}}))}}return"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}}ir.DEFAULT_TIMEOUT=6e4;class ii extends ir{constructor(){super(...arguments),this.interactions=new nW(this)}}ii.GeminiNextGenAPIClient=ii,ii.GeminiNextGenAPIClientError=nf,ii.APIError=nm,ii.APIConnectionError=ny,ii.APIConnectionTimeoutError=n_,ii.APIUserAbortError=ng,ii.NotFoundError=nA,ii.ConflictError=nS,ii.RateLimitError=nC,ii.BadRequestError=nE,ii.AuthenticationError=nv,ii.InternalServerError=nO,ii.PermissionDeniedError=nT,ii.UnprocessableEntityError=nb,ii.toFile=nF,ii.Interactions=nW;let io="x-goog-api-key",is="https://www.googleapis.com/auth/cloud-platform";class ia{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}const t=function(e){let t;if(!e)return{scopes:[is]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==is||Array.isArray(t.scopes)&&0>t.scopes.indexOf(is))throw Error(`Invalid auth scopes. Scopes must include: ${is}`)}else t.scopes=[is];return t}(e.googleAuthOptions);this.googleAuth=new tl.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(io)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(io,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class il{async download(e,t){if(e.downloadPath){let r=await iu(e,t);if(r instanceof tT){let t=(0,tu.createWriteStream)(e.downloadPath);td.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,tp.finished)(t)}else try{await (0,tc.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function iu(e,t){var r,n,i;let o=ru(e.file);if(void 0!==o)return await t.request({path:`files/${o}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(ra(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rl(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class ic{create(e,t,r){return new id(e,t,r)}}class id{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new th.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(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ip(e,t){let r,n,i,o={},s=t_(e,["sdkHttpResponse"]);null!=s&&ty(o,["sdkHttpResponse"],s);let a=t_(e,["name"]);null!=a&&ty(o,["name"],a);let l=t_(e,["state"]);null!=l&&ty(o,["state"],rs(l));let u=t_(e,["createTime"]);null!=u&&ty(o,["createTime"],u);let c=t_(e,["tuningTask","startTime"]);null!=c&&ty(o,["startTime"],c);let d=t_(e,["tuningTask","completeTime"]);null!=d&&ty(o,["endTime"],d);let p=t_(e,["updateTime"]);null!=p&&ty(o,["updateTime"],p);let h=t_(e,["description"]);null!=h&&ty(o,["description"],h);let f=t_(e,["baseModel"]);null!=f&&ty(o,["baseModel"],f);let m=t_(e,["_self"]);return null!=m&&ty(o,["tunedModel"],(r={},null!=(n=t_(m,["name"]))&&ty(r,["model"],n),null!=(i=t_(m,["name"]))&&ty(r,["endpoint"],i),r)),o}function ih(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["name"]);null!=i&&ty(r,["name"],i);let o=t_(e,["state"]);null!=o&&ty(r,["state"],rs(o));let s=t_(e,["createTime"]);null!=s&&ty(r,["createTime"],s);let a=t_(e,["startTime"]);null!=a&&ty(r,["startTime"],a);let l=t_(e,["endTime"]);null!=l&&ty(r,["endTime"],l);let u=t_(e,["updateTime"]);null!=u&&ty(r,["updateTime"],u);let c=t_(e,["error"]);null!=c&&ty(r,["error"],c);let d=t_(e,["description"]);null!=d&&ty(r,["description"],d);let p=t_(e,["baseModel"]);null!=p&&ty(r,["baseModel"],p);let h=t_(e,["tunedModel"]);null!=h&&ty(r,["tunedModel"],h);let f=t_(e,["preTunedModel"]);null!=f&&ty(r,["preTunedModel"],f);let m=t_(e,["supervisedTuningSpec"]);null!=m&&ty(r,["supervisedTuningSpec"],m);let g=t_(e,["preferenceOptimizationSpec"]);null!=g&&ty(r,["preferenceOptimizationSpec"],g);let y=t_(e,["distillationSpec"]);null!=y&&ty(r,["distillationSpec"],y);let _=t_(e,["tuningDataStats"]);null!=_&&ty(r,["tuningDataStats"],_);let E=t_(e,["encryptionSpec"]);null!=E&&ty(r,["encryptionSpec"],E);let v=t_(e,["partnerModelTuningSpec"]);null!=v&&ty(r,["partnerModelTuningSpec"],v);let T=t_(e,["customBaseModel"]);null!=T&&ty(r,["customBaseModel"],T);let A=t_(e,["experiment"]);null!=A&&ty(r,["experiment"],A);let S=t_(e,["labels"]);null!=S&&ty(r,["labels"],S);let b=t_(e,["outputUri"]);null!=b&&ty(r,["outputUri"],b);let C=t_(e,["pipelineJob"]);null!=C&&ty(r,["pipelineJob"],C);let O=t_(e,["serviceAccount"]);null!=O&&ty(r,["serviceAccount"],O);let I=t_(e,["tunedModelDisplayName"]);null!=I&&ty(r,["tunedModelDisplayName"],I);let w=t_(e,["veoTuningSpec"]);return null!=w&&ty(r,["veoTuningSpec"],w),r}function im(e,t){let r={},n=t_(e,["gcsUri"]);null!=n&&ty(r,["validationDatasetUri"],n);let i=t_(e,["vertexDatasetResource"]);return null!=i&&ty(r,["validationDatasetUri"],i),r}class ig extends tm{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rv(ts.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eM.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],i),n);return o=tg("{name}",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ih(e))}{let t,r,a=(t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],r),t);return o=tg("{name}",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ip(e))}}async listInternal(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=t_(e,["config"]))&&(a=t_(i,["pageSize"]),void 0!==n&&null!=a&&ty(n,["_query","pageSize"],a),l=t_(i,["pageToken"]),void 0!==n&&null!=l&&ty(n,["_query","pageToken"],l),u=t_(i,["filter"]),void 0!==n&&null!=u&&ty(n,["_query","filter"],u)),n);return o=tg("tuningJobs",c._url),s=c._query,delete c._url,delete c._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["nextPageToken"]);null!=i&&ty(r,["nextPageToken"],i);let o=t_(e,["tuningJobs"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>ih(e))),ty(r,["tuningJobs"],e)}return r}(e),r=new tU;return Object.assign(r,t),r})}{let t,r,a,l,u,c=(t={},null!=(r=t_(e,["config"]))&&(a=t_(r,["pageSize"]),void 0!==t&&null!=a&&ty(t,["_query","pageSize"],a),l=t_(r,["pageToken"]),void 0!==t&&null!=l&&ty(t,["_query","pageToken"],l),u=t_(r,["filter"]),void 0!==t&&null!=u&&ty(t,["_query","filter"],u)),t);return o=tg("tunedModels",c._url),s=c._query,delete c._url,delete c._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e,t){let r={},n=t_(e,["sdkHttpResponse"]);null!=n&&ty(r,["sdkHttpResponse"],n);let i=t_(e,["nextPageToken"]);null!=i&&ty(r,["nextPageToken"],i);let o=t_(e,["tunedModels"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>ip(e))),ty(r,["tuningJobs"],e)}return r}(e),r=new tU;return Object.assign(r,t),r})}}async cancel(e){var t,r,n,i;let o="",s={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=t_(e,["name"]))&&ty(n,["_url","name"],i),n);return o=tg("{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tD;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=t_(e,["name"]))&&ty(t,["_url","name"],r),t);return o=tg("{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),t),i=new tD;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let o,s,a,l,u,c=(o={},null!=(s=t_(e,["baseModel"]))&&ty(o,["baseModel"],s),null!=(a=t_(e,["preTunedModel"]))&&ty(o,["preTunedModel"],a),null!=(l=t_(e,["trainingDataset"]))&&function(e,t,r){let n=t_(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=t_(e,["gcsUri"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=t_(e,["gcsUri"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===n){let r=t_(e,["gcsUri"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","promptDatasetUri"],r)}let i=t_(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=t_(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=t_(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===i){let r=t_(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","promptDatasetUri"],r)}if(void 0!==t_(e,["examples"]))throw Error("examples parameter is not supported in Vertex AI.")}(l,o,e),null!=(u=t_(e,["config"]))&&function(e,t,r){let n=t_(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=t_(e,["validationDataset"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec"],im(r))}else if("PREFERENCE_TUNING"===n){let r=t_(e,["validationDataset"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec"],im(r))}else if("DISTILLATION"===n){let r=t_(e,["validationDataset"]);void 0!==t&&null!=r&&ty(t,["distillationSpec"],im(r))}let i=t_(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&ty(t,["tunedModelDisplayName"],i);let o=t_(e,["description"]);void 0!==t&&null!=o&&ty(t,["description"],o);let s=t_(r,["config","method"]);if(void 0===s&&(s="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===s){let r=t_(e,["epochCount"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===s){let r=t_(e,["epochCount"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}else if("DISTILLATION"===s){let r=t_(e,["epochCount"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","hyperParameters","epochCount"],r)}let a=t_(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=t_(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=t_(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}else if("DISTILLATION"===a){let r=t_(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","hyperParameters","learningRateMultiplier"],r)}let l=t_(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=t_(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=t_(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}else if("DISTILLATION"===l){let r=t_(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","exportLastCheckpointOnly"],r)}let u=t_(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=t_(e,["adapterSize"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=t_(e,["adapterSize"]);void 0!==t&&null!=r&&ty(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}else if("DISTILLATION"===u){let r=t_(e,["adapterSize"]);void 0!==t&&null!=r&&ty(t,["distillationSpec","hyperParameters","adapterSize"],r)}let c=t_(r,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){let r=t_(e,["tuningMode"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","tuningMode"],r)}let d=t_(e,["customBaseModel"]);void 0!==t&&null!=d&&ty(t,["customBaseModel"],d);let p=t_(r,["config","method"]);if(void 0===p&&(p="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===p){let r=t_(e,["batchSize"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","hyperParameters","batchSize"],r)}let h=t_(r,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){let r=t_(e,["learningRate"]);void 0!==t&&null!=r&&ty(t,["supervisedTuningSpec","hyperParameters","learningRate"],r)}let f=t_(e,["labels"]);void 0!==t&&null!=f&&ty(t,["labels"],f);let m=t_(e,["beta"]);void 0!==t&&null!=m&&ty(t,["preferenceOptimizationSpec","hyperParameters","beta"],m);let g=t_(e,["baseTeacherModel"]);void 0!==t&&null!=g&&ty(t,["distillationSpec","baseTeacherModel"],g);let y=t_(e,["tunedTeacherModelSource"]);void 0!==t&&null!=y&&ty(t,["distillationSpec","tunedTeacherModelSource"],y);let _=t_(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=_&&ty(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],_);let E=t_(e,["outputUri"]);void 0!==t&&null!=E&&ty(t,["outputUri"],E);let v=t_(e,["encryptionSpec"]);void 0!==t&&null!=v&&ty(t,["encryptionSpec"],v)}(u,o,e),o);return n=tg("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ih(e))}throw Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,s,a,l,u,c=(o={},null!=(s=t_(e,["baseModel"]))&&ty(o,["baseModel"],s),null!=(a=t_(e,["preTunedModel"]))&&ty(o,["preTunedModel"],a),null!=(l=t_(e,["trainingDataset"]))&&function(e,t){if(void 0!==t_(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==t_(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let r=t_(e,["examples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),ty({},["examples","examples"],e)}}(l),null!=(u=t_(e,["config"]))&&function(e,t,r){if(void 0!==t_(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let n=t_(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=n&&ty(t,["displayName"],n),void 0!==t_(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let i=t_(e,["epochCount"]);void 0!==t&&null!=i&&ty(t,["tuningTask","hyperparameters","epochCount"],i);let o=t_(e,["learningRateMultiplier"]);if(null!=o&&ty({},["tuningTask","hyperparameters","learningRateMultiplier"],o),void 0!==t_(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==t_(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==t_(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");if(void 0!==t_(e,["tuningMode"]))throw Error("tuningMode parameter is not supported in Gemini API.");if(void 0!==t_(e,["customBaseModel"]))throw Error("customBaseModel parameter is not supported in Gemini API.");let s=t_(e,["batchSize"]);void 0!==t&&null!=s&&ty(t,["tuningTask","hyperparameters","batchSize"],s);let a=t_(e,["learningRate"]);if(void 0!==t&&null!=a&&ty(t,["tuningTask","hyperparameters","learningRate"],a),void 0!==t_(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==t_(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.");if(void 0!==t_(e,["baseTeacherModel"]))throw Error("baseTeacherModel parameter is not supported in Gemini API.");if(void 0!==t_(e,["tunedTeacherModelSource"]))throw Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(void 0!==t_(e,["sftLossWeightMultiplier"]))throw Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(void 0!==t_(e,["outputUri"]))throw Error("outputUri parameter is not supported in Gemini API.");if(void 0!==t_(e,["encryptionSpec"]))throw Error("encryptionSpec parameter is not supported in Gemini API.")}(u,o),o);return n=tg("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,o,s;return t={},null!=(r=t_(e,["sdkHttpResponse"]))&&ty(t,["sdkHttpResponse"],r),null!=(n=t_(e,["name"]))&&ty(t,["name"],n),null!=(i=t_(e,["metadata"]))&&ty(t,["metadata"],i),null!=(o=t_(e,["done"]))&&ty(t,["done"],o),null!=(s=t_(e,["error"]))&&ty(t,["error"],s),t})}}}let iy="x-goog-upload-status";async function i_(e,t,r){var n;let i=await iv(e,t,r),o=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[iy])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async function iE(e,t,r){var n;let i=await iv(e,t,r),o=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[iy])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let s=tv(o),a=new tY;return Object.assign(a,s),a}async function iv(e,t,r){var n,i;let o=0,s=0,a=new tT(new Response),l="upload";for(o=e.size;s=o&&(l+=", finalize");let d=0,p=1e3;for(;d<3&&(null==(n=null==(a=await r.request({path:"",body:c,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(s),"Content-Length":String(u)}}}))?void 0:a.headers)||!n[iy]);)d++,await iA(p),p*=2;if(s+=u,(null==(i=null==a?void 0:a.headers)?void 0:i[iy])!=="active")break;if(o<=s)throw Error("All content has been uploaded, but the upload status is not finalized.")}return a}async function iT(e){return{size:e.size,type:e.type}}function iA(e){return new Promise(t=>setTimeout(t,e))}class iS{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await tc.stat(e)).size,t.type=this.inferMimeType(e),t):await iT(e)}async upload(e,t,r){return"string"==typeof e?await this.uploadFileFromPath(e,t,r):i_(e,t,r)}async uploadToFileSearchStore(e,t,r){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r):iE(e,t,r)}inferMimeType(e){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"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),o=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[iy])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async uploadFileToFileSearchStoreFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),o=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[iy])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let s=tv(o),a=new tY;return Object.assign(a,s),a}async uploadFileFromPathInternal(e,t,r){var n,i;let o,s=0,a=0,l=new tT(new Response),u="upload",c=tf.basename(e);try{if(!(o=await tc.open(e,"r")))throw Error("Failed to open file");for(s=(await o.stat()).size;a=s&&(u+=", finalize");let d=new Uint8Array(e),{bytesRead:p}=await o.read(d,0,e,a);if(p!==e)throw Error(`Failed to read ${e} bytes from file at offset ${a}. bytes actually read: ${p}`);let h=new Blob([d]),f=0,m=1e3;for(;f<3&&(null==(n=null==(l=await r.request({path:"",body:h,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":u,"X-Goog-Upload-Offset":String(a),"Content-Length":String(p),"X-Goog-Upload-File-Name":c}}}))?void 0:l.headers)||!n[iy]);)f++,await iA(m),m*=2;if(a+=p,(null==(i=null==l?void 0:l.headers)?void 0:i[iy])!=="active")break;if(s<=a)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}finally{o&&await o.close()}}}class ib extends rx{async registerFiles(e){if("u"e?e.length>t?e.substring(0,t)+"...":e:"",iw=e=>"master"===e.subscription.plan||e.usage.aiActionsCurrent{if(!iw(n))return{text:"Limite d'actions IA atteinte pour ce mois. Passez au plan Pro !",type:"reflection"};try{let i,o,s,a,l,u,c,d=new iC({apiKey:process.env.GEMINI_API_KEY}),p=(i=e.chapters.findIndex(e=>e.id===t),o=e.chapters.slice(0,i).map((e,t)=>`Chapitre ${t+1} (${e.title}): ${e.summary||iI(e.content.replace(/<[^>]*>?/gm,""),200)}`).join("\n"),s=e.entities.map(e=>`[${e.type}] ${e.name}: ${iI(e.description,150)}`+(e.storyContext?` - V\xc9CU/\xc9VOLUTION DANS L'HISTOIRE: ${iI(e.storyContext,500)}`:"")).join("\n"),a=(e.ideas||[]).map(e=>`[ID\xc9E - ${({todo:"À FAIRE",progress:"EN COURS",done:"TERMINÉ"})[e.status]}] ${e.title}: ${iI(e.description,100)}`).join("\n"),l=e.chapters[i]?.content.replace(/<[^>]*>?/gm,"")||"",c=(u=e.settings)?` PARAM\xc8TRES DU ROMAN: - Genre: ${u.genre} ${u.subGenre?`(${u.subGenre})`:""} - Public: ${u.targetAudience} - Ton: ${u.tone} - Narration: ${u.pov} - Temps: ${u.tense} - Th\xe8mes: ${u.themes} - Synopsis Global: ${iI(u.synopsis||"",500)} `:"",` Tu es un assistant \xe9ditorial expert et un co-auteur cr\xe9atif. L'utilisateur \xe9crit un livre intitul\xe9 "${e.title}". ${c} CONTEXTE DE L'HISTOIRE (R\xe9sum\xe9 des chapitres pr\xe9c\xe9dents): ${o||"Aucun chapitre précédent."} BIBLE DU MONDE (Personnages et Lieux): ${s||"Aucune fiche créée."} BO\xceTE \xc0 ID\xc9ES & NOTES (Pistes de l'auteur): ${a||"Aucune note."} CHAPITRE ACTUEL (Texte brut): ${iI(l,3e3)} STYLE D'\xc9CRITURE SP\xc9CIFIQUE (Instruction de l'auteur): ${e.styleGuide||"Standard, neutre."} TA MISSION: ${r} `),h="master"===n.subscription.plan?"gemini-3-pro-preview":"gemini-3-flash-preview",f=await d.models.generateContent({model:h,contents:p,config:{temperature:.7,responseMimeType:"application/json",responseSchema:{type:ef.OBJECT,properties:{responseType:{type:ef.STRING,enum:["draft","reflection"]},content:{type:ef.STRING}}}}}),m=JSON.parse(f.text||"{}");return{text:m.content||"Erreur de génération.",type:m.responseType||"reflection"}}catch(e){return console.error("AI Generation Error:",e),{text:"Erreur lors de la communication avec l'IA.",type:"reflection"}}},iN=async(e,t,r,n)=>{if(!iw(n))return"Limite d'actions IA atteinte.";try{let n=new iC({apiKey:process.env.GEMINI_API_KEY}),i=`Action: ${t}. Texte: ${e}. Contexte: ${iI(r,1e3)}. Renvoie juste le texte transform\xe9.`,o=await n.models.generateContent({model:"gemini-3-flash-preview",contents:i});return o.text?.trim()||e}catch{return e}};e.s(["generateStoryContent",0,iR,"transformTextServer",0,iN],94666)}]; //# sourceMappingURL=%5Broot-of-the-server%5D__71cad4f2._.js.map