@earendil-works/pi-coding-agent
Version:
Coding agent CLI with read, bash, edit, write tools and session management
45 lines • 951 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-ZGYS4UTC.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-AUUCDC7R.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.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))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",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.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
`)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
Content-Type: ${partContentType}\r
\r
`,typeof currentPart.content=="string"?yield currentPart.content:yield*currentPart.content,yield`\r
`}yield finale}static#proxyAgent;static#fetch;static async#getProxyAgent(){return this.#proxyAgent||=(await import("./https-proxy-agent-LVOO5TPL.js")).HttpsProxyAgent,this.#proxyAgent}static async#getFetch(){let hasWindow=typeof window<"u"&&!!window;return this.#fetch||=hasWindow?window.fetch:(await import("./src-QKGKDFSU.js")).default,this.#fetch}static mergeHeaders(base,...append){base=base instanceof Headers?base:new Headers(base);for(let headers of append)(headers instanceof Headers?headers:new Headers(headers)).forEach((value,key)=>{key==="set-cookie"?base.append(key,value):base.set(key,value)});return base}};exports.Gaxios=Gaxios;_a2=Gaxios}});var require_src=__commonJS({"node_modules/gaxios/build/cjs/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.instance=exports.Gaxios=exports.GaxiosError=void 0;exports.request=request;var gaxios_js_1=require_gaxios();Object.defineProperty(exports,"Gaxios",{enumerable:!0,get:function(){return gaxios_js_1.Gaxios}});var common_js_1=require_common();Object.defineProperty(exports,"GaxiosError",{enumerable:!0,get:function(){return common_js_1.GaxiosError}});__exportStar(require_interceptor(),exports);exports.instance=new gaxios_js_1.Gaxios;async function request(opts){return exports.instance.request(opts)}}});var require_bignumber=__commonJS({"node_modules/bignumber.js/bignumber.js"(exports,module){(function(globalObject){"use strict";var BigNumber,isNumeric=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mathceil=Math.ceil,mathfloor=Math.floor,bignumberError="[BigNumber Error] ",tooManyDigits=bignumberError+"Number primitive has more than 15 significant digits: ",BASE=1e14,LOG_BASE=14,MAX_SAFE_INTEGER=9007199254740991,POWS_TEN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],SQRT_BASE=1e7,MAX=1e9;function clone(configObject){var div,convertBase,parseNumeric,P=BigNumber2.prototype={constructor:BigNumber2,toString:null,valueOf:null},ONE=new BigNumber2(1),DECIMAL_PLACES=20,ROUNDING_MODE=4,TO_EXP_NEG=-7,TO_EXP_POS=21,MIN_EXP=-1e7,MAX_EXP=1e7,CRYPTO=!1,MODULO_MODE=1,POW_PRECISION=0,FORMAT={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ALPHABET="0123456789abcdefghijklmnopqrstuvwxyz",alphabetHasNormalDecimalDigits=!0;function BigNumber2(v,b){var alphabet,c,caseChanged,e,i,isNum,len,str,x=this;if(!(x instanceof BigNumber2))return new BigNumber2(v,b);if(b==null){if(v&&v._isBigNumber===!0){x.s=v.s,!v.c||v.e>MAX_EXP?x.c=x.e=null:v.e<MIN_EXP?x.c=[x.e=0]:(x.e=v.e,x.c=v.c.slice());return}if((isNum=typeof v=="number")&&v*0==0){if(x.s=1/v<0?(v=-v,-1):1,v===~~v){for(e=0,i=v;i>=10;i/=10,e++);e>MAX_EXP?x.c=x.e=null:(x.e=e,x.c=[v]);return}str=String(v)}else{if(!isNumeric.test(str=String(v)))return parseNumeric(x,str,isNum);x.s=str.charCodeAt(0)==45?(str=str.slice(1),-1):1}(e=str.indexOf("."))>-1&&(str=str.replace(".","")),(i=str.search(/e/i))>0?(e<0&&(e=i),e+=+str.slice(i+1),str=str.substring(0,i)):e<0&&(e=str.length)}else{if(intCheck(b,2,ALPHABET.length,"Base"),b==10&&alphabetHasNormalDecimalDigits)return x=new BigNumber2(v),round(x,DECIMAL_PLACES+x.e+1,ROUNDING_MODE);if(str=String(v),isNum=typeof v=="number"){if(v*0!=0)return parseNumeric(x,str,isNum,b);if(x.s=1/v<0?(str=str.slice(1),-1):1,BigNumber2.DEBUG&&str.replace(/^0\.0*|\./,"").length>15)throw Error(tooManyDigits+v)}else x.s=str.charCodeAt(0)===45?(str=str.slice(1),-1):1;for(alphabet=ALPHABET.slice(0,b),e=i=0,len=str.length;i<len;i++)if(alphabet.indexOf(c=str.charAt(i))<0){if(c=="."){if(i>e){e=len;continue}}else if(!caseChanged&&(str==str.toUpperCase()&&(str=str.toLowerCase())||str==str.toLowerCase()&&(str=str.toUpperCase()))){caseChanged=!0,i=-1,e=0;continue}return parseNumeric(x,String(v),isNum,b)}isNum=!1,str=convertBase(str,b,10,x.s),(e=str.indexOf("."))>-1?str=str.replace(".",""):e=str.length}for(i=0;str.charCodeAt(i)===48;i++);for(len=str.length;str.charCodeAt(--len)===48;);if(str=str.slice(i,++len)){if(len-=i,isNum&&BigNumber2.DEBUG&&len>15&&(v>MAX_SAFE_INTEGER||v!==mathfloor(v)))throw Error(tooManyDigits+x.s*v);if((e=e-i-1)>MAX_EXP)x.c=x.e=null;else if(e<MIN_EXP)x.c=[x.e=0];else{if(x.e=e,x.c=[],i=(e+1)%LOG_BASE,e<0&&(i+=LOG_BASE),i<len){for(i&&x.c.push(+str.slice(0,i)),len-=LOG_BASE;i<len;)x.c.push(+str.slice(i,i+=LOG_BASE));i=LOG_BASE-(str=str.slice(i)).length}else i-=len;for(;i--;str+="0");x.c.push(+str)}}else x.c=[x.e=0]}BigNumber2.clone=clone,BigNumber2.ROUND_UP=0,BigNumber2.ROUND_DOWN=1,BigNumber2.ROUND_CEIL=2,BigNumber2.ROUND_FLOOR=3,BigNumber2.ROUND_HALF_UP=4,BigNumber2.ROUND_HALF_DOWN=5,BigNumber2.ROUND_HALF_EVEN=6,BigNumber2.ROUND_HALF_CEIL=7,BigNumber2.ROUND_HALF_FLOOR=8,BigNumber2.EUCLID=9,BigNumber2.config=BigNumber2.set=function(obj){var p,v;if(obj!=null)if(typeof obj=="object"){if(obj.hasOwnProperty(p="DECIMAL_PLACES")&&(v=obj[p],intCheck(v,0,MAX,p),DECIMAL_PLACES=v),obj.hasOwnProperty(p="ROUNDING_MODE")&&(v=obj[p],intCheck(v,0,8,p),ROUNDING_MODE=v),obj.hasOwnProperty(p="EXPONENTIAL_AT")&&(v=obj[p],v&&v.pop?(intCheck(v[0],-MAX,0,p),intCheck(v[1],0,MAX,p),TO_EXP_NEG=v[0],TO_EXP_POS=v[1]):(intCheck(v,-MAX,MAX,p),TO_EXP_NEG=-(TO_EXP_POS=v<0?-v:v))),obj.hasOwnProperty(p="RANGE"))if(v=obj[p],v&&v.pop)intCheck(v[0],-MAX,-1,p),intCheck(v[1],1,MAX,p),MIN_EXP=v[0],MAX_EXP=v[1];else if(intCheck(v,-MAX,MAX,p),v)MIN_EXP=-(MAX_EXP=v<0?-v:v);else throw Error(bignumberError+p+" cannot be zero: "+v);if(obj.hasOwnProperty(p="CRYPTO"))if(v=obj[p],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))CRYPTO=v;else throw CRYPTO=!v,Error(bignumberError+"crypto unavailable");else CRYPTO=v;else throw Error(bignumberError+p+" not true or false: "+v);if(obj.hasOwnProperty(p="MODULO_MODE")&&(v=obj[p],intCheck(v,0,9,p),MODULO_MODE=v),obj.hasOwnProperty(p="POW_PRECISION")&&(v=obj[p],intCheck(v,0,MAX,p),POW_PRECISION=v),obj.hasOwnProperty(p="FORMAT"))if(v=obj[p],typeof v=="object")FORMAT=v;else throw Error(bignumberError+p+" not an object: "+v);if(obj.hasOwnProperty(p="ALPHABET"))if(v=obj[p],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))alphabetHasNormalDecimalDigits=v.slice(0,10)=="0123456789",ALPHABET=v;else throw Error(bignumberError+p+" invalid: "+v)}else throw Error(bignumberError+"Object expected: "+obj);return{DECIMAL_PLACES,ROUNDING_MODE,EXPONENTIAL_AT:[TO_EXP_NEG,TO_EXP_POS],RANGE:[MIN_EXP,MAX_EXP],CRYPTO,MODULO_MODE,POW_PRECISION,FORMAT,ALPHABET}},BigNumber2.isBigNumber=function(v){if(!v||v._isBigNumber!==!0)return!1;if(!BigNumber2.DEBUG)return!0;var i,n,c=v.c,e=v.e,s=v.s;out:if({}.toString.call(c)=="[object Array]"){if((s===1||s===-1)&&e>=-MAX&&e<=MAX&&e===mathfloor(e)){if(c[0]===0){if(e===0&&c.length===1)return!0;break out}if(i=(e+1)%LOG_BASE,i<1&&(i+=LOG_BASE),String(c[0]).length==i){for(i=0;i<c.length;i++)if(n=c[i],n<0||n>=BASE||n!==mathfloor(n))break out;if(n!==0)return!0}}}else if(c===null&&e===null&&(s===null||s===1||s===-1))return!0;throw Error(bignumberError+"Invalid BigNumber: "+v)},BigNumber2.maximum=BigNumber2.max=function(){return maxOrMin(arguments,-1)},BigNumber2.minimum=BigNumber2.min=function(){return maxOrMin(arguments,1)},BigNumber2.random=(function(){var pow2_53=9007199254740992,random53bitInt=Math.random()*pow2_53&2097151?function(){return mathfloor(Math.random()*pow2_53)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(dp){var a,b,e,k,v,i=0,c=[],rand=new BigNumber2(ONE);if(dp==null?dp=DECIMAL_PLACES:intCheck(dp,0,MAX),k=mathceil(dp/LOG_BASE),CRYPTO)if(crypto.getRandomValues){for(a=crypto.getRandomValues(new Uint32Array(k*=2));i<k;)v=a[i]*131072+(a[i+1]>>>11),v>=9e15?(b=crypto.getRandomValues(new Uint32Array(2)),a[i]=b[0],a[i+1]=b[1]):(c.push(v%1e14),i+=2);i=k/2}else if(crypto.randomBytes){for(a=crypto.randomBytes(k*=7);i<k;)v=(a[i]&31)*281474976710656+a[i+1]*1099511627776+a[i+2]*4294967296+a[i+3]*16777216+(a[i+4]<<16)+(a[i+5]<<8)+a[i+6],v>=9e15?crypto.randomBytes(7).copy(a,i):(c.push(v%1e14),i+=7);i=k/7}else throw CRYPTO=!1,Error(bignumberError+"crypto unavailable");if(!CRYPTO)for(;i<k;)v=random53bitInt(),v<9e15&&(c[i++]=v%1e14);for(k=c[--i],dp%=LOG_BASE,k&&dp&&(v=POWS_TEN[LOG_BASE-dp],c[i]=mathfloor(k/v)*v);c[i]===0;c.pop(),i--);if(i<0)c=[e=0];else{for(e=-1;c[0]===0;c.splice(0,1),e-=LOG_BASE);for(i=1,v=c[0];v>=10;v/=10,i++);i<LOG_BASE&&(e-=LOG_BASE-i)}return rand.e=e,rand.c=c,rand}})(),BigNumber2.sum=function(){for(var i=1,args=arguments,sum=new BigNumber2(args[0]);i<args.length;)sum=sum.plus(args[i++]);return sum},convertBase=(function(){var decimal="0123456789";function toBaseOut(str,baseIn,baseOut,alphabet){for(var j,arr=[0],arrL,i=0,len=str.length;i<len;){for(arrL=arr.length;arrL--;arr[arrL]*=baseIn);for(arr[0]+=alphabet.indexOf(str.charAt(i++)),j=0;j<arr.length;j++)arr[j]>baseOut-1&&(arr[j+1]==null&&(arr[j+1]=0),arr[j+1]+=arr[j]/baseOut|0,arr[j]%=baseOut)}return arr.reverse()}return function(str,baseIn,baseOut,sign,callerIsToString){var alphabet,d,e,k,r,x,xc,y,i=str.indexOf("."),dp=DECIMAL_PLACES,rm=ROUNDING_MODE;for(i>=0&&(k=POW_PRECISION,POW_PRECISION=0,str=str.replace(".",""),y=new BigNumber2(baseIn),x=y.pow(str.length-i),POW_PRECISION=k,y.c=toBaseOut(toFixedPoint(coeffToString(x.c),x.e,"0"),10,baseOut,decimal),y.e=y.c.length),xc=toBaseOut(str,baseIn,baseOut,callerIsToString?(alphabet=ALPHABET,decimal):(alphabet=decimal,ALPHABET)),e=k=xc.length;xc[--k]==0;xc.pop());if(!xc[0])return alphabet.charAt(0);if(i<0?--e:(x.c=xc,x.e=e,x.s=sign,x=div(x,y,dp,rm,baseOut),xc=x.c,r=x.r,e=x.e),d=e+dp+1,i=xc[d],k=baseOut/2,r=r||d<0||xc[d+1]!=null,r=rm<4?(i!=null||r)&&(rm==0||rm==(x.s<0?3:2)):i>k||i==k&&(rm==4||r||rm==6&&xc[d-1]&1||rm==(x.s<0?8:7)),d<1||!xc[0])str=r?toFixedPoint(alphabet.charAt(1),-dp,alphabet.charAt(0)):alphabet.charAt(0);else{if(xc.length=d,r)for(--baseOut;++xc[--d]>baseOut;)xc[d]=0,d||(++e,xc=[1].concat(xc));for(k=xc.length;!xc[--k];);for(i=0,str="";i<=k;str+=alphabet.charAt(xc[i++]));str=toFixedPoint(str,e,alphabet.charAt(0))}return str}})(),div=(function(){function multiply(x,k,base){var m,temp,xlo,xhi,carry=0,i=x.length,klo=k%SQRT_BASE,khi=k/SQRT_BASE|0;for(x=x.slice();i--;)xlo=x[i]%SQRT_BASE,xhi=x[i]/SQRT_BASE|0,m=khi*xlo+xhi*klo,temp=klo*xlo+m%SQRT_BASE*SQRT_BASE+carry,carry=(temp/base|0)+(m/SQRT_BASE|0)+khi*xhi,x[i]=temp%base;return carry&&(x=[carry].concat(x)),x}function compare2(a,b,aL,bL){var i,cmp;if(aL!=bL)cmp=aL>bL?1:-1;else for(i=cmp=0;i<aL;i++)if(a[i]!=b[i]){cmp=a[i]>b[i]?1:-1;break}return cmp}function subtract(a,b,aL,base){for(var i=0;aL--;)a[aL]-=i,i=a[aL]<b[aL]?1:0,a[aL]=i*base+a[aL]-b[aL];for(;!a[0]&&a.length>1;a.splice(0,1));}return function(x,y,dp,rm,base){var cmp,e,i,more,n,prod,prodL,q,qc,rem,remL,rem0,xi,xL,yc0,yL,yz,s=x.s==y.s?1:-1,xc=x.c,yc=y.c;if(!xc||!xc[0]||!yc||!yc[0])return new BigNumber2(!x.s||!y.s||(xc?yc&&xc[0]==yc[0]:!yc)?NaN:xc&&xc[0]==0||!yc?s*0:s/0);for(q=new BigNumber2(s),qc=q.c=[],e=x.e-y.e,s=dp+e+1,base||(base=BASE,e=bitFloor(x.e/LOG_BASE)-bitFloor(y.e/LOG_BASE),s=s/LOG_BASE|0),i=0;yc[i]==(xc[i]||0);i++);if(yc[i]>(xc[i]||0)&&e--,s<0)qc.push(1),more=!0;else{for(xL=xc.length,yL=yc.length,i=0,s+=2,n=mathfloor(base/(yc[0]+1)),n>1&&(yc=multiply(yc,n,base),xc=multiply(xc,n,base),yL=yc.length,xL=xc.length),xi=yL,rem=xc.slice(0,yL),remL=rem.length;remL<yL;rem[remL++]=0);yz=yc.slice(),yz=[0].concat(yz),yc0=yc[0],yc[1]>=base/2&&yc0++;do{if(n=0,cmp=compare2(yc,rem,yL,remL),cmp<0){if(rem0=rem[0],yL!=remL&&(rem0=rem0*base+(rem[1]||0)),n=mathfloor(rem0/yc0),n>1)for(n>=base&&(n=base-1),prod=multiply(yc,n,base),prodL=prod.length,remL=rem.length;compare2(prod,rem,prodL,remL)==1;)n--,subtract(prod,yL<prodL?yz:yc,prodL,base),prodL=prod.length,cmp=1;else n==0&&(cmp=n=1),prod=yc.slice(),prodL=prod.length;if(prodL<remL&&(prod=[0].concat(prod)),subtract(rem,prod,remL,base),remL=rem.length,cmp==-1)for(;compare2(yc,rem,yL,remL)<1;)n++,subtract(rem,yL<remL?yz:yc,remL,base),remL=rem.length}else cmp===0&&(n++,rem=[0]);qc[i++]=n,rem[0]?rem[remL++]=xc[xi]||0:(rem=[xc[xi]],remL=1)}while((xi++<xL||rem[0]!=null)&&s--);more=rem[0]!=null,qc[0]||qc.splice(0,1)}if(base==BASE){for(i=1,s=qc[0];s>=10;s/=10,i++);round(q,dp+(q.e=i+e*LOG_BASE-1)+1,rm,more)}else q.e=e,q.r=+more;return q}})();function format(n,i,rm,id){var c0,e,ne,len,str;if(rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),!n.c)return n.toString();if(c0=n.c[0],ne=n.e,i==null)str=coeffToString(n.c),str=id==1||id==2&&(ne<=TO_EXP_NEG||ne>=TO_EXP_POS)?toExponential(str,ne):toFixedPoint(str,ne,"0");else if(n=round(new BigNumber2(n),i,rm),e=n.e,str=coeffToString(n.c),len=str.length,id==1||id==2&&(i<=e||e<=TO_EXP_NEG)){for(;len<i;str+="0",len++);str=toExponential(str,e)}else if(i-=ne+(id===2&&e>ne),str=toFixedPoint(str,e,"0"),e+1>len){if(--i>0)for(str+=".";i--;str+="0");}else if(i+=e-len,i>0)for(e+1==len&&(str+=".");i--;str+="0");return n.s<0&&c0?"-"+str:str}function maxOrMin(args,n){for(var k,y,i=1,x=new BigNumber2(args[0]);i<args.length;i++)y=new BigNumber2(args[i]),(!y.s||(k=compare(x,y))===n||k===0&&x.s===n)&&(x=y);return x}function normalise(n,c,e){for(var i=1,j=c.length;!c[--j];c.pop());for(j=c[0];j>=10;j/=10,i++);return(e=i+e*LOG_BASE-1)>MAX_EXP?n.c=n.e=null:e<MIN_EXP?n.c=[n.e=0]:(n.e=e,n.c=c),n}parseNumeric=(function(){var basePrefix=/^(-?)0([xbo])(?=\w[\w.]*$)/i,dotAfter=/^([^.]+)\.$/,dotBefore=/^\.([^.]+)$/,isInfinityOrNaN=/^-?(Infinity|NaN)$/,whitespaceOrPlus=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(x,str,isNum,b){var base,s=isNum?str:str.replace(whitespaceOrPlus,"");if(isInfinityOrNaN.test(s))x.s=isNaN(s)?null:s<0?-1:1;else{if(!isNum&&(s=s.replace(basePrefix,function(m,p1,p2){return base=(p2=p2.toLowerCase())=="x"?16:p2=="b"?2:8,!b||b==base?p1:m}),b&&(base=b,s=s.replace(dotAfter,"$1").replace(dotBefore,"0.$1")),str!=s))return new BigNumber2(s,base);if(BigNumber2.DEBUG)throw Error(bignumberError+"Not a"+(b?" base "+b:"")+" number: "+str);x.s=null}x.c=x.e=null}})();function round(x,sd,rm,r){var d,i,j,k,n,ni,rd,xc=x.c,pows10=POWS_TEN;if(xc){out:{for(d=1,k=xc[0];k>=10;k/=10,d++);if(i=sd-d,i<0)i+=LOG_BASE,j=sd,n=xc[ni=0],rd=mathfloor(n/pows10[d-j-1]%10);else if(ni=mathceil((i+1)/LOG_BASE),ni>=xc.length)if(r){for(;xc.length<=ni;xc.push(0));n=rd=0,d=1,i%=LOG_BASE,j=i-LOG_BASE+1}else break out;else{for(n=k=xc[ni],d=1;k>=10;k/=10,d++);i%=LOG_BASE,j=i-LOG_BASE+d,rd=j<0?0:mathfloor(n/pows10[d-j-1]%10)}if(r=r||sd<0||xc[ni+1]!=null||(j<0?n:n%pows10[d-j-1]),r=rm<4?(rd||r)&&(rm==0||rm==(x.s<0?3:2)):rd>5||rd==5&&(rm==4||r||rm==6&&(i>0?j>0?n/pows10[d-j]:0:xc[ni-1])%10&1||rm==(x.s<0?8:7)),sd<1||!xc[0])return xc.length=0,r?(sd-=x.e+1,xc[0]=pows10[(LOG_BASE-sd%LOG_BASE)%LOG_BASE],x.e=-sd||0):xc[0]=x.e=0,x;if(i==0?(xc.length=ni,k=1,ni--):(xc.length=ni+1,k=pows10[LOG_BASE-i],xc[ni]=j>0?mathfloor(n/pows10[d-j]%pows10[j])*k:0),r)for(;;)if(ni==0){for(i=1,j=xc[0];j>=10;j/=10,i++);for(j=xc[0]+=k,k=1;j>=10;j/=10,k++);i!=k&&(x.e++,xc[0]==BASE&&(xc[0]=1));break}else{if(xc[ni]+=k,xc[ni]!=BASE)break;xc[ni--]=0,k=1}for(i=xc.length;xc[--i]===0;xc.pop());}x.e>MAX_EXP?x.c=x.e=null:x.e<MIN_EXP&&(x.c=[x.e=0])}return x}function valueOf(n){var str,e=n.e;return e===null?n.toString():(str=coeffToString(n.c),str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(str,e):toFixedPoint(str,e,"0"),n.s<0?"-"+str:str)}return P.absoluteValue=P.abs=function(){var x=new BigNumber2(this);return x.s<0&&(x.s=1),x},P.comparedTo=function(y,b){return compare(this,new BigNumber2(y,b))},P.decimalPlaces=P.dp=function(dp,rm){var c,n,v,x=this;if(dp!=null)return intCheck(dp,0,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),dp+x.e+1,rm);if(!(c=x.c))return null;if(n=((v=c.length-1)-bitFloor(this.e/LOG_BASE))*LOG_BASE,v=c[v])for(;v%10==0;v/=10,n--);return n<0&&(n=0),n},P.dividedBy=P.div=function(y,b){return div(this,new BigNumber2(y,b),DECIMAL_PLACES,ROUNDING_MODE)},P.dividedToIntegerBy=P.idiv=function(y,b){return div(this,new BigNumber2(y,b),0,1)},P.exponentiatedBy=P.pow=function(n,m){var half,isModExp,i,k,more,nIsBig,nIsNeg,nIsOdd,y,x=this;if(n=new BigNumber2(n),n.c&&!n.isInteger())throw Error(bignumberError+"Exponent not an integer: "+valueOf(n));if(m!=null&&(m=new BigNumber2(m)),nIsBig=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return y=new BigNumber2(Math.pow(+valueOf(x),nIsBig?n.s*(2-isOdd(n)):+valueOf(n))),m?y.mod(m):y;if(nIsNeg=n.s<0,m){if(m.c?!m.c[0]:!m.s)return new BigNumber2(NaN);isModExp=!nIsNeg&&x.isInteger()&&m.isInteger(),isModExp&&(x=x.mod(m))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||nIsBig&&x.c[1]>=24e7:x.c[0]<8e13||nIsBig&&x.c[0]<=9999975e7)))return k=x.s<0&&isOdd(n)?-0:0,x.e>-1&&(k=1/k),new BigNumber2(nIsNeg?1/k:k);POW_PRECISION&&(k=mathceil(POW_PRECISION/LOG_BASE+2))}for(nIsBig?(half=new BigNumber2(.5),nIsNeg&&(n.s=1),nIsOdd=isOdd(n)):(i=Math.abs(+valueOf(n)),nIsOdd=i%2),y=new BigNumber2(ONE);;){if(nIsOdd){if(y=y.times(x),!y.c)break;k?y.c.length>k&&(y.c.length=k):isModExp&&(y=y.mod(m))}if(i){if(i=mathfloor(i/2),i===0)break;nIsOdd=i%2}else if(n=n.times(half),round(n,n.e+1,1),n.e>14)nIsOdd=isOdd(n);else{if(i=+valueOf(n),i===0)break;nIsOdd=i%2}x=x.times(x),k?x.c&&x.c.length>k&&(x.c.length=k):isModExp&&(x=x.mod(m))}return isModExp?y:(nIsNeg&&(y=ONE.div(y)),m?y.mod(m):k?round(y,POW_PRECISION,ROUNDING_MODE,more):y)},P.integerValue=function(rm){var n=new BigNumber2(this);return rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(n,n.e+1,rm)},P.isEqualTo=P.eq=function(y,b){return compare(this,new BigNumber2(y,b))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(y,b){return compare(this,new BigNumber2(y,b))>0},P.isGreaterThanOrEqualTo=P.gte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===1||b===0},P.isInteger=function(){return!!this.c&&bitFloor(this.e/LOG_BASE)>this.c.length-2},P.isLessThan=P.lt=function(y,b){return compare(this,new BigNumber2(y,b))<0},P.isLessThanOrEqualTo=P.lte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===-1||b===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(y,b){var i,j,t,xLTy,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.plus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return xc?(y.s=-b,y):new BigNumber2(yc?x:NaN);if(!xc[0]||!yc[0])return yc[0]?(y.s=-b,y):new BigNumber2(xc[0]?x:ROUNDING_MODE==3?-0:0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for((xLTy=a<0)?(a=-a,t=xc):(ye=xe,t=yc),t.reverse(),b=a;b--;t.push(0));t.reverse()}else for(j=(xLTy=(a=xc.length)<(b=yc.length))?a:b,a=b=0;b<j;b++)if(xc[b]!=yc[b]){xLTy=xc[b]<yc[b];break}if(xLTy&&(t=xc,xc=yc,yc=t,y.s=-y.s),b=(j=yc.length)-(i=xc.length),b>0)for(;b--;xc[i++]=0);for(b=BASE-1;j>a;){if(xc[--j]<yc[j]){for(i=j;i&&!xc[--i];xc[i]=b);--xc[i],xc[j]+=BASE}xc[j]-=yc[j]}for(;xc[0]==0;xc.splice(0,1),--ye);return xc[0]?normalise(y,xc,ye):(y.s=ROUNDING_MODE==3?-1:1,y.c=[y.e=0],y)},P.modulo=P.mod=function(y,b){var q,s,x=this;return y=new BigNumber2(y,b),!x.c||!y.s||y.c&&!y.c[0]?new BigNumber2(NaN):!y.c||x.c&&!x.c[0]?new BigNumber2(x):(MODULO_MODE==9?(s=y.s,y.s=1,q=div(x,y,0,3),y.s=s,q.s*=s):q=div(x,y,0,MODULO_MODE),y=x.minus(q.times(y)),!y.c[0]&&MODULO_MODE==1&&(y.s=x.s),y)},P.multipliedBy=P.times=function(y,b){var c,e,i,j,k,m,xcL,xlo,xhi,ycL,ylo,yhi,zc,base,sqrtBase,x=this,xc=x.c,yc=(y=new BigNumber2(y,b)).c;if(!xc||!yc||!xc[0]||!yc[0])return!x.s||!y.s||xc&&!xc[0]&&!yc||yc&&!yc[0]&&!xc?y.c=y.e=y.s=null:(y.s*=x.s,!xc||!yc?y.c=y.e=null:(y.c=[0],y.e=0)),y;for(e=bitFloor(x.e/LOG_BASE)+bitFloor(y.e/LOG_BASE),y.s*=x.s,xcL=xc.length,ycL=yc.length,xcL<ycL&&(zc=xc,xc=yc,yc=zc,i=xcL,xcL=ycL,ycL=i),i=xcL+ycL,zc=[];i--;zc.push(0));for(base=BASE,sqrtBase=SQRT_BASE,i=ycL;--i>=0;){for(c=0,ylo=yc[i]%sqrtBase,yhi=yc[i]/sqrtBase|0,k=xcL,j=i+k;j>i;)xlo=xc[--k]%sqrtBase,xhi=xc[k]/sqrtBase|0,m=yhi*xlo+xhi*ylo,xlo=ylo*xlo+m%sqrtBase*sqrtBase+zc[j]+c,c=(xlo/base|0)+(m/sqrtBase|0)+yhi*xhi,zc[j--]=xlo%base;zc[j]=c}return c?++e:zc.splice(0,1),normalise(y,zc,e)},P.negated=function(){var x=new BigNumber2(this);return x.s=-x.s||null,x},P.plus=function(y,b){var t,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.minus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return new BigNumber2(a/0);if(!xc[0]||!yc[0])return yc[0]?y:new BigNumber2(xc[0]?x:a*0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for(a>0?(ye=xe,t=yc):(a=-a,t=xc),t.reverse();a--;t.push(0));t.reverse()}for(a=xc.length,b=yc.length,a-b<0&&(t=yc,yc=xc,xc=t,b=a),a=0;b;)a=(xc[--b]=xc[b]+yc[b]+a)/BASE|0,xc[b]=BASE===xc[b]?0:xc[b]%BASE;return a&&(xc=[a].concat(xc),++ye),normalise(y,xc,ye)},P.precision=P.sd=function(sd,rm){var c,n,v,x=this;if(sd!=null&&sd!==!!sd)return intCheck(sd,1,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),sd,rm);if(!(c=x.c))return null;if(v=c.length-1,n=v*LOG_BASE+1,v=c[v]){for(;v%10==0;v/=10,n--);for(v=c[0];v>=10;v/=10,n++);}return sd&&x.e+1>n&&(n=x.e+1),n},P.shiftedBy=function(k){return intCheck(k,-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER),this.times("1e"+k)},P.squareRoot=P.sqrt=function(){var m,n,r,rep,t,x=this,c=x.c,s=x.s,e=x.e,dp=DECIMAL_PLACES+4,half=new BigNumber2("0.5");if(s!==1||!c||!c[0])return new BigNumber2(!s||s<0&&(!c||c[0])?NaN:c?x:1/0);if(s=Math.sqrt(+valueOf(x)),s==0||s==1/0?(n=coeffToString(c),(n.length+e)%2==0&&(n+="0"),s=Math.sqrt(+n),e=bitFloor((e+1)/2)-(e<0||e%2),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new BigNumber2(n)):r=new BigNumber2(s+""),r.c[0]){for(e=r.e,s=e+dp,s<3&&(s=0);;)if(t=r,r=half.times(t.plus(div(x,t,dp,1))),coeffToString(t.c).slice(0,s)===(n=coeffToString(r.c)).slice(0,s))if(r.e<e&&--s,n=n.slice(s-3,s+1),n=="9999"||!rep&&n=="4999"){if(!rep&&(round(t,t.e+DECIMAL_PLACES+2,0),t.times(t).eq(x))){r=t;break}dp+=4,s+=4,rep=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(round(r,r.e+DECIMAL_PLACES+2,1),m=!r.times(r).eq(x));break}}return round(r,r.e+DECIMAL_PLACES+1,ROUNDING_MODE,m)},P.toExponential=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp++),format(this,dp,rm,1)},P.toFixed=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp=dp+this.e+1),format(this,dp,rm)},P.toFormat=function(dp,rm,format2){var str,x=this;if(format2==null)dp!=null&&rm&&typeof rm=="object"?(format2=rm,rm=null):dp&&typeof dp=="object"?(format2=dp,dp=rm=null):format2=FORMAT;else if(typeof format2!="object")throw Error(bignumberError+"Argument not an object: "+format2);if(str=x.toFixed(dp,rm),x.c){var i,arr=str.split("."),g1=+format2.groupSize,g2=+format2.secondaryGroupSize,groupSeparator=format2.groupSeparator||"",intPart=arr[0],fractionPart=arr[1],isNeg=x.s<0,intDigits=isNeg?intPart.slice(1):intPart,len=intDigits.length;if(g2&&(i=g1,g1=g2,g2=i,len-=i),g1>0&&len>0){for(i=len%g1||g1,intPart=intDigits.substr(0,i);i<len;i+=g1)intPart+=groupSeparator+intDigits.substr(i,g1);g2>0&&(intPart+=groupSeparator+intDigits.slice(i)),isNeg&&(intPart="-"+intPart)}str=fractionPart?intPart+(format2.decimalSeparator||"")+((g2=+format2.fractionGroupSize)?fractionPart.replace(new RegExp("\\d{"+g2+"}\\B","g"),"$&"+(format2.fractionGroupSeparator||"")):fractionPart):intPart}return(format2.prefix||"")+str+(format2.suffix||"")},P.toFraction=function(md){var d,d0,d1,d2,e,exp,n,n0,n1,q,r,s,x=this,xc=x.c;if(md!=null&&(n=new BigNumber2(md),!n.isInteger()&&(n.c||n.s!==1)||n.lt(ONE)))throw Error(bignumberError+"Argument "+(n.isInteger()?"out of range: ":"not an integer: ")+valueOf(n));if(!xc)return new BigNumber2(x);for(d=new BigNumber2(ONE),n1=d0=new BigNumber2(ONE),d1=n0=new BigNumber2(ONE),s=coeffToString(xc),e=d.e=s.length-x.e-1,d.c[0]=POWS_TEN[(exp=e%LOG_BASE)<0?LOG_BASE+exp:exp],md=!md||n.comparedTo(d)>0?e>0?d:n1:n,exp=MAX_EXP,MAX_EXP=1/0,n=new BigNumber2(s),n0.c[0]=0;q=div(n,d,0,1),d2=d0.plus(q.times(d1)),d2.comparedTo(md)!=1;)d0=d1,d1=d2,n1=n0.plus(q.times(d2=n1)),n0=d2,d=n.minus(q.times(d2=d)),n=d2;return d2=div(md.minus(d0),d1,0,1),n0=n0.plus(d2.times(n1)),d0=d0.plus(d2.times(d1)),n0.s=n1.s=x.s,e=e*2,r=div(n1,d1,e,ROUNDING_MODE).minus(x).abs().comparedTo(div(n0,d0,e,ROUNDING_MODE).minus(x).abs())<1?[n1,d1]:[n0,d0],MAX_EXP=exp,r},P.toNumber=function(){return+valueOf(this)},P.toPrecision=function(sd,rm){return sd!=null&&intCheck(sd,1,MAX),format(this,sd,rm,2)},P.toString=function(b){var str,n=this,s=n.s,e=n.e;return e===null?s?(str="Infinity",s<0&&(str="-"+str)):str="NaN":(b==null?str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(coeffToString(n.c),e):toFixedPoint(coeffToString(n.c),e,"0"):b===10&&alphabetHasNormalDecimalDigits?(n=round(new BigNumber2(n),DECIMAL_PLACES+e+1,ROUNDING_MODE),str=toFixedPoint(coeffToString(n.c),n.e,"0")):(intCheck(b,2,ALPHABET.length,"Base"),str=convertBase(toFixedPoint(coeffToString(n.c),e,"0"),10,b,s,!0)),s<0&&n.c[0]&&(str="-"+str)),str},P.valueOf=P.toJSON=function(){return valueOf(this)},P._isBigNumber=!0,configObject!=null&&BigNumber2.set(configObject),BigNumber2}function bitFloor(n){var i=n|0;return n>0||n===i?i:i-1}function coeffToString(a){for(var s,z,i=1,j=a.length,r=a[0]+"";i<j;){for(s=a[i++]+"",z=LOG_BASE-s.length;z--;s="0"+s);r+=s}for(j=r.length;r.charCodeAt(--j)===48;);return r.slice(0,j+1||1)}function compare(x,y){var a,b,xc=x.c,yc=y.c,i=x.s,j=y.s,k=x.e,l=y.e;if(!i||!j)return null;if(a=xc&&!xc[0],b=yc&&!yc[0],a||b)return a?b?0:-j:i;if(i!=j)return i;if(a=i<0,b=k==l,!xc||!yc)return b?0:!xc^a?1:-1;if(!b)return k>l^a?1:-1;for(j=(k=xc.length)<(l=yc.length)?k:l,i=0;i<j;i++)if(xc[i]!=yc[i])return xc[i]>yc[i]^a?1:-1;return k==l?0:k>l^a?1:-1}function intCheck(n,min,max,name){if(n<min||n>max||n!==mathfloor(n))throw Error(bignumberError+(name||"Argument")+(typeof n=="number"?n<min||n>max?" out of range: ":" not an integer: ":" not a primitive number: ")+String(n))}function isOdd(n){var k=n.c.length-1;return bitFloor(n.e/LOG_BASE)==k&&n.c[k]%2!=0}function toExponential(str,e){return(str.length>1?str.charAt(0)+"."+str.slice(1):str)+(e<0?"e":"e+")+e}function toFixedPoint(str,e,z){var len,zs;if(e<0){for(zs=z+".";++e;zs+=z);str=zs+str}else if(len=str.length,++e>len){for(zs=z,e-=len;--e;zs+=z);str+=zs}else e<len&&(str=str.slice(0,e)+"."+str.slice(e));return str}BigNumber=clone(),BigNumber.default=BigNumber.BigNumber=BigNumber,typeof define=="function"&&define.amd?define(function(){return BigNumber}):typeof module<"u"&&module.exports?module.exports=BigNumber:(globalObject||(globalObject=typeof self<"u"&&self?self:window),globalObject.BigNumber=BigNumber)})(exports)}});var require_stringify=__commonJS({"node_modules/json-bigint/lib/stringify.js"(exports,module){var BigNumber=require_bignumber(),JSON2=module.exports;(function(){"use strict";function f(n){return n<10?"0"+n:n}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){return escapable.lastIndex=0,escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c=="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key],isBigNumber=value!=null&&(value instanceof BigNumber||BigNumber.isBigNumber(value));switch(value&&typeof value=="object"&&typeof value.toJSON=="function"&&(value=value.toJSON(key)),typeof rep=="function"&&(value=rep.call(holder,key,value)),typeof value){case"string":return isBigNumber?value:quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":case"bigint":return String(value);case"object":if(!value)return"null";if(gap+=indent,partial=[],Object.prototype.toString.apply(value)==="[object Array]"){for(length=value.length,i=0;i<length;i+=1)partial[i]=str(i,value)||"null";return v=partial.length===0?"[]":gap?`[
`+gap+partial.join(`,
`+gap)+`
`+mind+"]":"["+partial.join(",")+"]",gap=mind,v}if(rep&&typeof rep=="object")for(length=rep.length,i=0;i<length;i+=1)typeof rep[i]=="string"&&(k=rep[i],v=str(k,value),v&&partial.push(quote(k)+(gap?": ":":")+v));else Object.keys(value).forEach(function(k2){var v2=str(k2,value);v2&&partial.push(quote(k2)+(gap?": ":":")+v2)});return v=partial.length===0?"{}":gap?`{
`+gap+partial.join(`,
`+gap)+`
`+mind+"}":"{"+partial.join(",")+"}",gap=mind,v}}typeof JSON2.stringify!="function"&&(JSON2.stringify=function(value,replacer,space){var i;if(gap="",indent="",typeof space=="number")for(i=0;i<space;i+=1)indent+=" ";else typeof space=="string"&&(indent=space);if(rep=replacer,replacer&&typeof replacer!="function"&&(typeof replacer!="object"||typeof replacer.length!="number"))throw new Error("JSON.stringify");return str("",{"":value})})})()}});var require_parse=__commonJS({"node_modules/json-bigint/lib/parse.js"(exports,module){var BigNumber=null,suspectProtoRx=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,suspectConstructorRx=/(?: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)/,json_parse=function(options){"use strict";var _options={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(options!=null){if(options.strict===!0&&(_options.strict=!0),options.storeAsString===!0&&(_options.storeAsString=!0),_options.alwaysParseAsBig=options.alwaysParseAsBig===!0?options.alwaysParseAsBig:!1,_options.useNativeBigInt=options.useNativeBigInt===!0?options.useNativeBigInt:!1,typeof options.constructorAction<"u")if(options.constructorAction==="error"||options.constructorAction==="ignore"||options.constructorAction==="preserve")_options.constructorAction=options.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`);if(typeof options.protoAction<"u")if(options.protoAction==="error"||options.protoAction==="ignore"||options.protoAction==="preserve")_options.protoAction=options.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`)}var at,ch,escapee={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
`,r:"\r",t:" "},text,error=function(m){throw{name:"SyntaxError",message:m,at,text}},next=function(c){return c&&c!==ch&&error("Expected '"+c+"' instead of '"+ch+"'"),ch=text.charAt(at),at+=1,ch},number=function(){var number2,string2="";for(ch==="-"&&(string2="-",next("-"));ch>="0"&&ch<="9";)string2+=ch,next();if(ch===".")for(string2+=".";next()&&ch>="0"&&ch<="9";)string2+=ch;if(ch==="e"||ch==="E")for(string2+=ch,next(),(ch==="-"||ch==="+")&&(string2+=ch,next());ch>="0"&&ch<="9";)string2+=ch,next();if(number2=+string2,!isFinite(number2))error("Bad number");else return BigNumber==null&&(BigNumber=require_bignumber()),string2.length>15?_options.storeAsString?string2:_options.useNativeBigInt?BigInt(string2):new BigNumber(string2):_options.alwaysParseAsBig?_options.useNativeBigInt?BigInt(number2):new BigNumber(number2):number2},string=function(){var hex,i,string2="",uffff;if(ch==='"')for(var startAt=at;next();){if(ch==='"')return at-1>startAt&&(string2+=text.substring(startAt,at-1)),next(),string2;if(ch==="\\"){if(at-1>startAt&&(string2+=text.substring(startAt,at-1)),next(),ch==="u"){for(uffff=0,i=0;i<4&&(hex=parseInt(next(),16),!!isFinite(hex));i+=1)uffff=uffff*16+hex;string2+=String.fromCharCode(uffff)}else if(typeof escapee[ch]=="string")string2+=escapee[ch];else break;startAt=at}}error("Bad string")},white=function(){for(;ch&&ch<=" ";)next()},word=function(){switch(ch){case"t":return next("t"),next("r"),next("u"),next("e"),!0;case"f":return next("f"),next("a"),next("l"),next("s"),next("e"),!1;case"n":return next("n"),next("u"),next("l"),next("l"),null}error("Unexpected '"+ch+"'")},value,array=function(){var array2=[];if(ch==="["){if(next("["),white(),ch==="]")return next("]"),array2;for(;ch;){if(array2.push(value()),white(),ch==="]")return next("]"),array2;next(","),white()}}error("Bad array")},object=function(){var key,object2=Object.create(null);if(ch==="{"){if(next("{"),white(),ch==="}")return next("}"),object2;for(;ch;){if(key=string(),white(),next(":"),_options.strict===!0&&Object.hasOwnProperty.call(object2,key)&&error('Duplicate key "'+key+'"'),suspectProtoRx.test(key)===!0?_options.protoAction==="error"?error("Object contains forbidden prototype property"):_options.protoAction==="ignore"?value():object2[key]=value():suspectConstructorRx.test(key)===!0?_options.constructorAction==="error"?error("Object contains forbidden constructor property"):_options.constructorAction==="ignore"?value():object2[key]=value():object2[key]=value(),white(),ch==="}")return next("}"),object2;next(","),white()}}error("Bad object")};return value=function(){switch(white(),ch){case"{":return object();case"[":return array();case'"':return string();case"-":return number();default:return ch>="0"&&ch<="9"?number():word()}},function(source,reviver){var result;return text=source+"",at=0,ch=" ",result=value(),white(),ch&&error("Syntax error"),typeof reviver=="function"?(function walk(holder,key){var k,v,value2=holder[key];return value2&&typeof value2=="object"&&Object.keys(value2).forEach(function(k2){v=walk(value2,k2),v!==void 0?value2[k2]=v:delete value2[k2]}),reviver.call(holder,key,value2)})({"":result},""):result}};module.exports=json_parse}});var require_json_bigint=__commonJS({"node_modules/json-bigint/index.js"(exports,module){var json_stringify=require_stringify().stringify,json_parse=require_parse();module.exports=function(options){return{parse:json_parse(options),stringify:json_stringify}};module.exports.parse=json_parse();module.exports.stringify=json_stringify}});var require_gcp_residency=__commonJS({"node_modules/gcp-metadata/build/src/gcp-residency.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GCE_LINUX_BIOS_PATHS=void 0;exports.isGoogleCloudServerless=isGoogleCloudServerless;exports.isGoogleComputeEngineLinux=isGoogleComputeEngineLinux;exports.isGoogleComputeEngineMACAddress=isGoogleComputeEngineMACAddress;exports.isGoogleComputeEngine=isGoogleComputeEngine;exports.detectGCPResidency=detectGCPResidency;var fs_1=__require("fs"),os_1=__require("os");exports.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var GCE_MAC_ADDRESS_REGEX=/^42:01/;function isGoogleCloudServerless(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function isGoogleComputeEngineLinux(){if((0,os_1.platform)()!=="linux")return!1;try{(0,fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let biosVendor=(0,fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(biosVendor)}catch{return!1}}function isGoogleComputeEngineMACAddress(){let interfaces=(0,os_1.networkInterfaces)();for(let item of Object.values(interfaces))if(item){for(let{mac}of item)if(GCE_MAC_ADDRESS_REGEX.test(mac))return!0}return!1}function isGoogleComputeEngine(){return isGoogleComputeEngineLinux()||isGoogleComputeEngineMACAddress()}function detectGCPResidency(){return isGoogleCloudServerless()||isGoogleComputeEngine()}}});var require_colours=__commonJS({"node_modules/google-logging-utils/build/src/colours.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.Colours=void 0;var Colours=class _Colours{static isEnabled(stream){return stream&&stream.isTTY&&(typeof stream.getColorDepth=="function"?stream.getColorDepth()>2:!0)}static refresh(){_Colours.enabled=_Colours.isEnabled(process==null?void 0:process.stderr),this.enabled?(_Colours.reset="\x1B[0m",_Colours.bright="\x1B[1m",_Colours.dim="\x1B[2m",_Colours.red="\x1B[31m",_Colours.green="\x1B[32m",_Colours.yellow="\x1B[33m",_Colours.blue="\x1B[34m",_Colours.magenta="\x1B[35m",_Colours.cyan="\x1B[36m",_Colours.white="\x1B[37m",_Colours.grey="\x1B[90m"):(_Colours.reset="",_Colours.bright="",_Colours.dim="",_Colours.red="",_Colours.green="",_Colours.yellow="",_Colours.blue="",_Colours.magenta="",_Colours.cyan="",_Colours.white="",_Colours.grey="")}};exports.Colours=Colours;Colours.enabled=!1;Colours.reset="";Colours.bright="";Colours.dim="";Colours.red="";Colours.green="";Colours.yellow="";Colours.blue="";Colours.magenta="";Colours.cyan="";Colours.white="";Colours.grey="";Colours.refresh()}});var require_logging_utils=__commonJS({"node_modules/google-logging-utils/build/src/logging-utils.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||(function(){var ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)Object.prototype.hasOwnProperty.call(o2,k)&&(ar[ar.length]=k);return ar},ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k=ownKeys(mod),i=0;i<k.length;i++)k[i]!=="default"&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.env=exports.DebugLogBackendBase=exports.placeholder=exports.AdhocDebugLogger=exports.LogSeverity=void 0;exports.getNodeBackend=getNodeBackend;exports.getDebugBackend=getDebugBackend;exports.getStructuredBackend=getStructuredBackend;exports.setBackend=setBackend;exports.log=log;var events_1=__require("events"),process2=__importStar(__require("process")),util=__importStar(__require("util")),colours_1=require_colours(),LogSeverity;(function(LogSeverity2){LogSeverity2.DEFAULT="DEFAULT",LogSeverity2.DEBUG="DEBUG",LogSeverity2.INFO="INFO",LogSeverity2.WARNING="WARNING",LogSeverity2.ERROR="ERROR"})(LogSeverity||(exports.LogSeverity=LogSeverity={}));var AdhocDebugLogger=class extends events_1.EventEmitter{constructor(namespace,upstream){super(),this.namespace=namespace,this.upstream=upstream,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(event,listener)=>this.on(event,listener)}),this.func.debug=(...args)=>this.invokeSeverity(LogSeverity.DEBUG,...args),this.func.info=(...args)=>this.invokeSeverity(LogSeverity.INFO,...args),this.func.warn=(...args)=>this.invokeSeverity(LogSeverity.WARNING,...args),this.func.error=(...args)=>this.invokeSeverity(LogSeverity.ERROR,...args),this.func.sublog=namespace2=>log(namespace2,this.func)}invoke(fields,...args){if(this.upstream)try{this.upstream(fields,...args)}catch{}try{this.emit("log",fields,args)}catch{}}invokeSeverity(severity,...args){this.invoke({severity},...args)}};exports.AdhocDebugLogger=AdhocDebugLogger;exports.placeholder=new AdhocDebugLogger("",()=>{}).func;var DebugLogBackendBase=class{constructor(){var _a2;this.cached=new Map,this.filters=[],this.filtersSet=!1;let nodeFlag=(_a2=process2.env[exports.env.nodeEnables])!==null&&_a2!==void 0?_a2:"*";nodeFlag==="all"&&(nodeFlag="*"),this.filters=nodeFlag.split(",")}log(namespace,fields,...args){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let logger=this.cached.get(namespace);logger||(logger=this.makeLogger(namespace),this.cached.set(namespace,logger)),logger(fields,...args)}catch(e){console.error(e)}}};exports.DebugLogBackendBase=DebugLogBackendBase;var NodeBackend=class extends DebugLogBackendBase{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(namespace){return this.enabledRegexp.test(namespace)}makeLogger(namespace){return this.enabledRegexp.test(namespace)?(fields,...args)=>{var _a2;let nscolour=`${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`,pid=`${colours_1.Colours.yellow}${process2.pid}${colours_1.Colours.reset}`,level;switch(fields.severity){case LogSeverity.ERROR:level=`${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;break;case LogSeverity.INFO:level=`${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;break;case LogSeverity.WARNING:level=`${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;break;default:level=(_a2=fields.severity)!==null&&_a2!==void 0?_a2:LogSeverity.DEFAULT;break}let msg=util.formatWithOptions({colors:colours_1.Colours.enabled},...args),filteredFields=Object.assign({},fields);delete filteredFields.severity;let fieldsJson=Object.getOwnPropertyNames(filteredFields).length?JSON.stringify(filteredFields):"",fieldsColour=fieldsJson?`${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",pid,nscolour,level,msg,fieldsJson?` ${fieldsColour}`:"")}:()=>{}}setFilters(){let regexp=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${regexp}$`,"i")}};function getNodeBackend(){return new NodeBackend}var DebugBackend=class extends DebugLogBackendBase{constructor(pkg){super(),this.debugPkg=pkg}makeLogger(namespace){let debugLogger=this.debugPkg(namespace);return(fields,...args)=>{debugLogger(args[0],...args.slice(1))}}setFilters(){var _a2;let existingFilters=(_a2=process2.env.NODE_DEBUG)!==null&&_a2!==void 0?_a2:"";process2.env.NODE_DEBUG=`${existingFilters}${existingFilters?",":""}${this.filters.join(",")}`}};function getDebugBackend(debugPkg){return new DebugBackend(debugPkg)}var StructuredBackend=class extends DebugLogBackendBase{constructor(upstream){var _a2;super(),this.upstream=(_a2=upstream)!==null&&_a2!==void 0?_a2:void 0}makeLogger(namespace){var _a2;let debugLogger=(_a2=this.upstream)===null||_a2===void 0?void 0:_a2.makeLogger(namespace);return(fields,...args)=>{var _a3;let severity=(_a3=fields.severity)!==null&&_a3!==void 0?_a3:LogSeverity.INFO,json2=Object.assign({severity,message:util.format(...args)},fields),jsonString=JSON.stringify(json2);debugLogger?debugLogger(fields,jsonString):console.log("%s",jsonString)}}setFilters(){var _a2;(_a2=this.upstream)===null||_a2===void 0||_a2.setFilters()}};function getStructuredBackend(upstream){return new StructuredBackend(upstream)}exports.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var loggerCache=new Map,cachedBackend;function setBackend(backend){cachedBackend=backend,loggerCache.clear()}function log(namespace,parent){if(!cachedBackend&&!process2.env[exports.env.nodeEnables]||!namespace)return exports.placeholder;parent&&(namespace=`${parent.instance.namespace}:${namespace}`);let existing=loggerCache.get(namespace);if(existing)return existing.func;if(cachedBackend===null)return exports.placeholder;cachedBackend===void 0&&(cachedBackend=getNodeBackend());let logger=(()=>{let previousBackend;return new AdhocDebugLogger(namespace,(fields,...args)=>{if(previousBackend!==cachedBackend){if(cachedBackend===null)return;cachedBackend===void 0&&(cachedBackend=getNodeBackend()),previousBackend=cachedBackend}cachedBackend?.log(namespace,fields,...args)})})();return loggerCache.set(namespace,logger),logger.func}}});var require_src2=__commonJS({"node_modules/google-logging-utils/build/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});__exportStar(require_logging_utils(),exports)}});var require_src3=__commonJS({"node_modules/gcp-metadata/build/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||(function(){var ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)Object.prototype.hasOwnProperty.call(o2,k)&&(ar[ar.length]=k);return ar},ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k=ownKeys(mod),i=0;i<k.length;i++)k[i]!=="default"&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result}})(),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.gcpResidencyCache=exports.METADATA_SERVER_DETECTION=exports.HEADERS=exports.HEADER_VALUE=exports.HEADER_NAME=exports.SECONDARY_HOST_ADDRESS=exports.HOST_ADDRESS=exports.BASE_PATH=void 0;exports.instance=instance;exports.project=project;exports.universe=universe;exports.bulk=bulk;exports.isAvailable=isAvailable;exports.resetIsAvailableCache=resetIsAvailableCache;exports.getGCPResidency=getGCPResidency;exports.setGCPResidency=setGCPResidency;exports.requestTimeout=requestTimeout;var gaxios_1=require_src(),jsonBigint=require_json_bigint(),gcp_residency_1=require_gcp_residency(),logger=__importStar(require_src2());exports.BASE_PATH="/computeMetadata/v1";exports.HOST_ADDRESS="http://169.254.169.254";exports.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";exports.HEADER_NAME="Metadata-Flavor";exports.HEADER_VALUE="Google";exports.HEADERS=Object.freeze({[exports.HEADER_NAME]:exports.HEADER_VALUE});var log=logger.log("gcp-metadata");exports.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function getBaseUrl2(baseUrl){return baseUrl||(baseUrl=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||exports.HOST_ADDRESS),/^https?:\/\//.test(baseUrl)||(baseUrl=`http://${baseUrl}`),new URL(exports.BASE_PATH,baseUrl).href}function validate(options){Object.keys(options).forEach(key=>{switch(key){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${key}' is not a valid configuration option.`)}})}async function metadataAccessor(type,options={},noResponseRetries=3,fastFail=!1){let headers=new Headers(exports.HEADERS),metadataKey="",params={};if(typeof type=="object"){let metadataAccessor2=type;new Headers(metadataAccessor2.headers).forEach((value,key)=>headers.set(key,value)),metadataKey=metadataAccessor2.metadataKey,params=metadataAccessor2.params||params,noResponseRetries=metadataAccessor2.noResponseRetries||noResponseRetries,fastFail=metadataAccessor2.fastFail||fastFail}else metadataKey=type;typeof options=="string"?metadataKey+=`/${options}`:(validate(options),options.property&&(metadataKey+=`/${options.property}`),new Headers(options.headers).forEach((value,key)=>headers.set(key,value)),params=options.params||params);let requestMethod=fastFail?fastFailMetadataRequest:gaxios_1.request,req={url:`${getBaseUrl2()}/${metadataKey}`,headers,retryConfig:{noResponseRetries},params,responseType:"text",timeout:requestTimeout()};log.info("instance request %j",req);let res=await requestMethod(req);log.info("instance metadata is %s",res.data);let metadataFlavor=res.headers.get(exports.HEADER_NAME);if(metadataFlavor!==exports.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor?`'${metadataFlavor}'`:"no header"}`);if(typeof res.data=="string")try{return jsonBigint.parse(res.data)}catch{}return res.data}async function fastFailMetadataRequest(options){let secondaryOptions={...options,url:options.url?.toString().replace(getBaseUrl2(),getBaseUrl2(exports.SECONDARY_HOST_ADDRESS))},r1=(0,gaxios_1.request)(options),r2=(0,gaxios_1.request)(secondaryOptions);return Promise.any([r1,r2])}function instance(options){return metadataAccessor("instance",options)}function project(options){return metadataAccessor("project",options)}function universe(options){return metadataAccessor("universe",options)}async function bulk(properties){let r={};return await Promise.all(properties.map(item=>(async()=>{let res=await metadataAccessor(item),key=item.metadataKey;r[key]=res})())),r}function detectGCPAvailableRetries(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var cachedIsAvailableResponse;async function isAvailable(){if(process.env.METADATA_SERVER_DETECTION){let value=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(value in exports.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(value){case"assume-present":return!0;case"none":return!1;case"bios-only":return getGCPResidency();case"ping-only":}}try{return cachedIsAvailableResponse===void 0&&(cachedIsAvailableResponse=metadataAccessor("instance",void 0,detectGCPAvailableRetries(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await cachedIsAvailableResponse,!0}catch(e){let err=e;if(process.env.DEBUG_AUTH&&console.info(err),err.type==="request-timeout"||err.response&&err.response.status===404)return!1;if(!(err.response&&err.response.status===404)&&(!err.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(err.code.toString()))){let code="UNKNOWN";err.code&&(code=err.code.toString()),process.emitWarning(`received unexpected error = ${err.message} code = ${code}`,"MetadataLookupWarning")}return!1}}function resetIsAvailableCache(){cachedIsAvailableResponse=void 0}exports.gcpResidencyCache=null;function getGCPResidency(){return exports.gcpResidencyCache===null&&setGCPResidency(),exports.gcpResidencyCache}function setGCPResidency(value=null){exports.gcpResidencyCache=value!==null?value:(0,gcp_residency_1.detectGCPResidency)()}function requestTimeout(){return getGCPResidency()?0:3e3}__exportStar(require_gcp_residency(),exports)}});var require_base64_js=__commonJS({"node_modules/base64-js/index.js"(exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;var i,len;revLookup[45]=62;revLookup[95]=63;function getLens(b64){var len2=b64.length;if(len2%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");validLen===-1&&(validLen=len2);var placeHoldersLen=validLen===len2?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len2=placeHoldersLen>0?validLen-4:validLen,i2;for(i2=0;i2<len2;i2+=4)tmp=revLookup[b64.charCodeAt(i2)]<<18|revLookup[b64.charCodeAt(i2+1)]<<12|revLookup[b64.charCodeAt(i2+2)]<<6|revLookup[b64.charCodeAt(i2+3)],arr[curByte++]=tmp>>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=tmp&255;return placeHoldersLen===2&&(tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4,arr[curByte++]=tmp&255),placeHoldersLen===1&&(tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=tmp&255),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i2=start;i2<end;i2+=3)tmp=(uint8[i2]<<16&16711680)+(uint8[i2+1]<<8&65280)+(uint8[i2+2]&255),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len2=uint8.length,extraBytes=len2%3,parts=[],maxChunkLength=16383,i2=0,len22=len2-extraBytes;i2<len22;i2+=maxChunkLength)parts.push(encodeChunk(uint8,i2,i2+maxChunkLength>len22?len22:i2+maxChunkLength));return extraBytes===1?(tmp=uint8[len2-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):extraBytes===2&&(tmp=(uint8[len2-2]<<8)+uint8[len2-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}}});var require_shared=__commonJS({"node_modules/google-auth-library/build/src/crypto/shared.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.fromArrayBufferToHex=fromArrayBufferToHex;function fromArrayBufferToHex(arrayBuffer){return Array.from(new Uint8Array(arrayBuffer)).map(byte=>byte.toString(16).padStart(2,"0")).join("")}}});var require_crypto=__commonJS({"node_modules/google-auth-library/build/src/crypto/browser/crypto.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.BrowserCrypto=void 0;var base64js=require_base64_js(),shared_1=require_shared(),BrowserCrypto=class _BrowserCrypto{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(str){let inputBuffer=new TextEncoder().encode(str),outputBuffer=await window.crypto.subtle.digest("SHA-256",inputBuffer);return base64js.fromByteArray(new Uint8Array(outputBuffer))}randomBytesBase64(count){let array=new Uint8Array(count);return window.crypto.getRandomValues(array),base64js.fromByteArray(array)}static padBase64(base64){for(;base64.length%4!==0;)base64+="=";return base64}async verify(pubkey,data,signature){let algo={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},dataArray=new TextEncoder().encode(data),signatureArray=base64js.toByteArray(_BrowserCrypto.padBase64(signature)),cryptoKey=await window.crypto.subtle.importKey("jwk",pubkey,algo,!0,["verify"]);return await window.crypto.subtle.verify(algo,cryptoKey,Buffer.from(signatureArray),dataArray)}async sign(privateKey,data){let algo={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},dataArray=new TextEncoder().encode(data),cryptoKey=await window.crypto.subtle.importKey("jwk",privateKey,algo,!0,["sign"]),result=await window.crypto.subtle.sign(algo,cryptoKey,dataArray);return base64js.fromByteArray(new Uint8Array(result))}decodeBase64StringUtf8(base64){let uint8array=base64js.toByteArray(_BrowserCrypto.padBase64(base64));return new TextDecoder().decode(uint8array)}encodeBase64StringUtf8(text){let uint8array=new TextEncoder().encode(text);return base64js.fromByteArray(uint8array)}async sha256DigestHex(str){let inputBuffer=new TextEncoder().encode(str),outputBuffer=await window.crypto.subtle.digest("SHA-256",inputBuffer);return(0,shared_1.fromArrayBufferToHex)(outputBuffer)}async signWithHmacSha256(key,msg){let rawKey=typeof key=="string"?key:String.fromCharCode(...new Uint16Array(key)),enc=new TextEncoder,cryptoKey=await window.crypto.subtle.importKey("raw",enc.encode(rawKey),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",cryptoKey,enc.encode(msg))}};exports.BrowserCrypto=BrowserCrypto}});var require_crypto2=__commonJS({"node_modules/google-auth-library/build/src/crypto/node/crypto.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.NodeCrypto=void 0;var crypto2=__require("crypto"),NodeCrypto=class{async sha256DigestBase64(str){return crypto2.createHash("sha256").update(str).digest("base64")}randomBytesBase64(count){return crypto2.randomBytes(count).toString("base64")}async verify(pubkey,data,signature){let verifier=crypto2.createVerify("RSA-SHA256");return verifier.update(data),verifier.end(),verifier.verify(pubkey,signature,"base64")}async sign(privateKey,data){let signer=crypto2.createSign("RSA-SHA256");return signer.update(data),signer.end(),signer.sign(privateKey,"base64")}decodeBase64StringUtf8(base64){return Buffer.from(base64,"base64").toString("utf-8")}encodeBase64StringUtf8(text){return Buffer.from(text,"utf-8").toString("base64")}async sha256DigestHex(str){return crypto2.createHash("sha256").update(str).digest("hex")}async signWithHmacSha256(key,msg){let cryptoKey=typeof key=="string"?key:toBuffer(key);return toArrayBuffer(crypto2.createHmac("sha256",cryptoKey).update(msg).digest())}};exports.NodeCrypto=NodeCrypto;function toArrayBuffer(buffer){let ab=new ArrayBuffer(buffer.length),view=new Uint8Array(ab);for(let i=0;i<buffer.length;++i)view[i]=buffer[i];return ab}function toBuffer(arrayBuffer){return Buffer.from(arrayBuffer)}}});var require_crypto3=__commonJS({"node_modules/google-auth-library/build/src/crypto/crypto.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createCrypto=createCrypto;exports.hasBrowserCrypto=hasBrowserCrypto;var crypto_1=require_crypto(),crypto_2=require_crypto2();__exportStar(require_shared(),exports);function createCrypto(){return hasBrowserCrypto()?new crypto_1.BrowserCrypto:new crypto_2.NodeCrypto}function hasBrowserCrypto(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}}});var require_safe_buffer=__commonJS({"node_modules/safe-buffer/index.js"(exports,module){var buffer=__require("buffer"),Buffer2=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}Buffer2.from&&Buffer2.alloc&&Buffer2.allocUnsafe&&Buffer2.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer);function SafeBuffer(arg,encodingOrOffset,length){return Buffer2(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer2.prototype);copyProps(Buffer2,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg=="number")throw new TypeError("Argument must not be a number");return Buffer2(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!="number")throw new TypeError("Argument must be a number");var buf=Buffer2(size);return fill!==void 0?typeof encoding=="string"?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!="number")throw new TypeError("Argument must be a number");return Buffer2(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!="number")throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}}});var require_param_bytes_for_alg=__commonJS({"node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(exports,module){"use strict";function getParamSize(keySize){var result=(keySize/8|0)+(keySize%8===0?0:1);return result}var paramBytesForAlg={ES256:getParamSize(256),ES384:getParamSize(384),ES512:getParamSize(521)};function getParamBytesForAlg(alg){var paramBytes=paramBytesForAlg[alg];if(paramBytes)return paramBytes;throw new Error('Unknown algorithm "'+alg+'"')}module.exports=getParamBytesForAlg}});var require_ecdsa_sig_formatter=__commonJS({"node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(exports,module){"use strict";var Buffer2=require_safe_buffer().Buffer,getParamBytesForAlg=require_param_bytes_for_alg(),MAX_OCTET=128,CLASS_UNIVERSAL=0,PRIMITIVE_BIT=32,TAG_SEQ=16,TAG_INT=2,ENCODED_TAG_SEQ=TAG_SEQ|PRIMITIVE_BIT|CLASS_UNIVERSAL<<6,ENCODED_TAG_INT=TAG_INT|CLASS_UNIVERSAL<<6;function base64Url(base64){return base64.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function signatureAsBuffer(signature){if(Buffer2.isBuffer(signature))return signature;if(typeof signature=="string")return Buffer2.from(signature,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function derToJose(signature,alg){signature=signatureAsBuffer(signature);var paramBytes=getParamBytesForAlg(alg),maxEncodedParamLength=paramBytes+1,inputLength=signature.length,offset=0;if(signature[offset++]!==ENCODED_TAG_SEQ)throw new Error('Could not find expected "seq"');var seqLength=signature[offset++];if(seqLength===(MAX_OCTET|1)&&(seqLength=signature[offset++]),inputLength-offset<seqLength)throw new Error('"seq" specified length of "'+seqLength+'", only "'+(inputLength-offset)+'" remaining');if(signature[offset++]!==ENCODED_TAG_INT)throw new Error('Could not find expected "int" for "r"');var rLength=signature[offset++];if(inputLength-offset-2<rLength)throw new Error('"r" specified length of "'+rLength+'", only "'+(inputLength-offset-2)+'" available');if(maxEncodedParamLength<rLength)throw new Error('"r" specified length of "'+rLength+'", max of "'+maxEncodedParamLength+'" is acceptable');var rOffset=offset;if(offset+=rLength,signature[offset++]!==ENCODED_TAG_INT)throw new Error('Could not find expected "int" for "s"');var sLength=signature[offset++];if(inputLength-offset!==sLength)throw new Error('"s" specified length of "'+sLength+'", expected "'+(inputLength-offset)+'"');if(maxEncodedParamLength<sLength)throw new Error('"s" specified length of "'+sLength+'", max of "'+maxEncodedParamLength+'" is acceptable');var sOffset=offset;if(offset+=sLength,offset!==inputLength)throw new Error('Expected to consume entire buffer, but "'+(inputLength-offset)+'" bytes remain');var rPadding=paramBytes-rLength,sPadding=paramBytes-sLength,dst=Buffer2.allocUnsafe(rPadding+rLength+sPadding+sLength);for(offset=0;offset<rPadding;++offset)dst[offset]=0;signature.copy(dst,offset,rOffset+Math.max(-rPadding,0),rOffset+rLength),offset=paramBytes;for(var o=offset;offset<o+sPadding;++offset)dst[offset]=0;return signature.copy(dst,offset,sOffset+Math.max(-sPadding,0),sOffset+sLength),dst=dst.toString("base64"),dst=base64Url(dst),dst}function countPadding(buf,start,stop){for(var padding=0;start+padding<stop&&buf[start+padding]===0;)++padding;var needsSign=buf[start+padding]>=MAX_OCTET;return needsSign&&--padding,padding}function joseToDer(signature,alg){signature=signatureAsBuffer(signature);var paramBytes=getParamBytesForAlg(alg),signatureBytes=signature.length;if(signatureBytes!==paramBytes*2)throw new TypeError('"'+alg+'" signatures must be "'+paramBytes*2+'" bytes, saw "'+signatureBytes+'"');var rPadding=countPadding(signature,0,paramBytes),sPadding=countPadding(signature,paramBytes,signature.length),rLength=paramBytes-rPadding,sLength=paramBytes-sPadding,rsBytes=2+rLength+1+1+sLength,shortLength=rsBytes<MAX_OCTET,dst=Buffer2.allocUnsafe((shortLength?2:3)+rsBytes),offset=0;return dst[offset++]=ENCODED_TAG_SEQ,shortLength?dst[offset++]=rsBytes:(dst[offset++]=MAX_OCTET|1,dst[offset++]=rsBytes&255),dst[offset++]=ENCODED_TAG_INT,dst[offset++]=rLength,rPadding<0?(dst[offset++]=0,offset+=signature.copy(dst,offset,0,paramBytes)):offset+=signature.copy(dst,offset,rPadding,paramBytes),dst[offset++]=ENCODED_TAG_INT,dst[offset++]=sLength,sPadding<0?(dst[offset++]=0,signature.copy(dst,offset,paramBytes)):signature.copy(dst,offset,paramBytes+sPadding),dst}module.exports={derToJose,joseToDer}}});var require_util2=__commonJS({"node_modules/google-auth-library/build/src/util.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;exports.snakeToCamel=snakeToCamel;exports.originalOrCamelOptions=originalOrCamelOptions;exports.removeUndefinedValuesInObject=removeUndefinedValuesInObject;exports.isValidFile=isValidFile;exports.getWellKnownCertificateConfigFileLocation=getWellKnownCertificateConfigFileLocation;var fs2=__require("fs"),os=__require("os"),path2=__require("path"),WELL_KNOWN_CERTIFICATE_CONFIG_FILE="certificate_config.json",CLOUDSDK_CONFIG_DIRECTORY="gcloud";function snakeToCamel(str){return str.replace(/([_][^_])/g,match2=>match2.slice(1).toUpperCase())}function originalOrCamelOptions(obj){function get(key){let o=obj||{};return o[key]??o[snakeToCamel(key)]}return{get}}var LRUCache=class{capacity;#cache=new Map;maxAge;constructor(options){this.capacity=options.capacity,this.maxAge=options.maxAge}#moveToEnd(key,value){this.#cache.delete(key),this.#cache.set(key,{value,lastAccessed:Date.now()})}set(key,value){this.#moveToEnd(key,value),this.#evict()}get(key){let item=this.#cache.get(key);if(item)return this.#moveToEnd(key,item.value),this.#evict(),item.value}#evict(){let cutoffDate=this.maxAge?Date.now()-this.maxAge:0,oldestItem=this.#cache.entries().next();for(;!oldestItem.done&&(this.#cache.size>this.capacity||oldestItem.value[1].lastAccessed<cutoffDate);)this.#cache.delete(oldestItem.value[0]),oldestItem=this.#cache.entries().next()}};exports.LRUCache=LRUCache;function removeUndefinedValuesInObject(object){return Object.entries(object).forEach(([key,value])=>{(value===void 0||value==="undefined")&&delete object[key]}),object}async function isValidFile(filePath){try{return(await fs2.promises.lstat(filePath)).isFile()}catch{return!1}}function getWellKnownCertificateConfigFileLocation(){let configDir=process.env.CLOUDSDK_CONFIG||(_isWindows()?path2.join(process.env.APPDATA||"",CLOUDSDK_CONFIG_DIRECTORY):path2.join(process.env.HOME||"",".config",CLOUDSDK_CONFIG_DIRECTORY));return path2.join(configDir,WELL_KNOWN_CERTIFICATE_CONFIG_FILE)}function _isWindows(){return os.platform().startsWith("win")}}});var require_package2=__commonJS({"node_modules/google-auth-library/package.json"(exports,module){module.exports={name:"google-auth-library",version:"10.6.2",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.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"^21.0.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"}}});var require_shared2=__commonJS({"node_modules/google-auth-library/build/src/shared.cjs"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.USER_AGENT=exports.PRODUCT_NAME=exports.pkg=void 0;var pkg=require_package2();exports.pkg=pkg;var PRODUCT_NAME="google-api-nodejs-client";exports.PRODUCT_NAME=PRODUCT_NAME;var USER_AGENT=`${PRODUCT_NAME}/${pkg.version}`;exports.USER_AGENT=USER_AGENT}});var require_authclient=__commonJS({"node_modules/google-auth-library/build/src/auth/authclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.AuthClient=exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=exports.DEFAULT_UNIVERSE=void 0;var events_1=__require("events"),gaxios_1=require_src(),util_1=require_util2(),google_logging_utils_1=require_src2(),shared_cjs_1=require_shared2();exports.DEFAULT_UNIVERSE="googleapis.com";exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var AuthClient=class _AuthClient extends events_1.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=exports.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(opts={}){super();let options=(0,util_1.originalOrCamelOptions)(opts);this.apiKey=opts.apiKey,this.projectId=options.get("project_id")??null,this.quotaProjectId=options.get("quota_project_id"),this.credentials=options.get("credentials")??{},this.universeDomain=options.get("universe_domain")??exports.DEFAULT_UNIVERSE,this.transporter=opts.transporter??new gaxios_1.Gaxios(opts.transporterOptions),options.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(_AuthClient.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(_AuthClient.DEFAULT_RESPONSE_INTERCEPTOR)),opts.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=opts.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=opts.forceRefreshOnFailure??!1}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&gaxios_1.Gaxios.mergeHeaders(headers,input.headers),init&&gaxios_1.Gaxios.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}setCredentials(credentials){this.credentials=credentials}addSharedMetadataHeaders(headers){return!headers.has("x-goog-user-project")&&this.quotaProjectId&&headers.set("x-goog-user-project",this.quotaProjectId),headers}addUserProjectAndAuthHeaders(target,source){let xGoogUserProject=source.get("x-goog-user-project"),authorizationHeader=source.get("authorization");return xGoogUserProject&&target.set("x-goog-user-project",xGoogUserProject),authorizationHeader&&target.set("authorization",authorizationHeader),target}static log=(0,google_logging_utils_1.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async config=>{if(!config.headers.has("x-goog-api-client")){let nodeVersion=process.version.replace(/^v/,"");config.headers.set("x-goog-api-client",`gl-node/${nodeVersion}`)}let userAgent=config.headers.get("User-Agent");userAgent?userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)||config.headers.set("User-Agent",`${userAgent} ${shared_cjs_1.USER_AGENT}`):config.headers.set("User-Agent",shared_cjs_1.USER_AGENT);try{let symbols=config,methodName=symbols[_AuthClient.RequestMethodNameSymbol],logId=`${Math.floor(Math.random()*1e3)}`;symbols[_AuthClient.RequestLogIdSymbol]=logId;let logObject={url:config.url,headers:config.headers};methodName?_AuthClient.log.info("%s [%s] request %j",methodName,logId,logObject):_AuthClient.log.info("[%s] request %j",logId,logObject)}catch{}return config}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async response=>{try{let symbols=response.config,methodName=symbols[_AuthClient.RequestMethodNameSymbol],logId=symbols[_AuthClient.RequestLogIdSymbol];methodName?_AuthClient.log.info("%s [%s] response %j",methodName,logId,response.data):_AuthClient.log.info("[%s] response %j",logId,response.data)}catch{}return response},rejected:async error=>{try{let symbols=error.config,methodName=symbols[_AuthClient.RequestMethodNameSymbol],logId=symbols[_AuthClient.RequestLogIdSymbol];methodName?_AuthClient.log.info("%s [%s] error %j",methodName,logId,error.response?.data):_AuthClient.log.error("[%s] error %j",logId,error.response?.data)}catch{}throw error}};static setMethodName(config,methodName){try{let symbols=config;symbols[_AuthClient.RequestMethodNameSymbol]=methodName}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};exports.AuthClient=AuthClient}});var require_loginticket=__commonJS({"node_modules/google-auth-library/build/src/auth/loginticket.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.LoginTicket=void 0;var LoginTicket=class{envelope;payload;constructor(env2,pay){this.envelope=env2,this.payload=pay}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let payload=this.getPayload();return payload&&payload.sub?payload.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};exports.LoginTicket=LoginTicket}});var require_oauth2client=__commonJS({"node_modules/google-auth-library/build/src/auth/oauth2client.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.OAuth2Client=exports.ClientAuthentication=exports.CertificateFormat=exports.CodeChallengeMethod=void 0;var gaxios_1=require_src(),querystring=__require("querystring"),stream=__require("stream"),formatEcdsa=require_ecdsa_sig_formatter(),util_1=require_util2(),crypto_1=require_crypto3(),authclient_1=require_authclient(),loginticket_1=require_loginticket(),CodeChallengeMethod;(function(CodeChallengeMethod2){CodeChallengeMethod2.Plain="plain",CodeChallengeMethod2.S256="S256"})(CodeChallengeMethod||(exports.CodeChallengeMethod=CodeChallengeMethod={}));var CertificateFormat;(function(CertificateFormat2){CertificateFormat2.PEM="PEM",CertificateFormat2.JWK="JWK"})(CertificateFormat||(exports.CertificateFormat=CertificateFormat={}));var ClientAuthentication;(function(ClientAuthentication2){ClientAuthentication2.ClientSecretPost="ClientSecretPost",ClientAuthentication2.ClientSecretBasic="ClientSecretBasic",ClientAuthentication2.None="None"})(ClientAuthentication||(exports.ClientAuthentication=ClientAuthentication={}));var OAuth2Client=class _OAuth2Client extends authclient_1.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=CertificateFormat.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(options={},clientSecret,redirectUri){super(typeof options=="object"?options:{}),typeof options!="object"&&(options={clientId:options,clientSecret,redirectUri}),this._clientId=options.clientId||options.client_id,this._clientSecret=options.clientSecret||options.client_secret,this.redirectUri=options.redirectUri||options.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",...options.endpoints},this.clientAuthentication=options.clientAuthentication||ClientAuthentication.ClientSecretPost,this.issuers=options.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(opts={}){if(opts.code_challenge_method&&!opts.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return opts.response_type=opts.response_type||"code",opts.client_id=opts.client_id||this._clientId,opts.redirect_uri=opts.redirect_uri||this.redirectUri,Array.isArray(opts.scope)&&(opts.scope=opts.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+querystring.stringify(opts)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let crypto2=(0,crypto_1.createCrypto)(),codeVerifier=crypto2.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),codeChallenge=(await crypto2.sha256DigestBase64(codeVerifier)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier,codeChallenge}}getToken(codeOrOptions,callback){let options=typeof codeOrOptions=="string"?{code:codeOrOptions}:codeOrOptions;if(callback)this.getTokenAsync(options).then(r=>callback(null,r.tokens,r.res),e=>callback(e,null,e.response));else return this.getTokenAsync(options)}async getTokenAsync(options){let url=this.endpoints.oauth2TokenUrl.toString(),headers=new Headers,values={client_id:options.client_id||this._clientId,code_verifier:options.codeVerifier,code:options.code,grant_type:"authorization_code",redirect_uri:options.redirect_uri||this.redirectUri};if(this.clientAuthentication===ClientAuthentication.ClientSecretBasic){let basic=Buffer.from(`${this._clientId}:${this._clientSecret}`);headers.set("authorization",`Basic ${basic.toString("base64")}`)}this.clientAuthentication===ClientAuthentication.ClientSecretPost&&(values.client_secret=this._clientSecret);let opts={..._OAuth2Client.RETRY_CONFIG,method:"POST",url,data:new URLSearchParams((0,util_1.removeUndefinedValuesInObject)(values)),headers};authclient_1.AuthClient.setMethodName(opts,"getTokenAsync");let res=await this.transporter.request(opts),tokens=res.data;return res.data&&res.data.expires_in&&(tokens.expiry_date=new Date().getTime()+res.data.expires_in*1e3,delete tokens.expires_in),this.emit("tokens",tokens),{tokens,res}}async refreshToken(refreshToken){if(!refreshToken)return this.refreshTokenNoCache(refreshToken);if(this.refreshTokenPromises.has(refreshToken))return this.refreshTokenPromises.get(refreshToken);let p=this.refreshTokenNoCache(refreshToken).then(r=>(this.refreshTokenPromises.delete(refreshToken),r),e=>{throw this.refreshTokenPromises.delete(refreshToken),e});return this.refreshTokenPromises.set(refreshToken,p),p}async refreshTokenNoCache(refreshToken){if(!refreshToken)throw new Error("No refresh token is set.");let url=this.endpoints.oauth2TokenUrl.toString(),data={refresh_token:refreshToken,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},res;try{let opts={..._OAuth2Client.RETRY_CONFIG,method:"POST",url,data:new URLSearchParams((0,util_1.removeUndefinedValuesInObject)(data))};authclient_1.AuthClient.setMethodName(opts,"refreshTokenNoCache"),res=await this.transporter.request(opts)}catch(e){throw e instanceof gaxios_1.GaxiosError&&e.message==="invalid_grant"&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}let tokens=res.data;return res.data&&res.data.expires_in&&(tokens.expiry_date=new Date().getTime()+res.data.expires_in*1e3,delete tokens.expires_in),this.emit("tokens",tokens),{tokens,res}}refreshAccessToken(callback){if(callback)this.refreshAccessTokenAsync().then(r=>callback(null,r.credentials,r.res),callback);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let r=await this.refreshToken(this.credentials.refresh_token),tokens=r.tokens;return tokens.refresh_token=this.credentials.refresh_token,this.credentials=tokens,{credentials:this.credentials,res:r.res}}getAccessToken(callback){if(callback)this.getAccessTokenAsync().then(r=>callback(null,r.token,r.res),callback);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let refreshedAccessToken=await this.processAndValidateRefreshHandler();if(refreshedAccessToken?.access_token)return this.setCredentials(refreshedAccessToken),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(url){return(await this.getRequestMetadataAsync(url)).headers}async getRequestMetadataAsync(url){let thisCreds=this.credentials;if(!thisCreds.access_token&&!thisCreds.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(thisCreds.access_token&&!this.isTokenExpiring()){thisCreds.token_type=thisCreds.token_type||"Bearer";let headers2=new Headers({authorization:thisCreds.token_type+" "+thisCreds.access_token});return{headers:this.addSharedMetadataHeaders(headers2)}}if(this.refreshHandler){let refreshedAccessToken=await this.processAndValidateRefreshHandler();if(refreshedAccessToken?.access_token){this.setCredentials(refreshedAccessToken);let headers2=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(headers2)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,tokens=null;try{r=await this.refreshToken(thisCreds.refresh_token),tokens=r.tokens}catch(err){let e=err;throw e.response&&(e.response.status===403||e.response.status===404)&&(e.message=`Could not refresh access token: ${e.message}`),e}let credentials=this.credentials;credentials.token_type=credentials.token_type||"Bearer",tokens.refresh_token=credentials.refresh_token,this.credentials=tokens;let headers=new Headers({authorization:credentials.token_type+" "+tokens.access_token});return{headers:this.addSharedMetadataHeaders(headers),res:r.res}}static getRevokeTokenUrl(token){return new _OAuth2Client().getRevokeTokenURL(token).toString()}getRevokeTokenURL(token){let url=new URL(this.endpoints.oauth2RevokeUrl);return url.searchParams.append("token",token),url}revokeToken(token,callback){let opts={..._OAuth2Client.RETRY_CONFIG,url:this.getRevokeTokenURL(token).toString(),method:"POST"};if(authclient_1.AuthClient.setMethodName(opts,"revokeToken"),callback)this.transporter.request(opts).then(r=>callback(null,r),callback);else return this.transporter.request(opts)}revokeCredentials(callback){if(callback)this.revokeCredentialsAsync().then(res=>callback(null,res),callback);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let token=this.credentials.access_token;if(this.credentials={},token)return this.revokeToken(token);throw new Error("No access token to revoke.")}request(opts,callback){if(callback)this.requestAsync(opts).then(r=>callback(null,r),e=>callback(e,e.response));else return this.requestAsync(opts)}async requestAsync(opts,reAuthRetried=!1){try{let r=await this.getRequestMetadataAsync();return opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,r.headers),this.apiKey&&opts.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(opts)}catch(e){let res=e.response;if(res){let statusCode=res.status,mayRequireRefresh=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),mayRequireRefreshWithNoRefreshToken=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,isReadableStream=res.config.data instanceof stream.Readable,isAuthErr=statusCode===401||statusCode===403;if(!reAuthRetried&&isAuthErr&&!isReadableStream&&mayRequireRefresh)return await this.refreshAccessTokenAsync(),this.requestAsync(opts,!0);if(!reAuthRetried&&isAuthErr&&!isReadableStream&&mayRequireRefreshWithNoRefreshToken){let refreshedAccessToken=await this.processAndValidateRefreshHandler();return refreshedAccessToken?.access_token&&this.setCredentials(refreshedAccessToken),this.requestAsync(opts,!0)}}throw e}}verifyIdToken(options,callback){if(callback&&typeof callback!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(callback)this.verifyIdTokenAsync(options).then(r=>callback(null,r),callback);else return this.verifyIdTokenAsync(options)}async verifyIdTokenAsync(options){if(!options.idToken)throw new Error("The verifyIdToken method requires an ID Token");let response=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(options.idToken,response.certs,options.audience,this.issuers,options.maxExpiry)}async getTokenInfo(accessToken){let{data}=await this.transporter.request({..._OAuth2Client.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${accessToken}`},url:this.endpoints.tokenInfoUrl.toString()}),info=Object.assign({expiry_date:new Date().getTime()+data.expires_in*1e3,scopes:data.scope.split(" ")},data);return delete info.expires_in,delete info.scope,info}getFederatedSignonCerts(callback){if(callback)this.getFederatedSignonCertsAsync().then(r=>callback(null,r.certs,r.res),callback);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let nowTime=new Date().getTime(),format=(0,crypto_1.hasBrowserCrypto)()?CertificateFormat.JWK:CertificateFormat.PEM;if(this.certificateExpiry&&nowTime<this.certificateExpiry.getTime()&&this.certificateCacheFormat===format)return{certs:this.certificateCache,format};let res,url;switch(format){case CertificateFormat.PEM:url=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case CertificateFormat.JWK:url=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${format}`)}try{let opts={..._OAuth2Client.RETRY_CONFIG,url};authclient_1.AuthClient.setMethodName(opts,"getFederatedSignonCertsAsync"),res=await this.transporter.request(opts)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}let cacheControl=res?.headers.get("cache-control"),cacheAge=-1;if(cacheControl){let maxAge=/max-age=(?<maxAge>[0-9]+)/.exec(cacheControl)?.groups?.maxAge;maxAge&&(cacheAge=Number(maxAge)*1e3)}let certificates={};switch(format){case CertificateFormat.PEM:certificates=res.data;break;case CertificateFormat.JWK:for(let key of res.data.keys)certificates[key.kid]=key;break;default:throw new Error(`Unsupported certificate format ${format}`)}let now=new Date;return this.certificateExpiry=cacheAge===-1?null:new Date(now.getTime()+cacheAge),this.certificateCache=certificates,this.certificateCacheFormat=format,{certs:certificates,format,res}}getIapPublicKeys(callback){if(callback)this.getIapPublicKeysAsync().then(r=>callback(null,r.pubkeys,r.res),callback);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let res,url=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let opts={..._OAuth2Client.RETRY_CONFIG,url};authclient_1.AuthClient.setMethodName(opts,"getIapPublicKeysAsync"),res=await this.transporter.request(opts)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:res.data,res}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(jwt,certs,requiredAudience,issuers,maxExpiry){let crypto2=(0,crypto_1.createCrypto)();maxExpiry||(maxExpiry=_OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let segments=jwt.split(".");if(segments.length!==3)throw new Error("Wrong number of segments in token: "+jwt);let signed=segments[0]+"."+segments[1],signature=segments[2],envelope,payload;try{envelope=JSON.parse(crypto2.decodeBase64StringUtf8(segments[0]))}catch(err){throw err instanceof Error&&(err.message=`Can't parse token envelope: ${segments[0]}': ${err.message}`),err}if(!envelope)throw new Error("Can't parse token envelope: "+segments[0]);try{payload=JSON.parse(crypto2.decodeBase64StringUtf8(segments[1]))}catch(err){throw err instanceof Error&&(err.message=`Can't parse token payload '${segments[0]}`),err}if(!payload)throw new Error("Can't parse token payload: "+segments[1]);if(!Object.prototype.hasOwnProperty.call(certs,envelope.kid))throw new Error("No pem found for envelope: "+JSON.stringify(envelope));let cert=certs[envelope.kid];if(envelope.alg==="ES256"&&(signature=formatEcdsa.joseToDer(signature,"ES256").toString("base64")),!await crypto2.verify(cert,signed,signature))throw new Error("Invalid token signature: "+jwt);if(!payload.iat)throw new Error("No issue time in token: "+JSON.stringify(payload));if(!payload.exp)throw new Error("No expiration time in token: "+JSON.stringify(payload));let iat=Number(payload.iat);if(isNaN(iat))throw new Error("iat field using invalid format");let exp=Number(payload.exp);if(isNaN(exp))throw new Error("exp field using invalid format");let now=new Date().getTime()/1e3;if(exp>=now+maxExpiry)throw new Error("Expiration time too far in future: "+JSON.stringify(payload));let earliest=iat-_OAuth2Client.CLOCK_SKEW_SECS_,latest=exp+_OAuth2Client.CLOCK_SKEW_SECS_;if(now<earliest)throw new Error("Token used too early, "+now+" < "+earliest+": "+JSON.stringify(payload));if(now>latest)throw new Error("Token used too late, "+now+" > "+latest+": "+JSON.stringify(payload));if(issuers&&issuers.indexOf(payload.iss)<0)throw new Error("Invalid issuer, expected one of ["+issuers+"], but got "+payload.iss);if(typeof requiredAudience<"u"&&requiredAudience!==null){let aud=payload.aud,audVerified=!1;if(requiredAudience.constructor===Array?audVerified=requiredAudience.indexOf(aud)>-1:audVerified=aud===requiredAudience,!audVerified)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new loginticket_1.LoginTicket(envelope,payload)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let accessTokenResponse=await this.refreshHandler();if(!accessTokenResponse.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return accessTokenResponse}}isTokenExpiring(){let expiryDate=this.credentials.expiry_date;return expiryDate?expiryDate<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};exports.OAuth2Client=OAuth2Client}});var require_computeclient=__commonJS({"node_modules/google-auth-library/build/src/auth/computeclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.Compute=void 0;var gaxios_1=require_src(),gcpMetadata=require_src3(),oauth2client_1=require_oauth2client(),Compute=class extends oauth2client_1.OAuth2Client{serviceAccountEmail;scopes;constructor(options={}){super(options),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=options.serviceAccountEmail||"default",this.scopes=Array.isArray(options.scopes)?options.scopes:options.scopes?[options.scopes]:[]}async refreshTokenNoCache(){let tokenPath=`service-accounts/${this.serviceAccountEmail}/token`,data;try{let instanceOptions={property:tokenPath};this.scopes.length>0&&(instanceOptions.params={scopes:this.scopes.join(",")}),data=await gcpMetadata.instance(instanceOptions)}catch(e){throw e instanceof gaxios_1.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}let tokens=data;return data&&data.expires_in&&(tokens.expiry_date=new Date().getTime()+data.expires_in*1e3,delete tokens.expires_in),this.emit("tokens",tokens),{tokens,res:null}}async fetchIdToken(targetAudience){let idTokenPath=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${targetAudience}`,idToken;try{let instanceOptions={property:idTokenPath};idToken=await gcpMetadata.instance(instanceOptions)}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return idToken}wrapError(e){let res=e.response;res&&res.status&&(e.status=res.status,res.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:res.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};exports.Compute=Compute}});var require_idtokenclient=__commonJS({"node_modules/google-auth-library/build/src/auth/idtokenclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.IdTokenClient=void 0;var oauth2client_1=require_oauth2client(),IdTokenClient=class extends oauth2client_1.OAuth2Client{targetAudience;idTokenProvider;constructor(options){super(options),this.targetAudience=options.targetAudience,this.idTokenProvider=options.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let idToken=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:idToken,expiry_date:this.getIdTokenExpiryDate(idToken)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(idToken){let payloadB64=idToken.split(".")[1];if(payloadB64)return JSON.parse(Buffer.from(payloadB64,"base64").toString("ascii")).exp*1e3}};exports.IdTokenClient=IdTokenClient}});var require_envDetect=__commonJS({"node_modules/google-auth-library/build/src/auth/envDetect.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GCPEnv=void 0;exports.clear=clear;exports.getEnv=getEnv2;var gcpMetadata=require_src3(),GCPEnv;(function(GCPEnv2){GCPEnv2.APP_ENGINE="APP_ENGINE",GCPEnv2.KUBERNETES_ENGINE="KUBERNETES_ENGINE",GCPEnv2.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",GCPEnv2.COMPUTE_ENGINE="COMPUTE_ENGINE",GCPEnv2.CLOUD_RUN="CLOUD_RUN",GCPEnv2.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",GCPEnv2.NONE="NONE"})(GCPEnv||(exports.GCPEnv=GCPEnv={}));var envPromise;function clear(){envPromise=void 0}async function getEnv2(){return envPromise||(envPromise=getEnvMemoized(),envPromise)}async function getEnvMemoized(){let env2=GCPEnv.NONE;return isAppEngine()?env2=GCPEnv.APP_ENGINE:isCloudFunction()?env2=GCPEnv.CLOUD_FUNCTIONS:await isComputeEngine()?await isKubernetesEngine()?env2=GCPEnv.KUBERNETES_ENGINE:isCloudRun()?env2=GCPEnv.CLOUD_RUN:isCloudRunJob()?env2=GCPEnv.CLOUD_RUN_JOBS:env2=GCPEnv.COMPUTE_ENGINE:env2=GCPEnv.NONE,env2}function isAppEngine(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function isCloudFunction(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function isCloudRun(){return!!process.env.K_CONFIGURATION}function isCloudRunJob(){return!!process.env.CLOUD_RUN_JOB}async function isKubernetesEngine(){try{return await gcpMetadata.instance("attributes/cluster-name"),!0}catch{return!1}}async function isComputeEngine(){return gcpMetadata.isAvailable()}}});var require_data_stream=__commonJS({"node_modules/jws/lib/data-stream.js"(exports,module){var Buffer2=require_safe_buffer().Buffer,Stream2=__require("stream"),util=__require("util");function DataStream(data){if(this.buffer=null,this.writable=!0,this.readable=!0,!data)return this.buffer=Buffer2.alloc(0),this;if(typeof data.pipe=="function")return this.buffer=Buffer2.alloc(0),data.pipe(this),this;if(data.length||typeof data=="object")return this.buffer=data,this.writable=!1,process.nextTick(function(){this.emit("end",data),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof data+")")}util.inherits(DataStream,Stream2);DataStream.prototype.write=function(data){this.buffer=Buffer2.concat([this.buffer,Buffer2.from(data)]),this.emit("data",data)};DataStream.prototype.end=function(data){data&&this.write(data),this.emit("end",data),this.emit("close"),this.writable=!1,this.readable=!1};module.exports=DataStream}});var require_buffer_equal_constant_time=__commonJS({"node_modules/buffer-equal-constant-time/index.js"(exports,module){"use strict";var Buffer2=__require("buffer").Buffer,SlowBuffer=__require("buffer").SlowBuffer;module.exports=bufferEq;function bufferEq(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)||a.length!==b.length)return!1;for(var c=0,i=0;i<a.length;i++)c|=a[i]^b[i];return c===0}bufferEq.install=function(){Buffer2.prototype.equal=SlowBuffer.prototype.equal=function(that){return bufferEq(this,that)}};var origBufEqual=Buffer2.prototype.equal,origSlowBufEqual=SlowBuffer.prototype.equal;bufferEq.restore=function(){Buffer2.prototype.equal=origBufEqual,SlowBuffer.prototype.equal=origSlowBufEqual}}});var require_jwa=__commonJS({"node_modules/jwa/index.js"(exports,module){var Buffer2=require_safe_buffer().Buffer,crypto2=__require("crypto"),formatEcdsa=require_ecdsa_sig_formatter(),util=__require("util"),MSG_INVALID_ALGORITHM=`"%s" is not a valid algorithm.
Supported algorithms are:
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,MSG_INVALID_SECRET="secret must be a string or buffer",MSG_INVALID_VERIFIER_KEY="key must be a string or a buffer",MSG_INVALID_SIGNER_KEY="key must be a string, a buffer or an object",supportsKeyObjects=typeof crypto2.createPublicKey=="function";supportsKeyObjects&&(MSG_INVALID_VERIFIER_KEY+=" or a KeyObject",MSG_INVALID_SECRET+="or a KeyObject");function checkIsPublicKey(key){if(!Buffer2.isBuffer(key)&&typeof key!="string"&&(!supportsKeyObjects||typeof key!="object"||typeof key.type!="string"||typeof key.asymmetricKeyType!="string"||typeof key.export!="function"))throw typeError(MSG_INVALID_VERIFIER_KEY)}function checkIsPrivateKey(key){if(!Buffer2.isBuffer(key)&&typeof key!="string"&&typeof key!="object")throw typeError(MSG_INVALID_SIGNER_KEY)}function checkIsSecretKey(key){if(!Buffer2.isBuffer(key)){if(typeof key=="string")return key;if(!supportsKeyObjects||typeof key!="object"||key.type!=="secret"||typeof key.export!="function")throw typeError(MSG_INVALID_SECRET)}}function fromBase64(base64){return base64.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function toBase64(base64url){base64url=base64url.toString();var padding=4-base64url.length%4;if(padding!==4)for(var i=0;i<padding;++i)base64url+="=";return base64url.replace(/\-/g,"+").replace(/_/g,"/")}function typeError(template){var args=[].slice.call(arguments,1),errMsg=util.format.bind(util,template).apply(null,args);return new TypeError(errMsg)}function bufferOrString(obj){return Buffer2.isBuffer(obj)||typeof obj=="string"}function normalizeInput(thing){return bufferOrString(thing)||(thing=JSON.stringify(thing)),thing}function createHmacSigner(bits){return function(thing,secret){checkIsSecretKey(secret),thing=normalizeInput(thing);var hmac=crypto2.createHmac("sha"+bits,secret),sig=(hmac.update(thing),hmac.digest("base64"));return fromBase64(sig)}}var bufferEqual,timingSafeEqual="timingSafeEqual"in crypto2?function(a,b){return a.byteLength!==b.byteLength?!1:crypto2.timingSafeEqual(a,b)}:function(a,b){return bufferEqual||(bufferEqual=require_buffer_equal_constant_time()),bufferEqual(a,b)};function createHmacVerifier(bits){return function(thing,signature,secret){var computedSig=createHmacSigner(bits)(thing,secret);return timingSafeEqual(Buffer2.from(signature),Buffer2.from(computedSig))}}function createKeySigner(bits){return function(thing,privateKey){checkIsPrivateKey(privateKey),thing=normalizeInput(thing);var signer=crypto2.createSign("RSA-SHA"+bits),sig=(signer.update(thing),signer.sign(privateKey,"base64"));return fromBase64(sig)}}function createKeyVerifier(bits){return function(thing,signature,publicKey){checkIsPublicKey(publicKey),thing=normalizeInput(thing),signature=toBase64(signature);var verifier=crypto2.createVerify("RSA-SHA"+bits);return verifier.update(thing),verifier.verify(publicKey,signature,"base64")}}function createPSSKeySigner(bits){return function(thing,privateKey){checkIsPrivateKey(privateKey),thing=normalizeInput(thing);var signer=crypto2.createSign("RSA-SHA"+bits),sig=(signer.update(thing),signer.sign({key:privateKey,padding:crypto2.constants.RSA_PKCS1_PSS_PADDING,saltLength:crypto2.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return fromBase64(sig)}}function createPSSKeyVerifier(bits){return function(thing,signature,publicKey){checkIsPublicKey(publicKey),thing=normalizeInput(thing),signature=toBase64(signature);var verifier=crypto2.createVerify("RSA-SHA"+bits);return verifier.update(thing),verifier.verify({key:publicKey,padding:crypto2.constants.RSA_PKCS1_PSS_PADDING,saltLength:crypto2.constants.RSA_PSS_SALTLEN_DIGEST},signature,"base64")}}function createECDSASigner(bits){var inner=createKeySigner(bits);return function(){var signature=inner.apply(null,arguments);return signature=formatEcdsa.derToJose(signature,"ES"+bits),signature}}function createECDSAVerifer(bits){var inner=createKeyVerifier(bits);return function(thing,signature,publicKey){signature=formatEcdsa.joseToDer(signature,"ES"+bits).toString("base64");var result=inner(thing,signature,publicKey);return result}}function createNoneSigner(){return function(){return""}}function createNoneVerifier(){return function(thing,signature){return signature===""}}module.exports=function(algorithm){var signerFactories={hs:createHmacSigner,rs:createKeySigner,ps:createPSSKeySigner,es:createECDSASigner,none:createNoneSigner},verifierFactories={hs:createHmacVerifier,rs:createKeyVerifier,ps:createPSSKeyVerifier,es:createECDSAVerifer,none:createNoneVerifier},match2=algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!match2)throw typeError(MSG_INVALID_ALGORITHM,algorithm);var algo=(match2[1]||match2[3]).toLowerCase(),bits=match2[2];return{sign:signerFactories[algo](bits),verify:verifierFactories[algo](bits)}}}});var require_tostring=__commonJS({"node_modules/jws/lib/tostring.js"(exports,module){var Buffer2=__require("buffer").Buffer;module.exports=function(obj){return typeof obj=="string"?obj:typeof obj=="number"||Buffer2.isBuffer(obj)?obj.toString():JSON.stringify(obj)}}});var require_sign_stream=__commonJS({"node_modules/jws/lib/sign-stream.js"(exports,module){var Buffer2=require_safe_buffer().Buffer,DataStream=require_data_stream(),jwa=require_jwa(),Stream2=__require("stream"),toString=require_tostring(),util=__require("util");function base64url(string,encoding){return Buffer2.from(string,encoding).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function jwsSecuredInput(header,payload,encoding){encoding=encoding||"utf8";var encodedHeader=base64url(toString(header),"binary"),encodedPayload=base64url(toString(payload),encoding);return util.format("%s.%s",encodedHeader,encodedPayload)}function jwsSign(opts){var header=opts.header,payload=opts.payload,secretOrKey=opts.secret||opts.privateKey,encoding=opts.encoding,algo=jwa(header.alg),securedInput=jwsSecuredInput(header,payload,encoding),signature=algo.sign(securedInput,secretOrKey);return util.format("%s.%s",securedInput,signature)}function SignStream(opts){var secret=opts.secret;if(secret=secret??opts.privateKey,secret=secret??opts.key,/^hs/i.test(opts.header.alg)===!0&&secret==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var secretStream=new DataStream(secret);this.readable=!0,this.header=opts.header,this.encoding=opts.encoding,this.secret=this.privateKey=this.key=secretStream,this.payload=new DataStream(opts.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))}util.inherits(SignStream,Stream2);SignStream.prototype.sign=function(){try{var signature=jwsSign({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",signature),this.emit("data",signature),this.emit("end"),this.readable=!1,signature}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}};SignStream.sign=jwsSign;module.exports=SignStream}});var require_verify_stream=__commonJS({"node_modules/jws/lib/verify-stream.js"(exports,module){var Buffer2=require_safe_buffer().Buffer,DataStream=require_data_stream(),jwa=require_jwa(),Stream2=__require("stream"),toString=require_tostring(),util=__require("util"),JWS_REGEX=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function isObject(thing){return Object.prototype.toString.call(thing)==="[object Object]"}function safeJsonParse(thing){if(isObject(thing))return thing;try{return JSON.parse(thing)}catch{return}}function headerFromJWS(jwsSig){var encodedHeader=jwsSig.split(".",1)[0];return safeJsonParse(Buffer2.from(encodedHeader,"base64").toString("binary"))}function securedInputFromJWS(jwsSig){return jwsSig.split(".",2).join(".")}function signatureFromJWS(jwsSig){return jwsSig.split(".")[2]}function payloadFromJWS(jwsSig,encoding){encoding=encoding||"utf8";var payload=jwsSig.split(".")[1];return Buffer2.from(payload,"base64").toString(encoding)}function isValidJws(string){return JWS_REGEX.test(string)&&!!headerFromJWS(string)}function jwsVerify(jwsSig,algorithm,secretOrKey){if(!algorithm){var err=new Error("Missing algorithm parameter for jws.verify");throw err.code="MISSING_ALGORITHM",err}jwsSig=toString(jwsSig);var signature=signatureFromJWS(jwsSig),securedInput=securedInputFromJWS(jwsSig),algo=jwa(algorithm);return algo.verify(securedInput,signature,secretOrKey)}function jwsDecode(jwsSig,opts){if(opts=opts||{},jwsSig=toString(jwsSig),!isValidJws(jwsSig))return null;var header=headerFromJWS(jwsSig);if(!header)return null;var payload=payloadFromJWS(jwsSig);return(header.typ==="JWT"||opts.json)&&(payload=JSON.parse(payload,opts.encoding)),{header,payload,signature:signatureFromJWS(jwsSig)}}function VerifyStream(opts){opts=opts||{};var secretOrKey=opts.secret;if(secretOrKey=secretOrKey??opts.publicKey,secretOrKey=secretOrKey??opts.key,/^hs/i.test(opts.algorithm)===!0&&secretOrKey==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var secretStream=new DataStream(secretOrKey);this.readable=!0,this.algorithm=opts.algorithm,this.encoding=opts.encoding,this.secret=this.publicKey=this.key=secretStream,this.signature=new DataStream(opts.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))}util.inherits(VerifyStream,Stream2);VerifyStream.prototype.verify=function(){try{var valid=jwsVerify(this.signature.buffer,this.algorithm,this.key.buffer),obj=jwsDecode(this.signature.buffer,this.encoding);return this.emit("done",valid,obj),this.emit("data",valid),this.emit("end"),this.readable=!1,valid}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}};VerifyStream.decode=jwsDecode;VerifyStream.isValid=isValidJws;VerifyStream.verify=jwsVerify;module.exports=VerifyStream}});var require_jws=__commonJS({"node_modules/jws/index.js"(exports){var SignStream=require_sign_stream(),VerifyStream=require_verify_stream(),ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];exports.ALGORITHMS=ALGORITHMS;exports.sign=SignStream.sign;exports.verify=VerifyStream.verify;exports.decode=VerifyStream.decode;exports.isValid=VerifyStream.isValid;exports.createSign=function(opts){return new SignStream(opts)};exports.createVerify=function(opts){return new VerifyStream(opts)}}});var require_jwsSign=__commonJS({"node_modules/google-auth-library/build/src/gtoken/jwsSign.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.buildPayloadForJwsSign=buildPayloadForJwsSign;exports.getJwsSign=getJwsSign;var jws_1=require_jws(),ALG_RS256="RS256",GOOGLE_TOKEN_URL="https://oauth2.googleapis.com/token";function buildPayloadForJwsSign(tokenOptions){let iat=Math.floor(new Date().getTime()/1e3);return{iss:tokenOptions.iss,scope:tokenOptions.scope,aud:GOOGLE_TOKEN_URL,exp:iat+3600,iat,sub:tokenOptions.sub,...tokenOptions.additionalClaims}}function getJwsSign(tokenOptions){let payload=buildPayloadForJwsSign(tokenOptions);return(0,jws_1.sign)({header:{alg:ALG_RS256},payload,secret:tokenOptions.key})}}});var require_getToken=__commonJS({"node_modules/google-auth-library/build/src/gtoken/getToken.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getToken=getToken;var jwsSign_1=require_jwsSign(),GOOGLE_TOKEN_URL="https://oauth2.googleapis.com/token",GOOGLE_GRANT_TYPE="urn:ietf:params:oauth:grant-type:jwt-bearer",generateRequestOptions=tokenOptions=>({method:"POST",url:GOOGLE_TOKEN_URL,data:new URLSearchParams({grant_type:GOOGLE_GRANT_TYPE,assertion:(0,jwsSign_1.getJwsSign)(tokenOptions)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function getToken(tokenOptions){if(!tokenOptions.transporter)throw new Error("No transporter set.");try{let gaxiosOptions=generateRequestOptions(tokenOptions);return(await tokenOptions.transporter.request(gaxiosOptions)).data}catch(e){let err=e,errorData=err.response?.data;throw errorData?.error&&(err.message=`${errorData.error}: ${errorData.error_description}`),err}}}});var require_errorWithCode=__commonJS({"node_modules/google-auth-library/build/src/gtoken/errorWithCode.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ErrorWithCode=void 0;var ErrorWithCode=class extends Error{code;constructor(message,code){super(message),this.code=code}};exports.ErrorWithCode=ErrorWithCode}});var require_getCredentials=__commonJS({"node_modules/google-auth-library/build/src/gtoken/getCredentials.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getCredentials=getCredentials;var path2=__require("path"),fs2=__require("fs"),util_1=__require("util"),errorWithCode_1=require_errorWithCode(),readFile=fs2.readFile?(0,util_1.promisify)(fs2.readFile):async()=>{throw new errorWithCode_1.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},ExtensionFiles;(function(ExtensionFiles2){ExtensionFiles2.JSON=".json",ExtensionFiles2.DER=".der",ExtensionFiles2.CRT=".crt",ExtensionFiles2.PEM=".pem",ExtensionFiles2.P12=".p12",ExtensionFiles2.PFX=".pfx"})(ExtensionFiles||(ExtensionFiles={}));var JsonCredentialsProvider=class{keyFilePath;constructor(keyFilePath){this.keyFilePath=keyFilePath}async getCredentials(){let key=await readFile(this.keyFilePath,"utf8"),body;try{body=JSON.parse(key)}catch(error){let err=error;throw new Error(`Invalid JSON key file: ${err.message}`)}let privateKey=body.private_key,clientEmail=body.client_email;if(!privateKey||!clientEmail)throw new errorWithCode_1.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey,clientEmail}}},PemCredentialsProvider=class{keyFilePath;constructor(keyFilePath){this.keyFilePath=keyFilePath}async getCredentials(){return{privateKey:await readFile(this.keyFilePath,"utf8")}}},P12CredentialsProvider=class{async getCredentials(){throw new errorWithCode_1.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")}},CredentialsProviderFactory=class{static create(keyFilePath){switch(path2.extname(keyFilePath)){case ExtensionFiles.JSON:return new JsonCredentialsProvider(keyFilePath);case ExtensionFiles.DER:case ExtensionFiles.CRT:case ExtensionFiles.PEM:return new PemCredentialsProvider(keyFilePath);case ExtensionFiles.P12:case ExtensionFiles.PFX:return new P12CredentialsProvider;default:throw new errorWithCode_1.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function getCredentials(keyFilePath){return CredentialsProviderFactory.create(keyFilePath).getCredentials()}}});var require_tokenHandler=__commonJS({"node_modules/google-auth-library/build/src/gtoken/tokenHandler.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.TokenHandler=void 0;var getToken_1=require_getToken(),getCredentials_1=require_getCredentials(),TokenHandler=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(tokenOptions){this.tokenOptions=tokenOptions}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let credentials=await(0,getCredentials_1.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=credentials.privateKey,this.tokenOptions.email=credentials.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let now=new Date().getTime(),eagerRefreshThresholdMillis=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=now+eagerRefreshThresholdMillis}hasExpired(){let now=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(forceRefresh){if(await this.processCredentials(),this.inFlightRequest&&!forceRefresh)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!forceRefresh)return this.token;try{this.inFlightRequest=(0,getToken_1.getToken)(this.tokenOptions);let token=await this.inFlightRequest;return this.token=token,this.tokenExpiresAt=new Date().getTime()+(token.expires_in??0)*1e3,token}finally{this.inFlightRequest=void 0}}};exports.TokenHandler=TokenHandler}});var require_revokeToken=__commonJS({"node_modules/google-auth-library/build/src/gtoken/revokeToken.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.revokeToken=revokeToken;var GOOGLE_REVOKE_TOKEN_URL="https://oauth2.googleapis.com/revoke?token=",DEFAULT_RETRY_VALUE=!0;async function revokeToken(accessToken,transporter){let url=GOOGLE_REVOKE_TOKEN_URL+accessToken;return await transporter.request({url,retry:DEFAULT_RETRY_VALUE})}}});var require_googleToken=__commonJS({"node_modules/google-auth-library/build/src/gtoken/googleToken.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GoogleToken=void 0;var gaxios_1=require_src(),tokenHandler_1=require_tokenHandler(),revokeToken_1=require_revokeToken(),GoogleToken=class{tokenOptions;tokenHandler;constructor(options){this.tokenOptions=options||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:opts=>(0,gaxios_1.request)(opts)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new tokenHandler_1.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(callbackOrOptions,opts={forceRefresh:!1}){let callback;typeof callbackOrOptions=="function"?callback=callbackOrOptions:typeof callbackOrOptions=="object"&&(opts=callbackOrOptions);let promise=this.tokenHandler.getToken(opts.forceRefresh??!1);return callback&&promise.then(token=>callback(null,token),callback),promise}revokeToken(callback){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let promise=(0,revokeToken_1.revokeToken)(this.accessToken,this.tokenOptions.transporter);callback&&promise.then(()=>callback(),callback),this.tokenHandler=new tokenHandler_1.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};exports.GoogleToken=GoogleToken}});var require_jwtaccess=__commonJS({"node_modules/google-auth-library/build/src/auth/jwtaccess.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.JWTAccess=void 0;var jws=require_jws(),util_1=require_util2(),DEFAULT_HEADER={alg:"RS256",typ:"JWT"},JWTAccess=class _JWTAccess{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new util_1.LRUCache({capacity:500,maxAge:3600*1e3});constructor(email,key,keyId,eagerRefreshThresholdMillis){this.email=email,this.key=key,this.keyId=keyId,this.eagerRefreshThresholdMillis=eagerRefreshThresholdMillis??300*1e3}getCachedKey(url,scopes){let cacheKey=url;if(scopes&&Array.isArray(scopes)&&scopes.length?cacheKey=url?`${url}_${scopes.join("_")}`:`${scopes.join("_")}`:typeof scopes=="string"&&(cacheKey=url?`${url}_${scopes}`:scopes),!cacheKey)throw Error("Scopes or url must be provided");return cacheKey}getRequestHeaders(url,additionalClaims,scopes){let key=this.getCachedKey(url,scopes),cachedToken=this.cache.get(key),now=Date.now();if(cachedToken&&cachedToken.expiration-now>this.eagerRefreshThresholdMillis)return new Headers(cachedToken.headers);let iat=Math.floor(Date.now()/1e3),exp=_JWTAccess.getExpirationTime(iat),defaultClaims;if(Array.isArray(scopes)&&(scopes=scopes.join(" ")),scopes?defaultClaims={iss:this.email,sub:this.email,scope:scopes,exp,iat}:defaultClaims={iss:this.email,sub:this.email,aud:url,exp,iat},additionalClaims){for(let claim in defaultClaims)if(additionalClaims[claim])throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let header=this.keyId?{...DEFAULT_HEADER,kid:this.keyId}:DEFAULT_HEADER,payload=Object.assign(defaultClaims,additionalClaims),signedJWT=jws.sign({header,payload,secret:this.key}),headers=new Headers({authorization:`Bearer ${signedJWT}`});return this.cache.set(key,{expiration:exp*1e3,headers}),headers}static getExpirationTime(iat){return iat+3600}fromJSON(json2){if(!json2)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!json2.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!json2.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=json2.client_email,this.key=json2.private_key,this.keyId=json2.private_key_id,this.projectId=json2.project_id}fromStream(inputStream,callback){if(callback)this.fromStreamAsync(inputStream).then(()=>callback(),callback);else return this.fromStreamAsync(inputStream)}fromStreamAsync(inputStream){return new Promise((resolve,reject)=>{inputStream||reject(new Error("Must pass in a stream containing the service account auth settings."));let s="";inputStream.setEncoding("utf8").on("data",chunk=>s+=chunk).on("error",reject).on("end",()=>{try{let data=JSON.parse(s);this.fromJSON(data),resolve()}catch(err){reject(err)}})})}};exports.JWTAccess=JWTAccess}});var require_jwtclient=__commonJS({"node_modules/google-auth-library/build/src/auth/jwtclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.JWT=void 0;var googleToken_1=require_googleToken(),getCredentials_1=require_getCredentials(),jwtaccess_1=require_jwtaccess(),oauth2client_1=require_oauth2client(),authclient_1=require_authclient(),JWT=class _JWT extends oauth2client_1.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(options={}){super(options),this.email=options.email,this.keyFile=options.keyFile,this.key=options.key,this.keyId=options.keyId,this.scopes=options.scopes,this.subject=options.subject,this.additionalClaims=options.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(scopes){let jwt=new _JWT(this);return jwt.scopes=scopes,jwt}async getRequestMetadataAsync(url){url=this.defaultServicePath?`https://${this.defaultServicePath}/`:url;let useSelfSignedJWT=!this.hasUserScopes()&&url||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==authclient_1.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==authclient_1.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);if(!this.apiKey&&useSelfSignedJWT)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${tokens.id_token}`}))}}else{this.access||(this.access=new jwtaccess_1.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let scopes;this.hasUserScopes()?scopes=this.scopes:url||(scopes=this.defaultScopes);let useScopes=this.useJWTAccessWithScope||this.universeDomain!==authclient_1.DEFAULT_UNIVERSE,headers=await this.access.getRequestHeaders(url??void 0,this.additionalClaims,useScopes?scopes:void 0);return{headers:this.addSharedMetadataHeaders(headers)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(url):{headers:new Headers}}async fetchIdToken(targetAudience){let gtoken=new googleToken_1.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:targetAudience},transporter:this.transporter});if(await gtoken.getToken({forceRefresh:!0}),!gtoken.idToken)throw new Error("Unknown error: Failed to fetch ID token");return gtoken.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(callback){if(callback)this.authorizeAsync().then(r=>callback(null,r),callback);else return this.authorizeAsync()}async authorizeAsync(){let result=await this.refreshToken();if(!result)throw new Error("No result returned");return this.credentials=result.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,result.tokens}async refreshTokenNoCache(){let gtoken=this.createGToken(),tokens={access_token:(await gtoken.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:gtoken.expiresAt,id_token:gtoken.idToken};return this.emit("tokens",tokens),{res:null,tokens}}createGToken(){return this.gtoken||(this.gtoken=new googleToken_1.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(json2){if(!json2)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!json2.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!json2.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=json2.client_email,this.key=json2.private_key,this.keyId=json2.private_key_id,this.projectId=json2.project_id,this.quotaProjectId=json2.quota_project_id,this.universeDomain=json2.universe_domain||this.universeDomain}fromStream(inputStream,callback){if(callback)this.fromStreamAsync(inputStream).then(()=>callback(),callback);else return this.fromStreamAsync(inputStream)}fromStreamAsync(inputStream){return new Promise((resolve,reject)=>{if(!inputStream)throw new Error("Must pass in a stream containing the service account auth settings.");let s="";inputStream.setEncoding("utf8").on("error",reject).on("data",chunk=>s+=chunk).on("end",()=>{try{let data=JSON.parse(s);this.fromJSON(data),resolve()}catch(e){reject(e)}})})}fromAPIKey(apiKey){if(typeof apiKey!="string")throw new Error("Must provide an API Key string.");this.apiKey=apiKey}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let gtoken=this.createGToken(),creds=await(0,getCredentials_1.getCredentials)(this.keyFile);return{private_key:creds.privateKey,client_email:creds.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};exports.JWT=JWT}});var require_refreshclient=__commonJS({"node_modules/google-auth-library/build/src/auth/refreshclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.UserRefreshClient=exports.USER_REFRESH_ACCOUNT_TYPE=void 0;var oauth2client_1=require_oauth2client(),authclient_1=require_authclient();exports.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var UserRefreshClient=class _UserRefreshClient extends oauth2client_1.OAuth2Client{_refreshToken;constructor(optionsOrClientId,clientSecret,refreshToken,eagerRefreshThresholdMillis,forceRefreshOnFailure){let opts=optionsOrClientId&&typeof optionsOrClientId=="object"?optionsOrClientId:{clientId:optionsOrClientId,clientSecret,refreshToken,eagerRefreshThresholdMillis,forceRefreshOnFailure};super(opts),this._refreshToken=opts.refreshToken,this.credentials.refresh_token=opts.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(targetAudience){let opts={..._UserRefreshClient.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:targetAudience}),responseType:"json"};return authclient_1.AuthClient.setMethodName(opts,"fetchIdToken"),(await this.transporter.request(opts)).data.id_token}fromJSON(json2){if(!json2)throw new Error("Must pass in a JSON object containing the user refresh token");if(json2.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!json2.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!json2.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!json2.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=json2.client_id,this._clientSecret=json2.client_secret,this._refreshToken=json2.refresh_token,this.credentials.refresh_token=json2.refresh_token,this.quotaProjectId=json2.quota_project_id,this.universeDomain=json2.universe_domain||this.universeDomain}fromStream(inputStream,callback){if(callback)this.fromStreamAsync(inputStream).then(()=>callback(),callback);else return this.fromStreamAsync(inputStream)}async fromStreamAsync(inputStream){return new Promise((resolve,reject)=>{if(!inputStream)return reject(new Error("Must pass in a stream containing the user refresh token."));let s="";inputStream.setEncoding("utf8").on("error",reject).on("data",chunk=>s+=chunk).on("end",()=>{try{let data=JSON.parse(s);return this.fromJSON(data),resolve()}catch(err){return reject(err)}})})}static fromJSON(json2){let client=new _UserRefreshClient;return client.fromJSON(json2),client}};exports.UserRefreshClient=UserRefreshClient}});var require_impersonated=__commonJS({"node_modules/google-auth-library/build/src/auth/impersonated.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.Impersonated=exports.IMPERSONATED_ACCOUNT_TYPE=void 0;var oauth2client_1=require_oauth2client(),gaxios_1=require_src(),util_1=require_util2();exports.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Impersonated=class _Impersonated extends oauth2client_1.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(options={}){if(super(options),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=options.sourceClient??new oauth2client_1.OAuth2Client,this.targetPrincipal=options.targetPrincipal??"",this.delegates=options.delegates??[],this.targetScopes=options.targetScopes??[],this.lifetime=options.lifetime??3600,!!!(0,util_1.originalOrCamelOptions)(options).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=options.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(blobToSign){await this.sourceClient.getAccessToken();let name=`projects/-/serviceAccounts/${this.targetPrincipal}`,u=`${this.endpoint}/v1/${name}:signBlob`,body={delegates:this.delegates,payload:Buffer.from(blobToSign).toString("base64")};return(await this.sourceClient.request({..._Impersonated.RETRY_CONFIG,url:u,data:body,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let name="projects/-/serviceAccounts/"+this.targetPrincipal,u=`${this.endpoint}/v1/${name}:generateAccessToken`,body={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},res=await this.sourceClient.request({..._Impersonated.RETRY_CONFIG,url:u,data:body,method:"POST"}),tokenResponse=res.data;return this.credentials.access_token=tokenResponse.accessToken,this.credentials.expiry_date=Date.parse(tokenResponse.expireTime),{tokens:this.credentials,res}}catch(error){if(!(error instanceof Error))throw error;let status=0,message="";throw error instanceof gaxios_1.GaxiosError&&(status=error?.response?.data?.error?.status,message=error?.response?.data?.error?.message),status&&message?(error.message=`${status}: unable to impersonate: ${message}`,error):(error.message=`unable to impersonate: ${error}`,error)}}async fetchIdToken(targetAudience,options){await this.sourceClient.getAccessToken();let name=`projects/-/serviceAccounts/${this.targetPrincipal}`,u=`${this.endpoint}/v1/${name}:generateIdToken`,body={delegates:this.delegates,audience:targetAudience,includeEmail:options?.includeEmail??!0,useEmailAzp:options?.includeEmail??!0};return(await this.sourceClient.request({..._Impersonated.RETRY_CONFIG,url:u,data:body,method:"POST"})).data.token}};exports.Impersonated=Impersonated}});var require_oauth2common=__commonJS({"node_modules/google-auth-library/build/src/auth/oauth2common.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.OAuthClientAuthHandler=void 0;exports.getErrorFromOAuthErrorResponse=getErrorFromOAuthErrorResponse;var gaxios_1=require_src(),crypto_1=require_crypto3(),METHODS_SUPPORTING_REQUEST_BODY=["PUT","POST","PATCH"],OAuthClientAuthHandler=class{#crypto=(0,crypto_1.createCrypto)();#clientAuthentication;transporter;constructor(options){options&&"clientId"in options?(this.#clientAuthentication=options,this.transporter=new gaxios_1.Gaxios):(this.#clientAuthentication=options?.clientAuthentication,this.transporter=options?.transporter||new gaxios_1.Gaxios)}applyClientAuthenticationOptions(opts,bearerToken){opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.injectAuthenticatedHeaders(opts,bearerToken),bearerToken||this.injectAuthenticatedRequestBody(opts)}injectAuthenticatedHeaders(opts,bearerToken){if(bearerToken)opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers,{authorization:`Bearer ${bearerToken}`});else if(this.#clientAuthentication?.confidentialClientType==="basic"){opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers);let clientId=this.#clientAuthentication.clientId,clientSecret=this.#clientAuthentication.clientSecret||"",base64EncodedCreds=this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);gaxios_1.Gaxios.mergeHeaders(opts.headers,{authorization:`Basic ${base64EncodedCreds}`})}}injectAuthenticatedRequestBody(opts){if(this.#clientAuthentication?.confidentialClientType==="request-body"){let method=(opts.method||"GET").toUpperCase();if(!METHODS_SUPPORTING_REQUEST_BODY.includes(method))throw new Error(`${method} HTTP method does not support ${this.#clientAuthentication.confidentialClientType} client authentication`);let contentType=new Headers(opts.headers).get("content-type");if(contentType?.startsWith("application/x-www-form-urlencoded")||opts.data instanceof URLSearchParams){let data=new URLSearchParams(opts.data??"");data.append("client_id",this.#clientAuthentication.clientId),data.append("client_secret",this.#clientAuthentication.clientSecret||""),opts.data=data}else if(contentType?.startsWith("application/json"))opts.data=opts.data||{},Object.assign(opts.data,{client_id:this.#clientAuthentication.clientId,client_secret:this.#clientAuthentication.clientSecret||""});else throw new Error(`${contentType} content-types are not supported with ${this.#clientAuthentication.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};exports.OAuthClientAuthHandler=OAuthClientAuthHandler;function getErrorFromOAuthErrorResponse(resp,err){let errorCode=resp.error,errorDescription=resp.error_description,errorUri=resp.error_uri,message=`Error code ${errorCode}`;typeof errorDescription<"u"&&(message+=`: ${errorDescription}`),typeof errorUri<"u"&&(message+=` - ${errorUri}`);let newError=new Error(message);if(err){let keys=Object.keys(err);err.stack&&keys.push("stack"),keys.forEach(key=>{key!=="message"&&Object.defineProperty(newError,key,{value:err[key],writable:!1,enumerable:!0})})}return newError}}});var require_stscredentials=__commonJS({"node_modules/google-auth-library/build/src/auth/stscredentials.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.StsCredentials=void 0;var gaxios_1=require_src(),authclient_1=require_authclient(),oauth2common_1=require_oauth2common(),util_1=require_util2(),StsCredentials=class _StsCredentials extends oauth2common_1.OAuthClientAuthHandler{#tokenExchangeEndpoint;constructor(options={tokenExchangeEndpoint:""},clientAuthentication){(typeof options!="object"||options instanceof URL)&&(options={tokenExchangeEndpoint:options,clientAuthentication}),super(options),this.#tokenExchangeEndpoint=options.tokenExchangeEndpoint}async exchangeToken(stsCredentialsOptions,headers,options){let values={grant_type:stsCredentialsOptions.grantType,resource:stsCredentialsOptions.resource,audience:stsCredentialsOptions.audience,scope:stsCredentialsOptions.scope?.join(" "),requested_token_type:stsCredentialsOptions.requestedTokenType,subject_token:stsCredentialsOptions.subjectToken,subject_token_type:stsCredentialsOptions.subjectTokenType,actor_token:stsCredentialsOptions.actingParty?.actorToken,actor_token_type:stsCredentialsOptions.actingParty?.actorTokenType,options:options&&JSON.stringify(options)},opts={..._StsCredentials.RETRY_CONFIG,url:this.#tokenExchangeEndpoint.toString(),method:"POST",headers,data:new URLSearchParams((0,util_1.removeUndefinedValuesInObject)(values)),responseType:"json"};authclient_1.AuthClient.setMethodName(opts,"exchangeToken"),this.applyClientAuthenticationOptions(opts);try{let response=await this.transporter.request(opts),stsSuccessfulResponse=response.data;return stsSuccessfulResponse.res=response,stsSuccessfulResponse}catch(error){throw error instanceof gaxios_1.GaxiosError&&error.response?(0,oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data,error):error}}};exports.StsCredentials=StsCredentials}});var require_baseexternalclient=__commonJS({"node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.BaseExternalAccountClient=exports.CLOUD_RESOURCE_MANAGER=exports.EXTERNAL_ACCOUNT_TYPE=exports.EXPIRATION_TIME_OFFSET=void 0;var gaxios_1=require_src(),stream=__require("stream"),authclient_1=require_authclient(),sts=require_stscredentials(),util_1=require_util2(),shared_cjs_1=require_shared2(),STS_GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange",STS_REQUEST_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token",DEFAULT_OAUTH_SCOPE="https://www.googleapis.com/auth/cloud-platform",DEFAULT_TOKEN_LIFESPAN=3600;exports.EXPIRATION_TIME_OFFSET=300*1e3;exports.EXTERNAL_ACCOUNT_TYPE="external_account";exports.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var WORKFORCE_AUDIENCE_PATTERN="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",DEFAULT_TOKEN_URL="https://sts.{universeDomain}/v1/token",BaseExternalAccountClient=class _BaseExternalAccountClient extends authclient_1.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#pendingAccessToken=null;constructor(options){super(options);let opts=(0,util_1.originalOrCamelOptions)(options),type=opts.get("type");if(type&&type!==exports.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but received "${options.type}"`);let clientId=opts.get("client_id"),clientSecret=opts.get("client_secret");this.tokenUrl=opts.get("token_url")??DEFAULT_TOKEN_URL.replace("{universeDomain}",this.universeDomain);let subjectTokenType=opts.get("subject_token_type"),workforcePoolUserProject=opts.get("workforce_pool_user_project"),serviceAccountImpersonationUrl=opts.get("service_account_impersonation_url"),serviceAccountImpersonation=opts.get("service_account_impersonation"),serviceAccountImpersonationLifetime=(0,util_1.originalOrCamelOptions)(serviceAccountImpersonation).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(opts.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),clientId&&(this.clientAuth={confidentialClientType:"basic",clientId,clientSecret}),this.stsCredential=new sts.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=opts.get("scopes")||[DEFAULT_OAUTH_SCOPE],this.cachedAccessToken=null,this.audience=opts.get("audience"),this.subjectTokenType=subjectTokenType,this.workforcePoolUserProject=workforcePoolUserProject;let workforceAudiencePattern=new RegExp(WORKFORCE_AUDIENCE_PATTERN);if(this.workforcePoolUserProject&&!this.audience.match(workforceAudiencePattern))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=serviceAccountImpersonationUrl,this.serviceAccountImpersonationLifetime=serviceAccountImpersonationLifetime,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=DEFAULT_TOKEN_LIFESPAN),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(credentials){super.setCredentials(credentials),this.cachedAccessToken=credentials}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let accessTokenResponse=await this.getAccessToken(),headers=new Headers({authorization:`Bearer ${accessTokenResponse.token}`});return this.addSharedMetadataHeaders(headers)}request(opts,callback){if(callback)this.requestAsync(opts).then(r=>callback(null,r),e=>callback(e,e.response));else return this.requestAsync(opts)}async getProjectId(){let projectNumber=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(projectNumber){let headers=await this.getRequestHeaders(),opts={..._BaseExternalAccountClient.RETRY_CONFIG,headers,url:`${this.cloudResourceManagerURL.toString()}${projectNumber}`,responseType:"json"};authclient_1.AuthClient.setMethodName(opts,"getProjectId");let response=await this.transporter.request(opts);return this.projectId=response.data.projectId,this.projectId}return null}async requestAsync(opts,reAuthRetried=!1){let response;try{let requestHeaders=await this.getRequestHeaders();opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,requestHeaders),response=await this.transporter.request(opts)}catch(e){let res=e.response;if(res){let statusCode=res.status,isReadableStream=res.config.data instanceof stream.Readable;if(!reAuthRetried&&(statusCode===401||statusCode===403)&&!isReadableStream&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(opts,!0)}throw e}return response}async refreshAccessTokenAsync(){this.#pendingAccessToken=this.#pendingAccessToken||this.#internalRefreshAccessTokenAsync();try{return await this.#pendingAccessToken}finally{this.#pendingAccessToken=null}}async#internalRefreshAccessTokenAsync(){let subjectToken=await this.retrieveSubjectToken(),stsCredentialsOptions={grantType:STS_GRANT_TYPE,audience:this.audience,requestedTokenType:STS_REQUEST_TOKEN_TYPE,subjectToken,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[DEFAULT_OAUTH_SCOPE]:this.getScopesArray()},additionalOptions=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,additionalHeaders=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),stsResponse=await this.stsCredential.exchangeToken(stsCredentialsOptions,additionalHeaders,additionalOptions);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(stsResponse.access_token):stsResponse.expires_in?this.cachedAccessToken={access_token:stsResponse.access_token,expiry_date:new Date().getTime()+stsResponse.expires_in*1e3,res:stsResponse.res}:this.cachedAccessToken={access_token:stsResponse.access_token,res:stsResponse.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(audience){let match2=audience.match(/\/projects\/([^/]+)/);return match2?match2[1]:null}async getImpersonatedAccessToken(token){let opts={..._BaseExternalAccountClient.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};authclient_1.AuthClient.setMethodName(opts,"getImpersonatedAccessToken");let response=await this.transporter.request(opts),successResponse=response.data;return{access_token:successResponse.accessToken,expiry_date:new Date(successResponse.expireTime).getTime(),res:response}}isExpired(accessToken){let now=new Date().getTime();return accessToken.expiry_date?now>=accessToken.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[DEFAULT_OAUTH_SCOPE]}getMetricsHeaderValue(){let nodeVersion=process.version.replace(/^v/,""),saImpersonation=this.serviceAccountImpersonationUrl!==void 0,credentialSourceType=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};exports.BaseExternalAccountClient=BaseExternalAccountClient}});var require_filesubjecttokensupplier=__commonJS({"node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.FileSubjectTokenSupplier=void 0;var util_1=__require("util"),fs2=__require("fs"),readFile=(0,util_1.promisify)(fs2.readFile??(()=>{})),realpath=(0,util_1.promisify)(fs2.realpath??(()=>{})),lstat=(0,util_1.promisify)(fs2.lstat??(()=>{})),FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(opts){this.filePath=opts.filePath,this.formatType=opts.formatType,this.subjectTokenFieldName=opts.subjectTokenFieldName}async getSubjectToken(){let parsedFilePath=this.filePath;try{if(parsedFilePath=await realpath(parsedFilePath),!(await lstat(parsedFilePath)).isFile())throw new Error}catch(err){throw err instanceof Error&&(err.message=`The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`),err}let subjectToken,rawText=await readFile(parsedFilePath,{encoding:"utf8"});if(this.formatType==="text"?subjectToken=rawText:this.formatType==="json"&&this.subjectTokenFieldName&&(subjectToken=JSON.parse(rawText)[this.subjectTokenFieldName]),!subjectToken)throw new Error("Unable to parse the subject_token from the credential_source file");return subjectToken}};exports.FileSubjectTokenSupplier=FileSubjectTokenSupplier}});var require_urlsubjecttokensupplier=__commonJS({"node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.UrlSubjectTokenSupplier=void 0;var authclient_1=require_authclient(),UrlSubjectTokenSupplier=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(opts){this.url=opts.url,this.formatType=opts.formatType,this.subjectTokenFieldName=opts.subjectTokenFieldName,this.headers=opts.headers,this.additionalGaxiosOptions=opts.additionalGaxiosOptions}async getSubjectToken(context){let opts={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};authclient_1.AuthClient.setMethodName(opts,"getSubjectToken");let subjectToken;if(this.formatType==="text"?subjectToken=(await context.transporter.request(opts)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(subjectToken=(await context.transporter.request(opts)).data[this.subjectTokenFieldName]),!subjectToken)throw new Error("Unable to parse the subject_token from the credential_source URL");return subjectToken}};exports.UrlSubjectTokenSupplier=UrlSubjectTokenSupplier}});var require_certificatesubjecttokensupplier=__commonJS({"node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.CertificateSubjectTokenSupplier=exports.InvalidConfigurationError=exports.CertificateSourceUnavailableError=exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var util_1=require_util2(),fs2=__require("fs"),crypto_1=__require("crypto"),https=__require("https");exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var CertificateSourceUnavailableError=class extends Error{constructor(message){super(message),this.name="CertificateSourceUnavailableError"}};exports.CertificateSourceUnavailableError=CertificateSourceUnavailableError;var InvalidConfigurationError=class extends Error{constructor(message){super(message),this.name="InvalidConfigurationError"}};exports.InvalidConfigurationError=InvalidConfigurationError;var CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(opts){if(!opts.useDefaultCertificateConfig&&!opts.certificateConfigLocation)throw new InvalidConfigurationError("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(opts.useDefaultCertificateConfig&&opts.certificateConfigLocation)throw new InvalidConfigurationError("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=opts.trustChainPath,this.certificateConfigPath=opts.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new InvalidConfigurationError("Cannot create mTLS Agent with missing certificate or key");return new https.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#resolveCertificateConfigFilePath();let{certPath,keyPath}=await this.#getCertAndKeyPaths();return{cert:this.cert,key:this.key}=await this.#getKeyAndCert(certPath,keyPath),await this.#processChainFromPaths(this.cert)}async#resolveCertificateConfigFilePath(){let overridePath=this.certificateConfigPath;if(overridePath){if(await(0,util_1.isValidFile)(overridePath))return overridePath;throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`)}let envPath=process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(envPath){if(await(0,util_1.isValidFile)(envPath))return envPath;throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`)}let wellKnownPath=(0,util_1.getWellKnownCertificateConfigFileLocation)();if(await(0,util_1.isValidFile)(wellKnownPath))return wellKnownPath;throw new CertificateSourceUnavailableError(`Could not find certificate configuration file. Searched override path, the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`)}async#getCertAndKeyPaths(){let configPath=this.certificateConfigPath,fileContents;try{fileContents=await fs2.promises.readFile(configPath,"utf8")}catch{throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`)}try{let config=JSON.parse(fileContents),certPath=config?.cert_configs?.workload?.cert_path,keyPath=config?.cert_configs?.workload?.key_path;if(!certPath||!keyPath)throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath,keyPath}}catch(e){throw e instanceof InvalidConfigurationError?e:new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`)}}async#getKeyAndCert(certPath,keyPath){let cert,key;try{cert=await fs2.promises.readFile(certPath),new crypto_1.X509Certificate(cert)}catch(err){let message=err instanceof Error?err.message:String(err);throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`)}try{key=await fs2.promises.readFile(keyPath),(0,crypto_1.createPrivateKey)(key)}catch(err){let message=err instanceof Error?err.message:String(err);throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`)}return{cert,key}}async#processChainFromPaths(leafCertBuffer){let leafCert=new crypto_1.X509Certificate(leafCertBuffer);if(!this.trustChainPath)return JSON.stringify([leafCert.raw.toString("base64")]);try{let chainCerts=((await fs2.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((pem,index)=>{try{return new crypto_1.X509Certificate(pem)}catch(err){let message=err instanceof Error?err.message:String(err);throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`)}}),leafIndex=chainCerts.findIndex(chainCert=>leafCert.raw.equals(chainCert.raw)),finalChain;if(leafIndex===-1)finalChain=[leafCert,...chainCerts];else if(leafIndex===0)finalChain=chainCerts;else throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);return JSON.stringify(finalChain.map(cert=>cert.raw.toString("base64")))}catch(err){if(err instanceof InvalidConfigurationError)throw err;let message=err instanceof Error?err.message:String(err);throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`)}}};exports.CertificateSubjectTokenSupplier=CertificateSubjectTokenSupplier}});var require_identitypoolclient=__commonJS({"node_modules/google-auth-library/build/src/auth/identitypoolclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.IdentityPoolClient=void 0;var baseexternalclient_1=require_baseexternalclient(),util_1=require_util2(),filesubjecttokensupplier_1=require_filesubjecttokensupplier(),urlsubjecttokensupplier_1=require_urlsubjecttokensupplier(),certificatesubjecttokensupplier_1=require_certificatesubjecttokensupplier(),stscredentials_1=require_stscredentials(),gaxios_1=require_src(),IdentityPoolClient=class _IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient{subjectTokenSupplier;constructor(options){super(options);let opts=(0,util_1.originalOrCamelOptions)(options),credentialSource=opts.get("credential_source"),subjectTokenSupplier=opts.get("subject_token_supplier");if(!credentialSource&&!subjectTokenSupplier)throw new Error("A credential source or subject token supplier must be specified.");if(credentialSource&&subjectTokenSupplier)throw new Error("Only one of credential source or subject token supplier can be specified.");if(subjectTokenSupplier)this.subjectTokenSupplier=subjectTokenSupplier,this.credentialSourceType="programmatic";else{let credentialSourceOpts=(0,util_1.originalOrCamelOptions)(credentialSource),formatOpts=(0,util_1.originalOrCamelOptions)(credentialSourceOpts.get("format")),formatType=formatOpts.get("type")||"text",formatSubjectTokenFieldName=formatOpts.get("subject_token_field_name");if(formatType!=="json"&&formatType!=="text")throw new Error(`Invalid credential_source format "${formatType}"`);if(formatType==="json"&&!formatSubjectTokenFieldName)throw new Error("Missing subject_token_field_name for JSON credential_source format");let file=credentialSourceOpts.get("file"),url=credentialSourceOpts.get("url"),certificate=credentialSourceOpts.get("certificate"),headers=credentialSourceOpts.get("headers");if(file&&url||url&&certificate||file&&certificate)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(file)this.credentialSourceType="file",this.subjectTokenSupplier=new filesubjecttokensupplier_1.FileSubjectTokenSupplier({filePath:file,formatType,subjectTokenFieldName:formatSubjectTokenFieldName});else if(url)this.credentialSourceType="url",this.subjectTokenSupplier=new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({url,formatType,subjectTokenFieldName:formatSubjectTokenFieldName,headers,additionalGaxiosOptions:_IdentityPoolClient.RETRY_CONFIG});else if(certificate){this.credentialSourceType="certificate";let certificateSubjecttokensupplier=new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:certificate.use_default_certificate_config,certificateConfigLocation:certificate.certificate_config_location,trustChainPath:certificate.trust_chain_path});this.subjectTokenSupplier=certificateSubjecttokensupplier}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let subjectToken=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier){let mtlsAgent=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new stscredentials_1.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new gaxios_1.Gaxios({agent:mtlsAgent})}),this.transporter=new gaxios_1.Gaxios({...this.transporter.defaults||{},agent:mtlsAgent})}return subjectToken}};exports.IdentityPoolClient=IdentityPoolClient}});var require_awsrequestsigner=__commonJS({"node_modules/google-auth-library/build/src/auth/awsrequestsigner.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.AwsRequestSigner=void 0;var gaxios_1=require_src(),crypto_1=require_crypto3(),AWS_ALGORITHM="AWS4-HMAC-SHA256",AWS_REQUEST_TYPE="aws4_request",AwsRequestSigner=class{getCredentials;region;crypto;constructor(getCredentials,region){this.getCredentials=getCredentials,this.region=region,this.crypto=(0,crypto_1.createCrypto)()}async getRequestOptions(amzOptions){if(!amzOptions.url)throw new RangeError('"url" is required in "amzOptions"');let requestPayloadData=typeof amzOptions.data=="object"?JSON.stringify(amzOptions.data):amzOptions.data,url=amzOptions.url,method=amzOptions.method||"GET",requestPayload=amzOptions.body||requestPayloadData,additionalAmzHeaders=amzOptions.headers,awsSecurityCredentials=await this.getCredentials(),uri=new URL(url);if(typeof requestPayload!="string"&&requestPayload!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);let headerMap=await generateAuthenticationHeaderMap({crypto:this.crypto,host:uri.host,canonicalUri:uri.pathname,canonicalQuerystring:uri.search.slice(1),method,region:this.region,securityCredentials:awsSecurityCredentials,requestPayload,additionalAmzHeaders}),headers=gaxios_1.Gaxios.mergeHeaders(headerMap.amzDate?{"x-amz-date":headerMap.amzDate}:{},{authorization:headerMap.authorizationHeader,host:uri.host},additionalAmzHeaders||{});awsSecurityCredentials.token&&gaxios_1.Gaxios.mergeHeaders(headers,{"x-amz-security-token":awsSecurityCredentials.token});let awsSignedReq={url,method,headers};return requestPayload!==void 0&&(awsSignedReq.body=requestPayload),awsSignedReq}};exports.AwsRequestSigner=AwsRequestSigner;async function sign(crypto2,key,msg){return await crypto2.signWithHmacSha256(key,msg)}async function getSigningKey(crypto2,key,dateStamp,region,serviceName){let kDate=await sign(crypto2,`AWS4${key}`,dateStamp),kRegion=await sign(crypto2,kDate,region),kService=await sign(crypto2,kRegion,serviceName);return await sign(crypto2,kService,"aws4_request")}async function generateAuthenticationHeaderMap(options){let additionalAmzHeaders=gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders),requestPayload=options.requestPayload||"",serviceName=options.host.split(".")[0],now=new Date,amzDate=now.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),dateStamp=now.toISOString().replace(/[-]/g,"").replace(/T.*/,"");options.securityCredentials.token&&additionalAmzHeaders.set("x-amz-security-token",options.securityCredentials.token);let amzHeaders=gaxios_1.Gaxios.mergeHeaders({host:options.host},additionalAmzHeaders.has("date")?{}:{"x-amz-date":amzDate},additionalAmzHeaders),canonicalHeaders="",signedHeadersList=[...amzHeaders.keys()].sort();signedHeadersList.forEach(key=>{canonicalHeaders+=`${key}:${amzHeaders.get(key)}
`});let signedHeaders=signedHeadersList.join(";"),payloadHash=await options.crypto.sha256DigestHex(requestPayload),canonicalRequest=`${options.method.toUpperCase()}
${options.canonicalUri}
${options.canonicalQuerystring}
${canonicalHeaders}
${signedHeaders}
${payloadHash}`,credentialScope=`${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`,stringToSign=`${AWS_ALGORITHM}
${amzDate}
${credentialScope}
`+await options.crypto.sha256DigestHex(canonicalRequest),signingKey=await getSigningKey(options.crypto,options.securityCredentials.secretAccessKey,dateStamp,options.region,serviceName),signature=await sign(options.crypto,signingKey,stringToSign),authorizationHeader=`${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${(0,crypto_1.fromArrayBufferToHex)(signature)}`;return{amzDate:additionalAmzHeaders.has("date")?void 0:amzDate,authorizationHeader,canonicalQuerystring:options.canonicalQuerystring}}}});var require_defaultawssecuritycredentialssupplier=__commonJS({"node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.DefaultAwsSecurityCredentialsSupplier=void 0;var authclient_1=require_authclient(),DefaultAwsSecurityCredentialsSupplier=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(opts){this.regionUrl=opts.regionUrl,this.securityCredentialsUrl=opts.securityCredentialsUrl,this.imdsV2SessionTokenUrl=opts.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=opts.additionalGaxiosOptions}async getAwsRegion(context){if(this.#regionFromEnv)return this.#regionFromEnv;let metadataHeaders=new Headers;if(!this.#regionFromEnv&&this.imdsV2SessionTokenUrl&&metadataHeaders.set("x-aws-ec2-metadata-token",await this.#getImdsV2SessionToken(context.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let opts={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:metadataHeaders};authclient_1.AuthClient.setMethodName(opts,"getAwsRegion");let response=await context.transporter.request(opts);return response.data.substr(0,response.data.length-1)}async getAwsSecurityCredentials(context){if(this.#securityCredentialsFromEnv)return this.#securityCredentialsFromEnv;let metadataHeaders=new Headers;this.imdsV2SessionTokenUrl&&metadataHeaders.set("x-aws-ec2-metadata-token",await this.#getImdsV2SessionToken(context.transporter));let roleName=await this.#getAwsRoleName(metadataHeaders,context.transporter),awsCreds=await this.#retrieveAwsSecurityCredentials(roleName,metadataHeaders,context.transporter);return{accessKeyId:awsCreds.AccessKeyId,secretAccessKey:awsCreds.SecretAccessKey,token:awsCreds.Token}}async#getImdsV2SessionToken(transporter){let opts={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return authclient_1.AuthClient.setMethodName(opts,"#getImdsV2SessionToken"),(await transporter.request(opts)).data}async#getAwsRoleName(headers,transporter){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let opts={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers};return authclient_1.AuthClient.setMethodName(opts,"#getAwsRoleName"),(await transporter.request(opts)).data}async#retrieveAwsSecurityCredentials(roleName,headers,transporter){let opts={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${roleName}`,headers,responseType:"json"};return authclient_1.AuthClient.setMethodName(opts,"#retrieveAwsSecurityCredentials"),(await transporter.request(opts)).data}get#regionFromEnv(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#securityCredentialsFromEnv(){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}};exports.DefaultAwsSecurityCredentialsSupplier=DefaultAwsSecurityCredentialsSupplier}});var require_awsclient=__commonJS({"node_modules/google-auth-library/build/src/auth/awsclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.AwsClient=void 0;var awsrequestsigner_1=require_awsrequestsigner(),baseexternalclient_1=require_baseexternalclient(),defaultawssecuritycredentialssupplier_1=require_defaultawssecuritycredentialssupplier(),util_1=require_util2(),gaxios_1=require_src(),AwsClient=class _AwsClient extends baseexternalclient_1.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL="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(options){super(options);let opts=(0,util_1.originalOrCamelOptions)(options),credentialSource=opts.get("credential_source"),awsSecurityCredentialsSupplier=opts.get("aws_security_credentials_supplier");if(!credentialSource&&!awsSecurityCredentialsSupplier)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(credentialSource&&awsSecurityCredentialsSupplier)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(awsSecurityCredentialsSupplier)this.awsSecurityCredentialsSupplier=awsSecurityCredentialsSupplier,this.regionalCredVerificationUrl=_AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL,this.credentialSourceType="programmatic";else{let credentialSourceOpts=(0,util_1.originalOrCamelOptions)(credentialSource);this.environmentId=credentialSourceOpts.get("environment_id");let regionUrl=credentialSourceOpts.get("region_url"),securityCredentialsUrl=credentialSourceOpts.get("url"),imdsV2SessionTokenUrl=credentialSourceOpts.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({regionUrl,securityCredentialsUrl,imdsV2SessionTokenUrl}),this.regionalCredVerificationUrl=credentialSourceOpts.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let match2=this.environmentId?.match(/^(aws)(\d+)$/);if(!match2||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(match2[2],10)!==1)throw new Error(`aws version "${match2[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new awsrequestsigner_1.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let options=await this.awsRequestSigner.getRequestOptions({..._AwsClient.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),reformattedHeader=[];return gaxios_1.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},options.headers).forEach((value,key)=>reformattedHeader.push({key,value})),encodeURIComponent(JSON.stringify({url:options.url,method:options.method,headers:reformattedHeader}))}};exports.AwsClient=AwsClient}});var require_executable_response=__commonJS({"node_modules/google-auth-library/build/src/auth/executable-response.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.InvalidSubjectTokenError=exports.InvalidMessageFieldError=exports.InvalidCodeFieldError=exports.InvalidTokenTypeFieldError=exports.InvalidExpirationTimeFieldError=exports.InvalidSuccessFieldError=exports.InvalidVersionFieldError=exports.ExecutableResponseError=exports.ExecutableResponse=void 0;var SAML_SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:saml2",OIDC_SUBJECT_TOKEN_TYPE1="urn:ietf:params:oauth:token-type:id_token",OIDC_SUBJECT_TOKEN_TYPE2="urn:ietf:params:oauth:token-type:jwt",ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(responseJson){if(!responseJson.version)throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");if(responseJson.success===void 0)throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");if(this.version=responseJson.version,this.success=responseJson.success,this.success){if(this.expirationTime=responseJson.expiration_time,this.tokenType=responseJson.token_type,this.tokenType!==SAML_SUBJECT_TOKEN_TYPE&&this.tokenType!==OIDC_SUBJECT_TOKEN_TYPE1&&this.tokenType!==OIDC_SUBJECT_TOKEN_TYPE2)throw new InvalidTokenTypeFieldError(`Executable response must contain a 'token_type' field when successful and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);if(this.tokenType===SAML_SUBJECT_TOKEN_TYPE){if(!responseJson.saml_response)throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);this.subjectToken=responseJson.saml_response}else{if(!responseJson.id_token)throw new InvalidSubjectTokenError(`Executable response must contain a 'id_token' field when token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);this.subjectToken=responseJson.id_token}}else{if(!responseJson.code)throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");if(!responseJson.message)throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=responseJson.code,this.errorMessage=responseJson.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};exports.ExecutableResponse=ExecutableResponse;var ExecutableResponseError=class extends Error{constructor(message){super(message),Object.setPrototypeOf(this,new.target.prototype)}};exports.ExecutableResponseError=ExecutableResponseError;var InvalidVersionFieldError=class extends ExecutableResponseError{};exports.InvalidVersionFieldError=InvalidVersionFieldError;var InvalidSuccessFieldError=class extends ExecutableResponseError{};exports.InvalidSuccessFieldError=InvalidSuccessFieldError;var InvalidExpirationTimeFieldError=class extends ExecutableResponseError{};exports.InvalidExpirationTimeFieldError=InvalidExpirationTimeFieldError;var InvalidTokenTypeFieldError=class extends ExecutableResponseError{};exports.InvalidTokenTypeFieldError=InvalidTokenTypeFieldError;var InvalidCodeFieldError=class extends ExecutableResponseError{};exports.InvalidCodeFieldError=InvalidCodeFieldError;var InvalidMessageFieldError=class extends ExecutableResponseError{};exports.InvalidMessageFieldError=InvalidMessageFieldError;var InvalidSubjectTokenError=class extends ExecutableResponseError{};exports.InvalidSubjectTokenError=InvalidSubjectTokenError}});var require_pluggable_auth_handler=__commonJS({"node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.PluggableAuthHandler=exports.ExecutableError=void 0;var executable_response_1=require_executable_response(),childProcess=__require("child_process"),fs2=__require("fs"),ExecutableError=class extends Error{code;constructor(message,code){super(`The executable failed with exit code: ${code} and error message: ${message}.`),this.code=code,Object.setPrototypeOf(this,new.target.prototype)}};exports.ExecutableError=ExecutableError;var PluggableAuthHandler=class _PluggableAuthHandler{commandComponents;timeoutMillis;outputFile;constructor(options){if(!options.command)throw new Error("No command provided.");if(this.commandComponents=_PluggableAuthHandler.parseCommand(options.command),this.timeoutMillis=options.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=options.outputFile}retrieveResponseFromExecutable(envMap){return new Promise((resolve,reject)=>{let child=childProcess.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(envMap)}}),output="";child.stdout.on("data",data=>{output+=data}),child.stderr.on("data",err=>{output+=err});let timeout=setTimeout(()=>(child.removeAllListeners(),child.kill(),reject(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);child.on("close",code=>{if(clearTimeout(timeout),code===0)try{let responseJson=JSON.parse(output),response=new executable_response_1.ExecutableResponse(responseJson);return resolve(response)}catch(error){return error instanceof executable_response_1.ExecutableResponseError?reject(error):reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`))}else return reject(new ExecutableError(output,code.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let filePath;try{filePath=await fs2.promises.realpath(this.outputFile)}catch{return}if(!(await fs2.promises.lstat(filePath)).isFile())return;let responseString=await fs2.promises.readFile(filePath,{encoding:"utf8"});if(responseString!=="")try{let responseJson=JSON.parse(responseString);return new executable_response_1.ExecutableResponse(responseJson).isValid()?new executable_response_1.ExecutableResponse(responseJson):void 0}catch(error){throw error instanceof executable_response_1.ExecutableResponseError?error:new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`)}}static parseCommand(command){let components=command.match(/(?:[^\s"]+|"[^"]*")+/g);if(!components)throw new Error(`Provided command: "${command}" could not be parsed.`);for(let i=0;i<components.length;i++)components[i][0]==='"'&&components[i].slice(-1)==='"'&&(components[i]=components[i].slice(1,-1));return components}};exports.PluggableAuthHandler=PluggableAuthHandler}});var require_pluggable_auth_client=__commonJS({"node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.PluggableAuthClient=exports.ExecutableError=void 0;var baseexternalclient_1=require_baseexternalclient(),executable_response_1=require_executable_response(),pluggable_auth_handler_1=require_pluggable_auth_handler(),pluggable_auth_handler_2=require_pluggable_auth_handler();Object.defineProperty(exports,"ExecutableError",{enumerable:!0,get:function(){return pluggable_auth_handler_2.ExecutableError}});var DEFAULT_EXECUTABLE_TIMEOUT_MILLIS=30*1e3,MINIMUM_EXECUTABLE_TIMEOUT_MILLIS=5*1e3,MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS=120*1e3,GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",MAXIMUM_EXECUTABLE_VERSION=1,PluggableAuthClient=class extends baseexternalclient_1.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(options){if(super(options),!options.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=options.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(options.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;else if(this.timeoutMillis=options.credential_source.executable.timeout_millis,this.timeoutMillis<MINIMUM_EXECUTABLE_TIMEOUT_MILLIS||this.timeoutMillis>MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS)throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);this.outputFile=options.credential_source.executable.output_file,this.handler=new pluggable_auth_handler_1.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let executableResponse;if(this.outputFile&&(executableResponse=await this.handler.retrieveCachedResponse()),!executableResponse){let envMap=new Map;envMap.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),envMap.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),envMap.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&envMap.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let serviceAccountEmail=this.getServiceAccountEmail();serviceAccountEmail&&envMap.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",serviceAccountEmail),executableResponse=await this.handler.retrieveResponseFromExecutable(envMap)}if(executableResponse.version>MAXIMUM_EXECUTABLE_VERSION)throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);if(!executableResponse.success)throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage,executableResponse.errorCode);if(this.outputFile&&!executableResponse.expirationTime)throw new executable_response_1.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(executableResponse.isExpired())throw new Error("Executable response is expired.");return executableResponse.subjectToken}};exports.PluggableAuthClient=PluggableAuthClient}});var require_externalclient=__commonJS({"node_modules/google-auth-library/build/src/auth/externalclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ExternalAccountClient=void 0;var baseexternalclient_1=require_baseexternalclient(),identitypoolclient_1=require_identitypoolclient(),awsclient_1=require_awsclient(),pluggable_auth_client_1=require_pluggable_auth_client(),ExternalAccountClient=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(options){return options&&options.type===baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?options.credential_source?.environment_id?new awsclient_1.AwsClient(options):options.credential_source?.executable?new pluggable_auth_client_1.PluggableAuthClient(options):new identitypoolclient_1.IdentityPoolClient(options):null}};exports.ExternalAccountClient=ExternalAccountClient}});var require_externalAccountAuthorizedUserClient=__commonJS({"node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ExternalAccountAuthorizedUserClient=exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var authclient_1=require_authclient(),oauth2common_1=require_oauth2common(),gaxios_1=require_src(),stream=__require("stream"),baseexternalclient_1=require_baseexternalclient();exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var DEFAULT_TOKEN_URL="https://sts.{universeDomain}/v1/oauthtoken",ExternalAccountAuthorizedUserHandler=class _ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler{#tokenRefreshEndpoint;constructor(options){super(options),this.#tokenRefreshEndpoint=options.tokenRefreshEndpoint}async refreshToken(refreshToken,headers){let opts={..._ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,url:this.#tokenRefreshEndpoint,method:"POST",headers,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken}),responseType:"json"};authclient_1.AuthClient.setMethodName(opts,"refreshToken"),this.applyClientAuthenticationOptions(opts);try{let response=await this.transporter.request(opts),tokenRefreshResponse=response.data;return tokenRefreshResponse.res=response,tokenRefreshResponse}catch(error){throw error instanceof gaxios_1.GaxiosError&&error.response?(0,oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data,error):error}}},ExternalAccountAuthorizedUserClient=class extends authclient_1.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(options){super(options),options.universe_domain&&(this.universeDomain=options.universe_domain),this.refreshToken=options.refresh_token;let clientAuthentication={confidentialClientType:"basic",clientId:options.client_id,clientSecret:options.client_secret};this.externalAccountAuthorizedUserHandler=new ExternalAccountAuthorizedUserHandler({tokenRefreshEndpoint:options.token_url??DEFAULT_TOKEN_URL.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication}),this.cachedAccessToken=null,this.quotaProjectId=options.quota_project_id,typeof options?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=baseexternalclient_1.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=options.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!options?.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 accessTokenResponse=await this.getAccessToken(),headers=new Headers({authorization:`Bearer ${accessTokenResponse.token}`});return this.addSharedMetadataHeaders(headers)}request(opts,callback){if(callback)this.requestAsync(opts).then(r=>callback(null,r),e=>callback(e,e.response));else return this.requestAsync(opts)}async requestAsync(opts,reAuthRetried=!1){let response;try{let requestHeaders=await this.getRequestHeaders();opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,requestHeaders),response=await this.transporter.request(opts)}catch(e){let res=e.response;if(res){let statusCode=res.status,isReadableStream=res.config.data instanceof stream.Readable;if(!reAuthRetried&&(statusCode===401||statusCode===403)&&!isReadableStream&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(opts,!0)}throw e}return response}async refreshAccessTokenAsync(){let refreshResponse=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:refreshResponse.access_token,expiry_date:new Date().getTime()+refreshResponse.expires_in*1e3,res:refreshResponse.res},refreshResponse.refresh_token!==void 0&&(this.refreshToken=refreshResponse.refresh_token),this.cachedAccessToken}isExpired(credentials){let now=new Date().getTime();return credentials.expiry_date?now>=credentials.expiry_date-this.eagerRefreshThresholdMillis:!1}};exports.ExternalAccountAuthorizedUserClient=ExternalAccountAuthorizedUserClient}});var require_googleauth=__commonJS({"node_modules/google-auth-library/build/src/auth/googleauth.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GoogleAuth=exports.GoogleAuthExceptionMessages=void 0;var child_process_1=__require("child_process"),fs2=__require("fs"),gaxios_1=require_src(),gcpMetadata=require_src3(),os=__require("os"),path2=__require("path"),crypto_1=require_crypto3(),computeclient_1=require_computeclient(),idtokenclient_1=require_idtokenclient(),envDetect_1=require_envDetect(),jwtclient_1=require_jwtclient(),refreshclient_1=require_refreshclient(),impersonated_1=require_impersonated(),externalclient_1=require_externalclient(),baseexternalclient_1=require_baseexternalclient(),authclient_1=require_authclient(),externalAccountAuthorizedUserClient_1=require_externalAccountAuthorizedUserClient(),util_1=require_util2();exports.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.
To learn more about authentication and Google APIs, visit:
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
To learn more about authentication and Google APIs, visit:
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
To learn more about Universe Domain retrieval, visit:
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var GoogleAuth2=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#pendingAuthClient=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(opts={}){if(this._cachedProjectId=opts.projectId||null,this.cachedCredential=opts.authClient||null,this.keyFilename=opts.keyFilename||opts.keyFile,this.scopes=opts.scopes,this.clientOptions=opts.clientOptions||{},this.jsonContent=opts.credentials||null,this.apiKey=opts.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);opts.universeDomain&&(this.clientOptions.universeDomain=opts.universeDomain)}setGapicJWTValues(client){client.defaultServicePath=this.defaultServicePath,client.useJWTAccessWithScope=this.useJWTAccessWithScope,client.defaultScopes=this.defaultScopes}getProjectId(callback){if(callback)this.getProjectIdAsync().then(r=>callback(null,r),callback);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let projectId=null;if(projectId||=await this.getProductionProjectId(),projectId||=await this.getFileProjectId(),projectId||=await this.getDefaultServiceProjectId(),projectId||=await this.getGCEProjectId(),projectId||=await this.getExternalAccountClientProjectId(),projectId)return this._cachedProjectId=projectId,projectId;throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let universeDomain;try{universeDomain=await gcpMetadata.universe("universe-domain"),universeDomain||=authclient_1.DEFAULT_UNIVERSE}catch(e){if(e&&e?.response?.status===404)universeDomain=authclient_1.DEFAULT_UNIVERSE;else throw e}return universeDomain}async getUniverseDomain(){let universeDomain=(0,util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{universeDomain??=(await this.getClient()).universeDomain}catch{universeDomain??=authclient_1.DEFAULT_UNIVERSE}return universeDomain}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(optionsOrCallback={},callback){let options;if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.getApplicationDefaultAsync(options).then(r=>callback(null,r.credential,r.projectId),callback);else return this.getApplicationDefaultAsync(options)}async getApplicationDefaultAsync(options={}){if(this.cachedCredential)return await this.#prepareAndCacheClient(this.cachedCredential,null);let credential;if(credential=await this._tryGetApplicationCredentialsFromEnvironmentVariable(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(credential=await this._tryGetApplicationCredentialsFromWellKnownFile(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(await this._checkIsGCE())return options.scopes=this.getAnyScopes(),await this.#prepareAndCacheClient(new computeclient_1.Compute(options));throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#prepareAndCacheClient(credential,quotaProjectIdOverride=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let projectId=await this.getProjectIdOptional();return quotaProjectIdOverride&&(credential.quotaProjectId=quotaProjectIdOverride),this.cachedCredential=credential,{credential,projectId}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=gcpMetadata.getGCPResidency()||await gcpMetadata.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(options){let credentialsPath=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!credentialsPath||credentialsPath.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(credentialsPath,options)}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(options){let location=null;if(this._isWindows())location=process.env.APPDATA;else{let home=process.env.HOME;home&&(location=path2.join(home,".config"))}return location&&(location=path2.join(location,"gcloud","application_default_credentials.json"),fs2.existsSync(location)||(location=null)),location?await this._getApplicationCredentialsFromFilePath(location,options):null}async _getApplicationCredentialsFromFilePath(filePath,options={}){if(!filePath||filePath.length===0)throw new Error("The file path is invalid.");try{if(filePath=fs2.realpathSync(filePath),!fs2.lstatSync(filePath).isFile())throw new Error}catch(err){throw err instanceof Error&&(err.message=`The file at ${filePath} does not exist, or it is not a file. ${err.message}`),err}let readStream=fs2.createReadStream(filePath);return this.fromStream(readStream,options)}fromImpersonatedJSON(json2){if(!json2)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(json2.type!==impersonated_1.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!json2.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!json2.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let sourceClient=this.fromJSON(json2.source_credentials);if(json2.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);let targetPrincipal=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)?.groups?.target;if(!targetPrincipal)throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);let targetScopes=(this.scopes||json2.scopes||this.defaultScopes)??[];return new impersonated_1.Impersonated({...json2,sourceClient,targetPrincipal,targetScopes:Array.isArray(targetScopes)?targetScopes:[targetScopes]})}fromJSON(json2,options={}){let client,preferredUniverseDomain=(0,util_1.originalOrCamelOptions)(options).get("universe_domain");return json2.type===refreshclient_1.USER_REFRESH_ACCOUNT_TYPE?(client=new refreshclient_1.UserRefreshClient(options),client.fromJSON(json2)):json2.type===impersonated_1.IMPERSONATED_ACCOUNT_TYPE?client=this.fromImpersonatedJSON(json2):json2.type===baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?(client=externalclient_1.ExternalAccountClient.fromJSON({...json2,...options}),client.scopes=this.getAnyScopes()):json2.type===externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?client=new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({...json2,...options}):(options.scopes=this.scopes,client=new jwtclient_1.JWT(options),this.setGapicJWTValues(client),client.fromJSON(json2)),preferredUniverseDomain&&(client.universeDomain=preferredUniverseDomain),client}_cacheClientFromJSON(json2,options){let client=this.fromJSON(json2,options);return this.jsonContent=json2,this.cachedCredential=client,client}fromStream(inputStream,optionsOrCallback={},callback){let options={};if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.fromStreamAsync(inputStream,options).then(r=>callback(null,r),callback);else return this.fromStreamAsync(inputStream,options)}fromStreamAsync(inputStream,options){return new Promise((resolve,reject)=>{if(!inputStream)throw new Error("Must pass in a stream containing the Google auth settings.");let chunks=[];inputStream.setEncoding("utf8").on("error",reject).on("data",chunk=>chunks.push(chunk)).on("end",()=>{try{try{let data=JSON.parse(chunks.join("")),r=this._cacheClientFromJSON(data,options);return resolve(r)}catch(err){if(!this.keyFilename)throw err;let client=new jwtclient_1.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=client,this.setGapicJWTValues(client),resolve(client)}}catch(err){return reject(err)}})})}fromAPIKey(apiKey,options={}){return new jwtclient_1.JWT({...options,apiKey})}_isWindows(){let sys=os.platform();return!!(sys&&sys.length>=3&&sys.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(resolve=>{(0,child_process_1.exec)("gcloud config config-helper --format json",(err,stdout)=>{if(!err&&stdout)try{let projectId=JSON.parse(stdout).configuration.properties.core.project;resolve(projectId);return}catch{}resolve(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 creds=await this.getClient();if(creds&&creds.projectId)return creds.projectId}let r=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return r?r.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await gcpMetadata.project("project-id")}catch{return null}}getCredentials(callback){if(callback)this.getCredentialsAsync().then(r=>callback(null,r),callback);else return this.getCredentialsAsync()}async getCredentialsAsync(){let client=await this.getClient();if(client instanceof impersonated_1.Impersonated)return{client_email:client.getTargetPrincipal()};if(client instanceof baseexternalclient_1.BaseExternalAccountClient){let serviceAccountEmail=client.getServiceAccountEmail();if(serviceAccountEmail)return{client_email:serviceAccountEmail,universe_domain:client.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[client_email,universe_domain]=await Promise.all([gcpMetadata.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email,universe_domain}}throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#pendingAuthClient=this.#pendingAuthClient||this.#determineClient();try{return await this.#pendingAuthClient}finally{this.#pendingAuthClient=null}}async#determineClient(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let filePath=path2.resolve(this.keyFilename),stream=fs2.createReadStream(filePath);return await this.fromStreamAsync(stream,this.clientOptions)}else if(this.apiKey){let client=await this.fromAPIKey(this.apiKey,this.clientOptions);client.scopes=this.scopes;let{credential}=await this.#prepareAndCacheClient(client);return credential}else{let{credential}=await this.getApplicationDefaultAsync(this.clientOptions);return credential}}async getIdTokenClient(targetAudience){let client=await this.getClient();if(!("fetchIdToken"in client))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new idtokenclient_1.IdTokenClient({targetAudience,idTokenProvider:client})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(url){return(await this.getClient()).getRequestHeaders(url)}async authorizeRequest(opts={}){let url=opts.url,headers=await(await this.getClient()).getRequestHeaders(url);return opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers,headers),opts}async fetch(...args){return(await this.getClient()).fetch(...args)}async request(opts){return(await this.getClient()).request(opts)}getEnv(){return(0,envDetect_1.getEnv)()}async sign(data,endpoint){let client=await this.getClient(),universe=await this.getUniverseDomain();if(endpoint=endpoint||`https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`,client instanceof impersonated_1.Impersonated)return(await client.sign(data)).signedBlob;let crypto2=(0,crypto_1.createCrypto)();if(client instanceof jwtclient_1.JWT&&client.key)return await crypto2.sign(client.key,data);let creds=await this.getCredentials();if(!creds.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(crypto2,creds.client_email,data,endpoint)}async signBlob(crypto2,emailOrUniqueId,data,endpoint){let url=new URL(endpoint+`${emailOrUniqueId}:signBlob`);return(await this.request({method:"POST",url:url.href,data:{payload:crypto2.encodeBase64StringUtf8(data)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};exports.GoogleAuth=GoogleAuth2}});var require_iam=__commonJS({"node_modules/google-auth-library/build/src/auth/iam.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.IAMAuth=void 0;var IAMAuth=class{selector;token;constructor(selector,token){this.selector=selector,this.token=token,this.selector=selector,this.token=token}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};exports.IAMAuth=IAMAuth}});var require_downscopedclient=__commonJS({"node_modules/google-auth-library/build/src/auth/downscopedclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.DownscopedClient=exports.EXPIRATION_TIME_OFFSET=exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var gaxios_1=require_src(),stream=__require("stream"),authclient_1=require_authclient(),sts=require_stscredentials(),STS_GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange",STS_REQUEST_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token",STS_SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token";exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;exports.EXPIRATION_TIME_OFFSET=300*1e3;var DownscopedClient=class extends authclient_1.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(options,credentialAccessBoundary={accessBoundary:{accessBoundaryRules:[]}}){if(super(options instanceof authclient_1.AuthClient?{}:options),options instanceof authclient_1.AuthClient?(this.authClient=options,this.credentialAccessBoundary=credentialAccessBoundary):(this.authClient=options.authClient,this.credentialAccessBoundary=options.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>exports.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let rule of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(rule.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new sts.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(credentials){if(!credentials.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(credentials),this.cachedDownscopedAccessToken=credentials}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 accessTokenResponse=await this.getAccessToken(),headers=new Headers({authorization:`Bearer ${accessTokenResponse.token}`});return this.addSharedMetadataHeaders(headers)}request(opts,callback){if(callback)this.requestAsync(opts).then(r=>callback(null,r),e=>callback(e,e.response));else return this.requestAsync(opts)}async requestAsync(opts,reAuthRetried=!1){let response;try{let requestHeaders=await this.getRequestHeaders();opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,requestHeaders),response=await this.transporter.request(opts)}catch(e){let res=e.response;if(res){let statusCode=res.status,isReadableStream=res.config.data instanceof stream.Readable;if(!reAuthRetried&&(statusCode===401||statusCode===403)&&!isReadableStream&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(opts,!0)}throw e}return response}async refreshAccessTokenAsync(){let subjectToken=(await this.authClient.getAccessToken()).token,stsCredentialsOptions={grantType:STS_GRANT_TYPE,requestedTokenType:STS_REQUEST_TOKEN_TYPE,subjectToken,subjectTokenType:STS_SUBJECT_TOKEN_TYPE},stsResponse=await this.stsCredential.exchangeToken(stsCredentialsOptions,void 0,this.credentialAccessBoundary),sourceCredExpireDate=this.authClient.credentials?.expiry_date||null,expiryDate=stsResponse.expires_in?new Date().getTime()+stsResponse.expires_in*1e3:sourceCredExpireDate;return this.cachedDownscopedAccessToken={access_token:stsResponse.access_token,expiry_date:expiryDate,res:stsResponse.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(downscopedAccessToken){let now=new Date().getTime();return downscopedAccessToken.expiry_date?now>=downscopedAccessToken.expiry_date-this.eagerRefreshThresholdMillis:!1}};exports.DownscopedClient=DownscopedClient}});var require_passthrough=__commonJS({"node_modules/google-auth-library/build/src/auth/passthrough.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.PassThroughClient=void 0;var authclient_1=require_authclient(),PassThroughClient=class extends authclient_1.AuthClient{async request(opts){return this.transporter.request(opts)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};exports.PassThroughClient=PassThroughClient}});var require_src4=__commonJS({"node_modules/google-auth-library/build/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.GoogleAuth=exports.auth=exports.PassThroughClient=exports.ExternalAccountAuthorizedUserClient=exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=exports.ExecutableError=exports.PluggableAuthClient=exports.DownscopedClient=exports.BaseExternalAccountClient=exports.ExternalAccountClient=exports.IdentityPoolClient=exports.AwsRequestSigner=exports.AwsClient=exports.UserRefreshClient=exports.LoginTicket=exports.ClientAuthentication=exports.OAuth2Client=exports.CodeChallengeMethod=exports.Impersonated=exports.JWT=exports.JWTAccess=exports.IdTokenClient=exports.IAMAuth=exports.GCPEnv=exports.Compute=exports.DEFAULT_UNIVERSE=exports.AuthClient=exports.gaxios=exports.gcpMetadata=void 0;var googleauth_1=require_googleauth();Object.defineProperty(exports,"GoogleAuth",{enumerable:!0,get:function(){return googleauth_1.GoogleAuth}});exports.gcpMetadata=require_src3();exports.gaxios=require_src();var authclient_1=require_authclient();Object.defineProperty(exports,"AuthClient",{enumerable:!0,get:function(){return authclient_1.AuthClient}});Object.defineProperty(exports,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return authclient_1.DEFAULT_UNIVERSE}});var computeclient_1=require_computeclient();Object.defineProperty(exports,"Compute",{enumerable:!0,get:function(){return computeclient_1.Compute}});var envDetect_1=require_envDetect();Object.defineProperty(exports,"GCPEnv",{enumerable:!0,get:function(){return envDetect_1.GCPEnv}});var iam_1=require_iam();Object.defineProperty(exports,"IAMAuth",{enumerable:!0,get:function(){return iam_1.IAMAuth}});var idtokenclient_1=require_idtokenclient();Object.defineProperty(exports,"IdTokenClient",{enumerable:!0,get:function(){return idtokenclient_1.IdTokenClient}});var jwtaccess_1=require_jwtaccess();Object.defineProperty(exports,"JWTAccess",{enumerable:!0,get:function(){return jwtaccess_1.JWTAccess}});var jwtclient_1=require_jwtclient();Object.defineProperty(exports,"JWT",{enumerable:!0,get:function(){return jwtclient_1.JWT}});var impersonated_1=require_impersonated();Object.defineProperty(exports,"Impersonated",{enumerable:!0,get:function(){return impersonated_1.Impersonated}});var oauth2client_1=require_oauth2client();Object.defineProperty(exports,"CodeChallengeMethod",{enumerable:!0,get:function(){return oauth2client_1.CodeChallengeMethod}});Object.defineProperty(exports,"OAuth2Client",{enumerable:!0,get:function(){return oauth2client_1.OAuth2Client}});Object.defineProperty(exports,"ClientAuthentication",{enumerable:!0,get:function(){return oauth2client_1.ClientAuthentication}});var loginticket_1=require_loginticket();Object.defineProperty(exports,"LoginTicket",{enumerable:!0,get:function(){return loginticket_1.LoginTicket}});var refreshclient_1=require_refreshclient();Object.defineProperty(exports,"UserRefreshClient",{enumerable:!0,get:function(){return refreshclient_1.UserRefreshClient}});var awsclient_1=require_awsclient();Object.defineProperty(exports,"AwsClient",{enumerable:!0,get:function(){return awsclient_1.AwsClient}});var awsrequestsigner_1=require_awsrequestsigner();Object.defineProperty(exports,"AwsRequestSigner",{enumerable:!0,get:function(){return awsrequestsigner_1.AwsRequestSigner}});var identitypoolclient_1=require_identitypoolclient();Object.defineProperty(exports,"IdentityPoolClient",{enumerable:!0,get:function(){return identitypoolclient_1.IdentityPoolClient}});var externalclient_1=require_externalclient();Object.defineProperty(exports,"ExternalAccountClient",{enumerable:!0,get:function(){return externalclient_1.ExternalAccountClient}});var baseexternalclient_1=require_baseexternalclient();Object.defineProperty(exports,"BaseExternalAccountClient",{enumerable:!0,get:function(){return baseexternalclient_1.BaseExternalAccountClient}});var downscopedclient_1=require_downscopedclient();Object.defineProperty(exports,"DownscopedClient",{enumerable:!0,get:function(){return downscopedclient_1.DownscopedClient}});var pluggable_auth_client_1=require_pluggable_auth_client();Object.defineProperty(exports,"PluggableAuthClient",{enumerable:!0,get:function(){return pluggable_auth_client_1.PluggableAuthClient}});Object.defineProperty(exports,"ExecutableError",{enumerable:!0,get:function(){return pluggable_auth_client_1.ExecutableError}});var externalAccountAuthorizedUserClient_1=require_externalAccountAuthorizedUserClient();Object.defineProperty(exports,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(exports,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient}});var passthrough_1=require_passthrough();Object.defineProperty(exports,"PassThroughClient",{enumerable:!0,get:function(){return passthrough_1.PassThroughClient}});__exportStar(require_googleToken(),exports);var auth=new googleauth_1.GoogleAuth;exports.auth=auth}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"],hasBlob=typeof Blob<"u";hasBlob&&BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants(),FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];let target=Buffer.allocUnsafe(totalLength),offset=0;for(let i=0;i<list.length;i++){let buf=list[i];target.set(buf,offset),offset+=buf.length}return offset<totalLength?new FastBuffer(target.buffer,target.byteOffset,offset):target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++)output[offset+i]=source[i]^mask[i&3]}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++)buffer[i]^=mask[i&3]}function toArrayBuffer(buf){return buf.length===buf.buffer.byteLength?buf.buffer:buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){if(toBuffer.readOnly=!0,Buffer.isBuffer(data))return data;let buf;return data instanceof ArrayBuffer?buf=new FastBuffer(data):ArrayBuffer.isView(data)?buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength):(buf=Buffer.from(data),toBuffer.readOnly=!1),buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL)try{let bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){length<48?_mask(source,mask,output,offset,length):bufferUtil.mask(source,mask,output,offset,length)},module.exports.unmask=function(buffer,mask){buffer.length<32?_unmask(buffer,mask):bufferUtil.unmask(buffer,mask)}}catch{}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone"),kRun=Symbol("kRun"),Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=concurrency||1/0,this.jobs=[],this.pending=0}add(job){this.jobs.push(job),this[kRun]()}[kRun](){if(this.pending!==this.concurrency&&this.jobs.length){let job=this.jobs.shift();this.pending++,job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib=__require("zlib"),bufferUtil=require_buffer_util(),Limiter=require_limiter(),{kStatusCode}=require_constants(),FastBuffer=Buffer[Symbol.species],TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error"),zlibLimiter,PerMessageDeflate2=class{constructor(options){if(this._options=options||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){let concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){let params={};return this._options.serverNoContextTakeover&&(params.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(params.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(params.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?params.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(params.client_max_window_bits=!0),params}accept(configurations){return configurations=this.normalizeParams(configurations),this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let callback=this._deflate[kCallback];this._deflate.close(),this._deflate=null,callback&&callback(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(offers){let opts=this._options,accepted=offers.find(params=>!(opts.serverNoContextTakeover===!1&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===!1||typeof opts.serverMaxWindowBits=="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits=="number"&&!params.client_max_window_bits));if(!accepted)throw new Error("None of the extension offers can be accepted");return opts.serverNoContextTakeover&&(accepted.server_no_context_takeover=!0),opts.clientNoContextTakeover&&(accepted.client_no_context_takeover=!0),typeof opts.serverMaxWindowBits=="number"&&(accepted.server_max_window_bits=opts.serverMaxWindowBits),typeof opts.clientMaxWindowBits=="number"?accepted.client_max_window_bits=opts.clientMaxWindowBits:(accepted.client_max_window_bits===!0||opts.clientMaxWindowBits===!1)&&delete accepted.client_max_window_bits,accepted}acceptAsClient(response){let params=response[0];if(this._options.clientNoContextTakeover===!1&¶ms.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!params.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(params.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return params}normalizeParams(configurations){return configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1)throw new Error(`Parameter "${key}" must have only a single value`);if(value=value[0],key==="client_max_window_bits"){if(value!==!0){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else if(key==="server_max_window_bits"){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==!0)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else throw new Error(`Unknown parameter "${key}"`);params[key]=value})}),configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done(),callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done(),callback(err,result)})})}_decompress(data,fin,callback){let endpoint=this._isServer?"client":"server";if(!this._inflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback,this._inflate.write(data),fin&&this._inflate.write(TRAILER),this._inflate.flush(()=>{let err=this._inflate[kError];if(err){this._inflate.close(),this._inflate=null,callback(err);return}let data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._inflate.reset()),callback(null,data2)})}_compress(data,fin,callback){let endpoint=this._isServer?"server":"client";if(!this._deflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback,this._deflate.write(data),this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);fin&&(data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)),this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._deflate.reset(),callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk),this[kTotalLength]+=chunk.length}function inflateOnData(chunk){if(this[kTotalLength]+=chunk.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded"),this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset()}function inflateOnError(err){if(this[kPerMessageDeflate]._inflate=null,this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007,this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer"),{hasBlob}=require_constants(),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];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){let len=buf.length,i=0;for(;i<len;)if((buf[i]&128)===0)i++;else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192)return!1;i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160)return!1;i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244)return!1;i+=4}else return!1;return!0}function isBlob(value){return hasBlob&&typeof value=="object"&&typeof value.arrayBuffer=="function"&&typeof value.type=="string"&&typeof value.stream=="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8)module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch{}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream"),PerMessageDeflate2=require_permessage_deflate(),{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants(),{concat,toArrayBuffer,unmask}=require_buffer_util(),{isValidStatusCode,isValidUTF8}=require_validation(),FastBuffer=Buffer[Symbol.species],GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5,DEFER_EVENT=6,Receiver2=class extends Writable{constructor(options={}){super(),this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:!0,this._binaryType=options.binaryType||BINARY_TYPES[0],this._extensions=options.extensions||{},this._isServer=!!options.isServer,this._maxBufferedChunks=options.maxBufferedChunks|0,this._maxFragments=options.maxFragments|0,this._maxPayload=options.maxPayload|0,this._skipUTF8Validation=!!options.skipUTF8Validation,this[kWebSocket]=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=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length,this._buffers.push(chunk),this.startLoop(cb)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let buf=this._buffers[0];return this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n),new FastBuffer(buf.buffer,buf.byteOffset,n)}let dst=Buffer.allocUnsafe(n);do{let buf=this._buffers[0],offset=dst.length-n;n>=buf.length?dst.set(this._buffers.shift(),offset):(dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset),this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)),n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=!0;do switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=!1;return}while(this._loop);this._errored||cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=!1;return}let buf=this.consume(2);if((buf[0]&48)!==0){let error=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}let compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._fin=(buf[0]&128)===128,this._opcode=buf[0]&15,this._payloadLength=buf[1]&127,this._opcode===0){if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){let error=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let error=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(buf[1]&128)===128,this._isServer){if(!this._masked){let error=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){let error=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}this._payloadLength===126?this._state=GET_PAYLOAD_LENGTH_16:this._payloadLength===127?this._state=GET_PAYLOAD_LENGTH_64:this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=!1;return}let buf=this.consume(8),num=buf.readUInt32BE(0);if(num>Math.pow(2,21)-1){let error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4),this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._masked?this._state=GET_MASK:this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}data=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&unmask(data,this._mask)}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING,this.decompress(data,cb);return}if(data.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._messageLength=this._totalPayloadLength,this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){this._extensions[PerMessageDeflate2.extensionName].decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){if(this._messageLength+=buf.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb),this._state===GET_INFO&&this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}let messageLength=this._messageLength,fragments=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let data;this._binaryType==="nodebuffer"?data=concat(fragments,messageLength):this._binaryType==="arraybuffer"?data=toArrayBuffer(concat(fragments,messageLength)):this._binaryType==="blob"?data=new Blob(fragments):data=fragments,this._allowSynchronousEvents?(this.emit("message",data,!0),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",data,!0),this._state=GET_INFO,this.startLoop(cb)}))}else{let buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._state===INFLATING||this._allowSynchronousEvents?(this.emit("message",buf,!1),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",buf,!1),this._state=GET_INFO,this.startLoop(cb)}))}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0)this._loop=!1,this.emit("conclude",1005,EMPTY_BUFFER),this.end();else{let code=data.readUInt16BE(0);if(!isValidStatusCode(code)){let error=this.createError(RangeError,`invalid status code ${code}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}let buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=!1,this.emit("conclude",code,buf),this.end()}this._state=GET_INFO;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO,this.startLoop(cb)}))}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=!1,this._errored=!0;let err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);return Error.captureStackTrace(err,this.createError),err.code=errorCode,err[kStatusCode]=statusCode,err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream"),{randomFillSync}=__require("crypto"),{types:{isUint8Array}}=__require("util"),PerMessageDeflate2=require_permessage_deflate(),{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants(),{isBlob,isValidStatusCode}=require_validation(),{mask:applyMask,toBuffer}=require_buffer_util(),kByteLength=Symbol("kByteLength"),maskBuffer=Buffer.alloc(4),RANDOM_POOL_SIZE=8*1024,randomPool,randomPoolPointer=RANDOM_POOL_SIZE,DEFAULT=0,DEFLATING=1,GET_BLOB_DATA=2,Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{},generateMask&&(this._generateMask=generateMask,this._maskBuffer=Buffer.alloc(4)),this._socket=socket,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=DEFAULT,this.onerror=NOOP,this[kWebSocket]=void 0}static frame(data,options){let mask,merge=!1,offset=2,skipMasking=!1;options.mask&&(mask=options.maskBuffer||maskBuffer,options.generateMask?options.generateMask(mask):(randomPoolPointer===RANDOM_POOL_SIZE&&(randomPool===void 0&&(randomPool=Buffer.alloc(RANDOM_POOL_SIZE)),randomFillSync(randomPool,0,RANDOM_POOL_SIZE),randomPoolPointer=0),mask[0]=randomPool[randomPoolPointer++],mask[1]=randomPool[randomPoolPointer++],mask[2]=randomPool[randomPoolPointer++],mask[3]=randomPool[randomPoolPointer++]),skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0,offset=6);let dataLength;typeof data=="string"?(!options.mask||skipMasking)&&options[kByteLength]!==void 0?dataLength=options[kByteLength]:(data=Buffer.from(data),dataLength=data.length):(dataLength=data.length,merge=options.mask&&options.readOnly&&!skipMasking);let payloadLength=dataLength;dataLength>=65536?(offset+=8,payloadLength=127):dataLength>125&&(offset+=2,payloadLength=126);let target=Buffer.allocUnsafe(merge?dataLength+offset:offset);return target[0]=options.fin?options.opcode|128:options.opcode,options.rsv1&&(target[0]|=64),target[1]=payloadLength,payloadLength===126?target.writeUInt16BE(dataLength,2):payloadLength===127&&(target[2]=target[3]=0,target.writeUIntBE(dataLength,4,6)),options.mask?(target[1]|=128,target[offset-4]=mask[0],target[offset-3]=mask[1],target[offset-2]=mask[2],target[offset-1]=mask[3],skipMasking?[target,data]:merge?(applyMask(data,mask,target,offset,dataLength),[target]):(applyMask(data,mask,data,0,dataLength),[target,data])):[target,data]}close(code,data,mask,cb){let buf;if(code===void 0)buf=EMPTY_BUFFER;else{if(typeof code!="number"||!isValidStatusCode(code))throw new TypeError("First argument must be a valid error code number");if(data===void 0||!data.length)buf=Buffer.allocUnsafe(2),buf.writeUInt16BE(code,0);else{let length=Buffer.byteLength(data);if(length>123)throw new RangeError("The message must not be greater than 123 bytes");if(buf=Buffer.allocUnsafe(2+length),buf.writeUInt16BE(code,0),typeof data=="string")buf.write(data,2);else if(isUint8Array(data))buf.set(data,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let options={[kByteLength]:buf.length,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==DEFAULT?this.enqueue([this.dispatch,buf,!1,options,cb]):this.sendFrame(_Sender.frame(buf,options),cb)}ping(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:!1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}pong(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:!1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}send(data,options,cb){let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName],opcode=options.binary?2:1,rsv1=options.compress,byteLength,readOnly;typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),this._firstFragment?(this._firstFragment=!1,rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(rsv1=byteLength>=perMessageDeflate._threshold),this._compress=rsv1):(rsv1=!1,opcode=0),options.fin&&(this._firstFragment=!0);let opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,this._compress,opts,cb]):this.getBlobData(data,this._compress,opts,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,this._compress,opts,cb]):this.dispatch(data,this._compress,opts,cb)}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength],this._state=GET_BLOB_DATA,blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){let err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];let data=toBuffer(arrayBuffer);compress?this.dispatch(data,compress,options,cb):(this._state=DEFAULT,this.sendFrame(_Sender.frame(data,options),cb),this.dequeue())}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength],this._state=DEFLATING,perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){let err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength],this._state=DEFAULT,options.readOnly=!1,this.sendFrame(_Sender.frame(buf,options),cb),this.dequeue()})}dequeue(){for(;this._state===DEFAULT&&this._queue.length;){let params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength],Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength],this._queue.push(params)}sendFrame(list,cb){list.length===2?(this._socket.cork(),this._socket.write(list[0]),this._socket.write(list[1],cb),this._socket.uncork()):this._socket.write(list[0],cb)}};module.exports=Sender2;function callCallbacks(sender,err,cb){typeof cb=="function"&&cb(err);for(let i=0;i<sender._queue.length;i++){let params=sender._queue[i],callback=params[params.length-1];typeof callback=="function"&&callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb),sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants(),kCode=Symbol("kCode"),kData=Symbol("kData"),kError=Symbol("kError"),kMessage=Symbol("kMessage"),kReason=Symbol("kReason"),kTarget=Symbol("kTarget"),kType=Symbol("kType"),kWasClean=Symbol("kWasClean"),Event=class{constructor(type){this[kTarget]=null,this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:!0});Object.defineProperty(Event.prototype,"type",{enumerable:!0});var CloseEvent=class extends Event{constructor(type,options={}){super(type),this[kCode]=options.code===void 0?0:options.code,this[kReason]=options.reason===void 0?"":options.reason,this[kWasClean]=options.wasClean===void 0?!1:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});var ErrorEvent=class extends Event{constructor(type,options={}){super(type),this[kError]=options.error===void 0?null:options.error,this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});var MessageEvent=class extends Event{constructor(type,options={}){super(type),this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});var EventTarget={addEventListener(type,handler,options={}){for(let listener of this.listeners(type))if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute])return;let wrapper;if(type==="message")wrapper=function(data,isBinary){let event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this,callListener(handler,this,event)};else if(type==="close")wrapper=function(code,message){let event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this,callListener(handler,this,event)};else if(type==="error")wrapper=function(error){let event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this,callListener(handler,this,event)};else if(type==="open")wrapper=function(){let event=new Event("open");event[kTarget]=this,callListener(handler,this,event)};else return;wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute],wrapper[kListener]=handler,options.once?this.once(type,wrapper):this.on(type,wrapper)},removeEventListener(type,handler){for(let listener of this.listeners(type))if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){typeof listener=="object"&&listener.handleEvent?listener.handleEvent.call(listener,event):listener.call(thisArg,event)}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){dest[name]===void 0?dest[name]=[elem]:dest[name].push(elem)}function parse(header){let offers=Object.create(null),params=Object.create(null),mustUnescape=!1,isEscaping=!1,inQuotes=!1,extensionName,paramName,start=-1,code=-1,end=-1,i=0;for(;i<header.length;i++)if(code=header.charCodeAt(i),extensionName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let name=header.slice(start,end);code===44?(push(offers,name,params),params=Object.create(null)):extensionName=name,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`);else if(paramName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(code===32||code===9)end===-1&&start!==-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i),push(params,header.slice(start,end),!0),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),start=end=-1}else if(code===61&&start!==-1&&end===-1)paramName=header.slice(start,i),start=end=-1;else throw new SyntaxError(`Unexpected character at index ${i}`);else if(isEscaping){if(tokenChars[code]!==1)throw new SyntaxError(`Unexpected character at index ${i}`);start===-1?start=i:mustUnescape||(mustUnescape=!0),isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1)start===-1&&(start=i);else if(code===34&&start!==-1)inQuotes=!1,end=i;else if(code===92)isEscaping=!0;else throw new SyntaxError(`Unexpected character at index ${i}`);else if(code===34&&header.charCodeAt(i-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(start!==-1&&(code===32||code===9))end===-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let value=header.slice(start,end);mustUnescape&&(value=value.replace(/\\/g,""),mustUnescape=!1),push(params,paramName,value),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),paramName=void 0,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`);if(start===-1||inQuotes||code===32||code===9)throw new SyntaxError("Unexpected end of input");end===-1&&(end=i);let token=header.slice(start,end);return extensionName===void 0?push(offers,token,params):(paramName===void 0?push(params,token,!0):mustUnescape?push(params,paramName,token.replace(/\\/g,"")):push(params,paramName,token),push(offers,extensionName,params)),offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params=>[extension2].concat(Object.keys(params).map(k=>{let values=params[k];return Array.isArray(values)||(values=[values]),values.map(v=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events"),https=__require("https"),http=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash}=__require("crypto"),{Duplex,Readable:Readable2}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),{isBlob}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super(),this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?protocols=[]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=protocols,protocols=[]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}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(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=_WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol==="https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https.request:http.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.captureStackTrace(err,abortHandshake),stream.setHeader?(stream[kAborted]=!0,stream.abort(),stream.socket&&!stream.socket.destroyed&&stream.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream.destroy(err),stream.once("error",websocket.emit.bind(websocket,"error")),stream.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&(websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;duplex.push(data)||ws.pause()}),ws.once("error",function(err){duplex.destroyed||(terminateOnDestroy=!1,duplex.destroy(err))}),ws.once("close",function(){duplex.destroyed||duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(emitClose,duplex);return}let called=!1;ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){called||callback(err),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}ws._socket!==null&&(ws._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.destroy()):(ws._socket.once("finish",function(){callback()}),ws.close()))},duplex._read=function(){ws.isPaused&&ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i=0;for(i;i<header.length;i++){let code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let protocol2=header.slice(start,end);if(protocols.has(protocol2))throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1||end!==-1)throw new SyntaxError("Unexpected end of input");let protocol=header.slice(start,i);if(protocols.has(protocol))throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),protocols}module.exports={parse}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter=__require("events"),http=__require("http"),{Duplex}=__require("stream"),{createHash}=__require("crypto"),extension2=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket2=require_websocket(),{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants(),keyRegex=/^[+/0-9A-Za-z]{22}==$/,RUNNING=0,CLOSING=1,CLOSED=2,WebSocketServer2=class extends EventEmitter{constructor(options,callback){if(super(),options={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket2,...options},options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options.port!=null?(this._server=http.createServer((req,res)=>{let body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback)):options.server&&(this._server=options.server),this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}options.perMessageDeflate===!0&&(options.perMessageDeflate={}),options.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(cb){if(this._state===CLOSED){cb&&this.once("close",()=>{cb(new Error("The server is not running"))}),process.nextTick(emitClose,this);return}if(cb&&this.once("close",cb),this._state!==CLOSING)if(this._state=CLOSING,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(emitClose,this):process.nextTick(emitClose,this);else{let server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){let index=req.url.indexOf("?");if((index!==-1?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);let key=req.headers["sec-websocket-key"],upgrade=req.headers.upgrade,version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){abortHandshakeOrEmitwsClientError(this,req,socket,405,"Invalid HTTP method");return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Upgrade header");return}if(key===void 0||!keyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Key header");return}if(version!==13&&version!==8){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}let secWebSocketProtocol=req.headers["sec-websocket-protocol"],protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Sec-WebSocket-Protocol header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension2.parse(secWebSocketExtensions);offers[PerMessageDeflate2.extensionName]&&(perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]),extensions[PerMessageDeflate2.extensionName]=perMessageDeflate)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(socket,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>RUNNING)return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash("sha1").update(key+GUID).digest("base64")}`],ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws._protocol=protocol)}if(extensions[PerMessageDeflate2.extensionName]){let params=extensions[PerMessageDeflate2.extensionName].params,value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`),ws._extensions=extensions}this.emit("headers",headers,req),socket.write(headers.concat(`\r
`).join(`\r
`)),socket.removeListener("error",socketOnError),ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(ws),ws.on("close",()=>{this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size&&process.nextTick(emitClose,this)})),cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map){for(let event of Object.keys(map))server.on(event,map[event]);return function(){for(let event of Object.keys(map))server.removeListener(event,map[event])}}function emitClose(server){server._state=CLOSED,server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code],headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers},socket.once("finish",socket.destroy),socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join(`\r
`)+`\r
\r
`+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){let err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message,headers)}}});var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src4(),1);import{createWriteStream}from"fs";import*as fs from"fs/promises";import{writeFile}from"fs/promises";import{Readable}from"node:stream";import{finished}from"node:stream/promises";var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);import*as path from"path";var _defaultBaseGeminiUrl,_defaultBaseVertexUrl;function getDefaultBaseUrls(){return{geminiUrl:_defaultBaseGeminiUrl,vertexUrl:_defaultBaseVertexUrl}}function getBaseUrl(httpOptions,vertexai,vertexBaseUrlFromEnv,geminiBaseUrlFromEnv){var _a2,_b;if(!httpOptions?.baseUrl){let defaultBaseUrls=getDefaultBaseUrls();return vertexai?(_a2=defaultBaseUrls.vertexUrl)!==null&&_a2!==void 0?_a2:vertexBaseUrlFromEnv:(_b=defaultBaseUrls.geminiUrl)!==null&&_b!==void 0?_b:geminiBaseUrlFromEnv}return httpOptions.baseUrl}var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match2,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i=0;i<keys.length-1;i++){let key=keys[i];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i=0;i<keys.length;i++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function moveValueByPath(data,paths){for(let[sourcePath,destPath]of Object.entries(paths)){let sourceKeys=sourcePath.split("."),destKeys=destPath.split("."),excludeKeys=new Set,wildcardIdx=-1;for(let i=0;i<sourceKeys.length;i++)if(sourceKeys[i]==="*"){wildcardIdx=i;break}if(wildcardIdx!==-1&&destKeys.length>wildcardIdx)for(let i=wildcardIdx;i<destKeys.length;i++){let key=destKeys[i];key!=="*"&&!key.endsWith("[]")&&!key.endsWith("[0]")&&excludeKeys.add(key)}_moveValueRecursive(data,sourceKeys,destKeys,0,excludeKeys)}}function _moveValueRecursive(data,sourceKeys,destKeys,keyIdx,excludeKeys){if(keyIdx>=sourceKeys.length||typeof data!="object"||data===null)return;let key=sourceKeys[keyIdx];if(key.endsWith("[]")){let keyName=key.slice(0,-2),dataRecord=data;if(keyName in dataRecord&&Array.isArray(dataRecord[keyName]))for(let item of dataRecord[keyName])_moveValueRecursive(item,sourceKeys,destKeys,keyIdx+1,excludeKeys)}else if(key==="*"){if(typeof data=="object"&&data!==null&&!Array.isArray(data)){let dataRecord=data,keysToMove=Object.keys(dataRecord).filter(k=>!k.startsWith("_")&&!excludeKeys.has(k)),valuesToMove={};for(let k of keysToMove)valuesToMove[k]=dataRecord[k];for(let[k,v]of Object.entries(valuesToMove)){let newDestKeys=[];for(let dk of destKeys.slice(keyIdx))dk==="*"?newDestKeys.push(k):newDestKeys.push(dk);setValueByPath(dataRecord,newDestKeys,v)}for(let k of keysToMove)delete dataRecord[k]}}else{let dataRecord=data;key in dataRecord&&_moveValueRecursive(dataRecord[key],sourceKeys,destKeys,keyIdx+1,excludeKeys)}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function fetchPredictOperationParametersToVertex(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);fromOperationName!=null&&setValueByPath(toObject,["operationName"],fromOperationName);let fromResourceName=getValueByPath(fromObject,["resourceName"]);return fromResourceName!=null&&setValueByPath(toObject,["_url","resourceName"],fromResourceName),toObject}function generateVideosOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function getOperationParametersToMldev(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);return fromOperationName!=null&&setValueByPath(toObject,["_url","operationName"],fromOperationName),toObject}function getOperationParametersToVertex(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);return fromOperationName!=null&&setValueByPath(toObject,["_url","operationName"],fromOperationName),toObject}function importFileOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],importFileResponseFromMldev$1(fromResponse)),toObject}function importFileResponseFromMldev$1(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function uploadToFileSearchStoreOperationFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],uploadToFileSearchStoreResponseFromMldev(fromResponse)),toObject}function uploadToFileSearchStoreResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){Outcome2.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Outcome2.OUTCOME_OK="OUTCOME_OK",Outcome2.OUTCOME_FAILED="OUTCOME_FAILED",Outcome2.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Outcome||(Outcome={}));var Language;(function(Language2){Language2.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Language2.PYTHON="PYTHON"})(Language||(Language={}));var FunctionResponseScheduling;(function(FunctionResponseScheduling2){FunctionResponseScheduling2.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",FunctionResponseScheduling2.SILENT="SILENT",FunctionResponseScheduling2.WHEN_IDLE="WHEN_IDLE",FunctionResponseScheduling2.INTERRUPT="INTERRUPT"})(FunctionResponseScheduling||(FunctionResponseScheduling={}));var Type;(function(Type2){Type2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",Type2.STRING="STRING",Type2.NUMBER="NUMBER",Type2.INTEGER="INTEGER",Type2.BOOLEAN="BOOLEAN",Type2.ARRAY="ARRAY",Type2.OBJECT="OBJECT",Type2.NULL="NULL"})(Type||(Type={}));var AuthType;(function(AuthType2){AuthType2.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",AuthType2.NO_AUTH="NO_AUTH",AuthType2.API_KEY_AUTH="API_KEY_AUTH",AuthType2.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",AuthType2.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",AuthType2.OAUTH="OAUTH",AuthType2.OIDC_AUTH="OIDC_AUTH"})(AuthType||(AuthType={}));var HttpElementLocation;(function(HttpElementLocation2){HttpElementLocation2.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",HttpElementLocation2.HTTP_IN_QUERY="HTTP_IN_QUERY",HttpElementLocation2.HTTP_IN_HEADER="HTTP_IN_HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var Environment;(function(Environment2){Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",PhishBlockThreshold2.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(PhishBlockThreshold||(PhishBlockThreshold={}));var Behavior;(function(Behavior2){Behavior2.UNSPECIFIED="UNSPECIFIED",Behavior2.BLOCKING="BLOCKING",Behavior2.NON_BLOCKING="NON_BLOCKING"})(Behavior||(Behavior={}));var DynamicRetrievalConfigMode;(function(DynamicRetrievalConfigMode2){DynamicRetrievalConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",DynamicRetrievalConfigMode2.MODE_DYNAMIC="MODE_DYNAMIC"})(DynamicRetrievalConfigMode||(DynamicRetrievalConfigMode={}));var ThinkingLevel;(function(ThinkingLevel2){ThinkingLevel2.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",ThinkingLevel2.MINIMAL="MINIMAL",ThinkingLevel2.LOW="LOW",ThinkingLevel2.MEDIUM="MEDIUM",ThinkingLevel2.HIGH="HIGH"})(ThinkingLevel||(ThinkingLevel={}));var PersonGeneration;(function(PersonGeneration2){PersonGeneration2.DONT_ALLOW="DONT_ALLOW",PersonGeneration2.ALLOW_ADULT="ALLOW_ADULT",PersonGeneration2.ALLOW_ALL="ALLOW_ALL"})(PersonGeneration||(PersonGeneration={}));var ProminentPeople;(function(ProminentPeople2){ProminentPeople2.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",ProminentPeople2.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",ProminentPeople2.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",TurnCoverage2.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",TurnCoverage2.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(TurnCoverage||(TurnCoverage={}));var AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));var Scale;(function(Scale2){Scale2.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",Scale2.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",Scale2.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",Scale2.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",Scale2.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",Scale2.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",Scale2.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",Scale2.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",Scale2.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",Scale2.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",Scale2.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",Scale2.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",Scale2.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Scale||(Scale={}));var MusicGenerationMode;(function(MusicGenerationMode2){MusicGenerationMode2.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",MusicGenerationMode2.QUALITY="QUALITY",MusicGenerationMode2.DIVERSITY="DIVERSITY",MusicGenerationMode2.VOCALIZATION="VOCALIZATION"})(MusicGenerationMode||(MusicGenerationMode={}));var LiveMusicPlaybackControl;(function(LiveMusicPlaybackControl2){LiveMusicPlaybackControl2.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",LiveMusicPlaybackControl2.PLAY="PLAY",LiveMusicPlaybackControl2.PAUSE="PAUSE",LiveMusicPlaybackControl2.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var HttpResponse=class{constructor(response){let headers={};for(let pair of response.headers.entries())headers[pair[0]]=pair[1];this.headers=headers,this.responseInternal=response}json(){return this.responseInternal.json()}};var GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.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 text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.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 data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.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 functionCalls=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.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 executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.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 codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};var ListTuningJobsResponse=class{},CancelTuningJobResponse=class{},ValidateRewardResponse=class{},DeleteCachedContentResponse=class{},ListCachedContentsResponse=class{},ListDocumentsResponse=class{},ListFileSearchStoresResponse=class{},UploadToFileSearchStoreResumableResponse=class{};var ImportFileOperation=class _ImportFileOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _ImportFileOperation,response=importFileOperationFromMldev$1(apiResponse);return Object.assign(operation,response),operation}},ListFilesResponse=class{},CreateFileResponse=class{},DeleteFileResponse=class{},RegisterFilesResponse=class{};var ListBatchJobsResponse=class{};var LiveServerMessage=class{get text(){var _a2,_b,_c;let text="",anyTextPartFound=!1,nonTextParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldValue!==null&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartFound=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartFound?text:void 0}get data(){var _a2,_b,_c;let data="",nonDataParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&fieldValue!==null&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}};var LiveMusicServerMessage=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var UploadToFileSearchStoreOperation=class _UploadToFileSearchStoreOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _UploadToFileSearchStoreOperation,response=uploadToFileSearchStoreOperationFromMldev(apiResponse);return Object.assign(operation,response),operation}};function tModel(apiClient,model){if(!model||typeof model!="string")throw new Error("model is required and must be a string");if(model.includes("..")||model.includes("?")||model.includes("&"))throw new Error("invalid model parameter");if(apiClient.isVertexAI()){if(model.startsWith("publishers/")||model.startsWith("projects/")||model.startsWith("models/"))return model;if(model.indexOf("/")>=0){let parts=model.split("/",2);return`publishers/${parts[0]}/models/${parts[1]}`}else return`publishers/google/models/${model}`}else return model.startsWith("models/")||model.startsWith("tunedModels/")?model:`models/${model}`}function tCachesModel(apiClient,model){let transformedModel=tModel(apiClient,model);return transformedModel?transformedModel.startsWith("publishers/")&&apiClient.isVertexAI()?`projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`:transformedModel.startsWith("models/")&&apiClient.isVertexAI()?`projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`:transformedModel:""}function tBlobs(blobs){return Array.isArray(blobs)?blobs.map(blob=>tBlob(blob)):[tBlob(blobs)]}function tBlob(blob){if(typeof blob=="object"&&blob!==null)return blob;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`)}function tImageBlob(blob){let transformedBlob=tBlob(blob);if(transformedBlob.mimeType&&transformedBlob.mimeType.startsWith("image/"))return transformedBlob;throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`)}function tAudioBlob(blob){let transformedBlob=tBlob(blob);if(transformedBlob.mimeType&&transformedBlob.mimeType.startsWith("audio/"))return transformedBlob;throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`)}function tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i.toUpperCase())?i.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tLiveSpeechConfig(speechConfig){if("multiSpeakerVoiceConfig"in speechConfig)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return speechConfig}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tTuningJobStatus(status){switch(status){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 status}}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function _isFile(origin){return origin!=null&&typeof origin=="object"&&"name"in origin}function isGeneratedVideo(origin){return origin!=null&&typeof origin=="object"&&"video"in origin}function isVideo(origin){return origin!=null&&typeof origin=="object"&&"uri"in origin}function tFileName(fromName){var _a2;let name;if(_isFile(fromName)&&(name=fromName.name),!(isVideo(fromName)&&(name=fromName.uri,name===void 0))&&!(isGeneratedVideo(fromName)&&(name=(_a2=fromName.video)===null||_a2===void 0?void 0:_a2.uri,name===void 0))){if(typeof fromName=="string"&&(name=fromName),name===void 0)throw new Error("Could not extract file name from the provided input.");if(name.startsWith("https://")){let match2=name.split("files/")[1].match(/[a-z0-9]+/);if(match2===null)throw new Error(`Could not extract file name from URI ${name}`);name=match2[0]}else name.startsWith("files/")&&(name=name.split("files/")[1]);return name}}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tBatchJobSource(client,src){let sourceObj;if(typeof src=="string")if(client.isVertexAI())if(src.startsWith("gs://"))sourceObj={format:"jsonl",gcsUri:[src]};else if(src.startsWith("bq://"))sourceObj={format:"bigquery",bigqueryUri:src};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(src))sourceObj={format:"vertex-dataset",vertexDatasetName:src};else throw new Error(`Unsupported string source for Vertex AI: ${src}`);else if(src.startsWith("files/"))sourceObj={fileName:src};else throw new Error(`Unsupported string source for Gemini API: ${src}`);else if(Array.isArray(src)){if(client.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");sourceObj={inlinedRequests:src}}else sourceObj=src;let vertexSourcesCount=[sourceObj.gcsUri,sourceObj.bigqueryUri,sourceObj.vertexDatasetName].filter(Boolean).length,mldevSourcesCount=[sourceObj.inlinedRequests,sourceObj.fileName].filter(Boolean).length;if(client.isVertexAI()){if(mldevSourcesCount>0||vertexSourcesCount!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(vertexSourcesCount>0||mldevSourcesCount!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return sourceObj}function tBatchJobDestination(dest){if(typeof dest!="string")return dest;let destString=dest;if(destString.startsWith("gs://"))return{format:"jsonl",gcsUri:destString};if(destString.startsWith("bq://"))return{format:"bigquery",bigqueryUri:destString};throw new Error(`Unsupported destination: ${destString}`)}function tRecvBatchJobDestination(dest){if(typeof dest!="object"||dest===null)return{};let obj=dest,inlineResponsesVal=obj.inlinedResponses;if(typeof inlineResponsesVal!="object"||inlineResponsesVal===null)return dest;let responsesArray=inlineResponsesVal.inlinedResponses;if(!Array.isArray(responsesArray)||responsesArray.length===0)return dest;let hasEmbedding=!1;for(let responseItem of responsesArray){if(typeof responseItem!="object"||responseItem===null)continue;let responseVal=responseItem.response;if(typeof responseVal!="object"||responseVal===null)continue;if(responseVal.embedding!==void 0){hasEmbedding=!0;break}}return hasEmbedding&&(obj.inlinedEmbedContentResponses=obj.inlinedResponses,delete obj.inlinedResponses),dest}function tBatchJobName(apiClient,name){let nameString=name;if(!apiClient.isVertexAI()){if(/batches\/[^/]+$/.test(nameString))return nameString.split("/").pop();throw new Error(`Invalid batch job name: ${nameString}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(nameString))return nameString.split("/").pop();if(/^\d+$/.test(nameString))return nameString;throw new Error(`Invalid batch job name: ${nameString}.`)}function tJobState(state){let stateString=state;return stateString==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":stateString==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":stateString==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":stateString==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":stateString==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":stateString==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":stateString==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":stateString}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}function authConfigToMldev$4(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function batchJobDestinationFromMldev(fromObject){let toObject={},fromFileName=getValueByPath(fromObject,["responsesFile"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromInlinedResponses=getValueByPath(fromObject,["inlinedResponses","inlinedResponses"]);if(fromInlinedResponses!=null){let transformedList=fromInlinedResponses;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>inlinedResponseFromMldev(item))),setValueByPath(toObject,["inlinedResponses"],transformedList)}let fromInlinedEmbedContentResponses=getValueByPath(fromObject,["inlinedEmbedContentResponses","inlinedResponses"]);if(fromInlinedEmbedContentResponses!=null){let transformedList=fromInlinedEmbedContentResponses;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["inlinedEmbedContentResponses"],transformedList)}return toObject}function batchJobDestinationFromVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["predictionsFormat"]);fromFormat!=null&&setValueByPath(toObject,["format"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsDestination","outputUriPrefix"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryDestination","outputUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryUri"],fromBigqueryUri);let fromVertexDataset=getValueByPath(fromObject,["vertexMultimodalDatasetDestination"]);return fromVertexDataset!=null&&setValueByPath(toObject,["vertexDataset"],vertexMultimodalDatasetDestinationFromVertex(fromVertexDataset)),toObject}function batchJobDestinationToVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["format"]);fromFormat!=null&&setValueByPath(toObject,["predictionsFormat"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsDestination","outputUriPrefix"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryDestination","outputUri"],fromBigqueryUri);let fromVertexDataset=getValueByPath(fromObject,["vertexDataset"]);if(fromVertexDataset!=null&&setValueByPath(toObject,["vertexMultimodalDatasetDestination"],vertexMultimodalDatasetDestinationToVertex(fromVertexDataset)),getValueByPath(fromObject,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function batchJobFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["metadata","displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromState=getValueByPath(fromObject,["metadata","state"]);fromState!=null&&setValueByPath(toObject,["state"],tJobState(fromState));let fromCreateTime=getValueByPath(fromObject,["metadata","createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromEndTime=getValueByPath(fromObject,["metadata","endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["metadata","updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromModel=getValueByPath(fromObject,["metadata","model"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromDest=getValueByPath(fromObject,["metadata","output"]);return fromDest!=null&&setValueByPath(toObject,["dest"],batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest))),toObject}function batchJobFromVertex(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tJobState(fromState));let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromSrc=getValueByPath(fromObject,["inputConfig"]);fromSrc!=null&&setValueByPath(toObject,["src"],batchJobSourceFromVertex(fromSrc));let fromDest=getValueByPath(fromObject,["outputConfig"]);fromDest!=null&&setValueByPath(toObject,["dest"],batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest)));let fromOutputInfo=getValueByPath(fromObject,["outputInfo"]);fromOutputInfo!=null&&setValueByPath(toObject,["outputInfo"],fromOutputInfo);let fromCompletionStats=getValueByPath(fromObject,["completionStats"]);return fromCompletionStats!=null&&setValueByPath(toObject,["completionStats"],fromCompletionStats),toObject}function batchJobSourceFromVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["instancesFormat"]);fromFormat!=null&&setValueByPath(toObject,["format"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsSource","uris"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigquerySource","inputUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryUri"],fromBigqueryUri);let fromVertexDatasetName=getValueByPath(fromObject,["vertexMultimodalDatasetSource","datasetName"]);return fromVertexDatasetName!=null&&setValueByPath(toObject,["vertexDatasetName"],fromVertexDatasetName),toObject}function batchJobSourceToMldev(apiClient,fromObject){let toObject={};if(getValueByPath(fromObject,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromInlinedRequests=getValueByPath(fromObject,["inlinedRequests"]);if(fromInlinedRequests!=null){let transformedList=fromInlinedRequests;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>inlinedRequestToMldev(apiClient,item))),setValueByPath(toObject,["requests","requests"],transformedList)}return toObject}function batchJobSourceToVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["format"]);fromFormat!=null&&setValueByPath(toObject,["instancesFormat"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsSource","uris"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigquerySource","inputUri"],fromBigqueryUri);let fromVertexDatasetName=getValueByPath(fromObject,["vertexDatasetName"]);if(fromVertexDatasetName!=null&&setValueByPath(toObject,["vertexMultimodalDatasetSource","datasetName"],fromVertexDatasetName),getValueByPath(fromObject,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function blobToMldev$4(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function cancelBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function cancelBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function candidateFromMldev$1(fromObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev$1(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev$1(fromObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function contentToMldev$4(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$4(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createBatchJobConfigToMldev(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);if(parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["batch","displayName"],fromDisplayName),getValueByPath(fromObject,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);return parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["batch","webhookConfig"],fromWebhookConfig),toObject}function createBatchJobConfigToVertex(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDest=getValueByPath(fromObject,["dest"]);if(parentObject!==void 0&&fromDest!=null&&setValueByPath(parentObject,["outputConfig"],batchJobDestinationToVertex(tBatchJobDestination(fromDest))),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function createBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["batch","inputConfig"],batchJobSourceToMldev(apiClient,tBatchJobSource(apiClient,fromSrc)));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createBatchJobConfigToMldev(fromConfig,toObject),toObject}function createBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["inputConfig"],batchJobSourceToVertex(tBatchJobSource(apiClient,fromSrc)));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createBatchJobConfigToVertex(fromConfig,toObject),toObject}function createEmbeddingsBatchJobConfigToMldev(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);return parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["batch","displayName"],fromDisplayName),toObject}function createEmbeddingsBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["batch","inputConfig"],embeddingsBatchJobSourceToMldev(apiClient,fromSrc));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createEmbeddingsBatchJobConfigToMldev(fromConfig,toObject),toObject}function deleteBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function deleteBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function deleteResourceJobFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function deleteResourceJobFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function embedContentBatchToMldev(apiClient,fromObject){let toObject={},fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","request","content"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&(setValueByPath(toObject,["_self"],embedContentConfigToMldev$1(fromConfig,toObject)),moveValueByPath(toObject,{"requests[].*":"requests[].request.*"})),toObject}function embedContentConfigToMldev$1(fromObject,parentObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embeddingsBatchJobSourceToMldev(apiClient,fromObject){let toObject={},fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["file_name"],fromFileName);let fromInlinedRequests=getValueByPath(fromObject,["inlinedRequests"]);return fromInlinedRequests!=null&&setValueByPath(toObject,["requests"],embedContentBatchToMldev(apiClient,fromInlinedRequests)),toObject}function fileDataToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$4(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$2(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev$1(apiClient,fromObject,parentObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$4(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$3(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$4(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$2(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev$1(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentResponseFromMldev$1(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev$1(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function getBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function getBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function googleMapsToMldev$4(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$4(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev$1(fromObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function inlinedRequestToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["request","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$4(item))),setValueByPath(toObject,["request","contents"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["request","generationConfig"],generateContentConfigToMldev$1(apiClient,fromConfig,getValueByPath(toObject,["request"],{}))),toObject}function inlinedResponseFromMldev(fromObject){let toObject={},fromResponse=getValueByPath(fromObject,["response"]);fromResponse!=null&&setValueByPath(toObject,["response"],generateContentResponseFromMldev$1(fromResponse));let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function listBatchJobsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);if(parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),getValueByPath(fromObject,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function listBatchJobsConfigToVertex(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listBatchJobsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listBatchJobsConfigToMldev(fromConfig,toObject),toObject}function listBatchJobsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listBatchJobsConfigToVertex(fromConfig,toObject),toObject}function listBatchJobsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromBatchJobs=getValueByPath(fromObject,["operations"]);if(fromBatchJobs!=null){let transformedList=fromBatchJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>batchJobFromMldev(item))),setValueByPath(toObject,["batchJobs"],transformedList)}return toObject}function listBatchJobsResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromBatchJobs=getValueByPath(fromObject,["batchPredictionJobs"]);if(fromBatchJobs!=null){let transformedList=fromBatchJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>batchJobFromVertex(item))),setValueByPath(toObject,["batchJobs"],transformedList)}return toObject}function partToMldev$4(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$4(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$4(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$4(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function safetySettingToMldev$3(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function toolConfigToMldev$2(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$2(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$4(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$4(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function vertexMultimodalDatasetDestinationFromVertex(fromObject){let toObject={},fromBigqueryDestination=getValueByPath(fromObject,["bigqueryDestination","outputUri"]);fromBigqueryDestination!=null&&setValueByPath(toObject,["bigqueryDestination"],fromBigqueryDestination);let fromDisplayName=getValueByPath(fromObject,["displayName"]);return fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName),toObject}function vertexMultimodalDatasetDestinationToVertex(fromObject){let toObject={},fromBigqueryDestination=getValueByPath(fromObject,["bigqueryDestination"]);fromBigqueryDestination!=null&&setValueByPath(toObject,["bigqueryDestination","outputUri"],fromBigqueryDestination);let fromDisplayName=getValueByPath(fromObject,["displayName"]);return fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName),toObject}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,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(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};var Batches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.create=async params=>(this.apiClient.isVertexAI()&&(params.config=this.formatDestination(params.src,params.config)),this.createInternal(params)),this.createEmbeddings=async params=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(params)}}createInlinedGenerateContentRequest(params){let body=createBatchJobParametersToMldev(this.apiClient,params),urlParams=body._url,path2=formatMap("{model}:batchGenerateContent",urlParams),requestsWrapper=body.batch.inputConfig.requests,requests=requestsWrapper.requests,newRequests=[];for(let request of requests){let requestDict=Object.assign({},request);if(requestDict.systemInstruction){let systemInstructionValue=requestDict.systemInstruction;delete requestDict.systemInstruction;let requestContent=requestDict.request;requestContent.systemInstruction=systemInstructionValue,requestDict.request=requestContent}newRequests.push(requestDict)}return requestsWrapper.requests=newRequests,delete body.config,delete body._url,delete body._query,{path:path2,body}}getGcsUri(src){if(typeof src=="string")return src.startsWith("gs://")?src:void 0;if(!Array.isArray(src)&&src.gcsUri&&src.gcsUri.length>0)return src.gcsUri[0]}getBigqueryUri(src){if(typeof src=="string")return src.startsWith("bq://")?src:void 0;if(!Array.isArray(src))return src.bigqueryUri}formatDestination(src,config){let newConfig=config?Object.assign({},config):{},timestampStr=Date.now().toString();if(newConfig.displayName||(newConfig.displayName=`genaiBatchJob_${timestampStr}`),newConfig.dest===void 0){let gcsUri=this.getGcsUri(src),bigqueryUri=this.getBigqueryUri(src);if(gcsUri)gcsUri.endsWith(".jsonl")?newConfig.dest=`${gcsUri.slice(0,-6)}/dest`:newConfig.dest=`${gcsUri}_dest_${timestampStr}`;else if(bigqueryUri)newConfig.dest=`${bigqueryUri}_dest_${timestampStr}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return newConfig}async createInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromVertex(apiResponse))}else{let body=createBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:batchGenerateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async createEmbeddingsInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createEmbeddingsBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:asyncBatchEmbedContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromVertex(apiResponse))}else{let body=getBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("batches/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async cancel(params){var _a2,_b,_c,_d;let path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelBatchJobParametersToVertex(this.apiClient,params);path2=formatMap("batchPredictionJobs/{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}else{let body=cancelBatchJobParametersToMldev(this.apiClient,params);path2=formatMap("batches/{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal})}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listBatchJobsParametersToVertex(params);return path2=formatMap("batchPredictionJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listBatchJobsResponseFromVertex(apiResponse),typedResp=new ListBatchJobsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listBatchJobsParametersToMldev(params);return path2=formatMap("batches",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listBatchJobsResponseFromMldev(apiResponse),typedResp=new ListBatchJobsResponse;return Object.assign(typedResp,resp),typedResp})}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>deleteResourceJobFromVertex(apiResponse))}else{let body=deleteBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("batches/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>deleteResourceJobFromMldev(apiResponse))}}};function authConfigToMldev$3(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$3(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function computerUseToVertex$2(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToMldev$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$3(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$1(fromToolConfig)),getValueByPath(fromObject,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$2(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex$1(fromToolConfig));let fromKmsKeyName=getValueByPath(fromObject,["kmsKeyName"]);return parentObject!==void 0&&fromKmsKeyName!=null&&setValueByPath(parentObject,["encryption_spec","kmsKeyName"],fromKmsKeyName),toObject}function createCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToMldev(fromConfig,toObject),toObject}function createCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToVertex(fromConfig,toObject),toObject}function deleteCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteCachedContentResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function fileDataToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$3(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$1(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function getCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function getCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function googleMapsToMldev$3(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$3(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function listCachedContentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsConfigToVertex(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToMldev(fromConfig,toObject),toObject}function listCachedContentsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToVertex(fromConfig,toObject),toObject}function listCachedContentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function listCachedContentsResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function mcpServerToVertex$2(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function partToMldev$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$3(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$3(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$3(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function toolConfigToMldev$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$1(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$3(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$3(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$2(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$2(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$2(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function updateCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToMldev(fromConfig,toObject),toObject}function updateCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToVertex(fromConfig,toObject),toObject}var Caches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS,x=>this.listInternal(x),await this.listInternal(params),params)}async create(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=createCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=getCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromVertex(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromMldev(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=updateCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listCachedContentsParametersToVertex(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromVertex(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listCachedContentsParametersToMldev(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromMldev(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}}};function __rest(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]]);return t}function __values(o){var s=typeof Symbol=="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){g[n]&&(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f&&(i[n]=f(i[n])))}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function isValidResponse(response){var _a2;if(response.candidates==null||response.candidates.length===0)return!1;let content=(_a2=response.candidates[0])===null||_a2===void 0?void 0:_a2.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0)return!1;return!0}function validateHistory(history){if(history.length!==0){for(let content of history)if(content.role!=="user"&&content.role!=="model")throw new Error(`Role must be user or model, but got ${content.role}.`)}}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i=0;for(;i<length;)if(comprehensiveHistory[i].role==="user")curatedHistory.push(comprehensiveHistory[i]),i++;else{let modelOutput=[],isValid=!0;for(;i<length&&comprehensiveHistory[i].role==="model";)modelOutput.push(comprehensiveHistory[i]),isValid&&!isValidContent(comprehensiveHistory[i])&&(isValid=!1),i++;isValid?curatedHistory.push(...modelOutput):curatedHistory.pop()}return curatedHistory}var Chats=class{constructor(modelsModule,apiClient){this.modelsModule=modelsModule,this.apiClient=apiClient}create(params){return new Chat(this.apiClient,this.modelsModule,params.model,params.config,structuredClone(params.history))}},Chat=class{constructor(apiClient,modelsModule,model,config={},history=[]){this.apiClient=apiClient,this.modelsModule=modelsModule,this.model=model,this.config=config,this.history=history,this.sendPromise=Promise.resolve(),validateHistory(history)}async sendMessage(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),responsePromise=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});return this.sendPromise=(async()=>{var _a3,_b,_c;let response=await responsePromise,outputContent=(_b=(_a3=response.candidates)===null||_a3===void 0?void 0:_a3[0])===null||_b===void 0?void 0:_b.content,fullAutomaticFunctionCallingHistory=response.automaticFunctionCallingHistory,index=this.getHistory(!0).length,automaticFunctionCallingHistory=[];fullAutomaticFunctionCallingHistory!=null&&(automaticFunctionCallingHistory=(_c=fullAutomaticFunctionCallingHistory.slice(index))!==null&&_c!==void 0?_c:[]);let modelOutput=outputContent?[outputContent]:[];this.recordHistory(inputContent,modelOutput,automaticFunctionCallingHistory)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),responsePromise}async sendMessageStream(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),streamResponse=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});this.sendPromise=streamResponse.then(()=>{}).catch(()=>{});let response=await streamResponse;return this.processStreamResponse(response,inputContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}processStreamResponse(streamResponse,inputContent){return __asyncGenerator(this,arguments,function*(){var _a2,e_1,_b,_c,_d,_e;let outputContent=[];try{for(var _f=!0,streamResponse_1=__asyncValues(streamResponse),streamResponse_1_1;streamResponse_1_1=yield __await(streamResponse_1.next()),_a2=streamResponse_1_1.done,!_a2;_f=!0){_c=streamResponse_1_1.value,_f=!1;let chunk=_c;if(isValidResponse(chunk)){let content=(_e=(_d=chunk.candidates)===null||_d===void 0?void 0:_d[0])===null||_e===void 0?void 0:_e.content;content!==void 0&&outputContent.push(content)}yield yield __await(chunk)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a2&&(_b=streamResponse_1.return)&&(yield __await(_b.call(streamResponse_1)))}finally{if(e_1)throw e_1.error}}this.recordHistory(inputContent,outputContent)})}recordHistory(userInput,modelOutput,automaticFunctionCallingHistory){let outputContents=[];modelOutput.length>0&&modelOutput.every(content=>content.role!==void 0)?outputContents=modelOutput:outputContents.push({role:"model",parts:[]}),automaticFunctionCallingHistory&&automaticFunctionCallingHistory.length>0?this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)):this.history.push(userInput),this.history.push(...outputContents)}};var ApiError=class _ApiError extends Error{constructor(options){super(options.message),this.name="ApiError",this.status=options.status,Object.setPrototypeOf(this,_ApiError.prototype)}};function createFileParametersToMldev(fromObject){let toObject={},fromFile=getValueByPath(fromObject,["file"]);return fromFile!=null&&setValueByPath(toObject,["file"],fromFile),toObject}function createFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function deleteFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function getFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function internalRegisterFilesParametersToMldev(fromObject){let toObject={},fromUris=getValueByPath(fromObject,["uris"]);return fromUris!=null&&setValueByPath(toObject,["uris"],fromUris),toObject}function listFilesConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listFilesParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFilesConfigToMldev(fromConfig,toObject),toObject}function listFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}function registerFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}var Files$1=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILES,x=>this.listInternal(x),await this.listInternal(params),params)}async upload(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(params.file,params.config).then(resp=>resp)}async download(params){await this.apiClient.downloadFile(params)}async registerFiles(params){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(params){return this.registerFilesInternal(params)}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFilesParametersToMldev(params);return path2=formatMap("files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listFilesResponseFromMldev(apiResponse),typedResp=new ListFilesResponse;return Object.assign(typedResp,resp),typedResp})}}async createInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileParametersToMldev(params);return path2=formatMap("upload/v1beta/files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=createFileResponseFromMldev(apiResponse),typedResp=new CreateFileResponse;return Object.assign(typedResp,resp),typedResp})}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteFileResponseFromMldev(apiResponse),typedResp=new DeleteFileResponse;return Object.assign(typedResp,resp),typedResp})}}async registerFilesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=internalRegisterFilesParametersToMldev(params);return path2=formatMap("files:register",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=registerFilesResponseFromMldev(apiResponse),typedResp=new RegisterFilesResponse;return Object.assign(typedResp,resp),typedResp})}}};function authConfigToMldev$2(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$2(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function computerUseToVertex$1(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToMldev$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function fileDataToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$2(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generationConfigToVertex$1(fromObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex$1(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function googleMapsToMldev$2(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$2(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev$1(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$2(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev$1(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$2(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConfigToVertex(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],generationConfigToVertex$1(fromGenerationConfig));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToVertex$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],fromSessionResumption);let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity);let fromExplicitVadSignal=getValueByPath(fromObject,["explicitVadSignal"]);parentObject!==void 0&&fromExplicitVadSignal!=null&&setValueByPath(parentObject,["setup","explicitVadSignal"],fromExplicitVadSignal);let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev$1(fromConfig,toObject)),toObject}function liveConnectParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToVertex(fromConfig,toObject)),toObject}function liveMusicSetConfigParametersToMldev(fromObject){let toObject={},fromMusicGenerationConfig=getValueByPath(fromObject,["musicGenerationConfig"]);return fromMusicGenerationConfig!=null&&setValueByPath(toObject,["musicGenerationConfig"],fromMusicGenerationConfig),toObject}function liveMusicSetWeightedPromptsParametersToMldev(fromObject){let toObject={},fromWeightedPrompts=getValueByPath(fromObject,["weightedPrompts"]);if(fromWeightedPrompts!=null){let transformedList=fromWeightedPrompts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["weightedPrompts"],transformedList)}return toObject}function liveSendRealtimeInputParametersToMldev(fromObject){let toObject={},fromMedia=getValueByPath(fromObject,["media"]);if(fromMedia!=null){let transformedList=tBlobs(fromMedia);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>blobToMldev$2(item))),setValueByPath(toObject,["mediaChunks"],transformedList)}let fromAudio=getValueByPath(fromObject,["audio"]);fromAudio!=null&&setValueByPath(toObject,["audio"],blobToMldev$2(tAudioBlob(fromAudio)));let fromAudioStreamEnd=getValueByPath(fromObject,["audioStreamEnd"]);fromAudioStreamEnd!=null&&setValueByPath(toObject,["audioStreamEnd"],fromAudioStreamEnd);let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["video"],blobToMldev$2(tImageBlob(fromVideo)));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromActivityStart=getValueByPath(fromObject,["activityStart"]);fromActivityStart!=null&&setValueByPath(toObject,["activityStart"],fromActivityStart);let fromActivityEnd=getValueByPath(fromObject,["activityEnd"]);return fromActivityEnd!=null&&setValueByPath(toObject,["activityEnd"],fromActivityEnd),toObject}function liveSendRealtimeInputParametersToVertex(fromObject){let toObject={},fromMedia=getValueByPath(fromObject,["media"]);if(fromMedia!=null){let transformedList=tBlobs(fromMedia);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mediaChunks"],transformedList)}let fromAudio=getValueByPath(fromObject,["audio"]);fromAudio!=null&&setValueByPath(toObject,["audio"],tAudioBlob(fromAudio));let fromAudioStreamEnd=getValueByPath(fromObject,["audioStreamEnd"]);fromAudioStreamEnd!=null&&setValueByPath(toObject,["audioStreamEnd"],fromAudioStreamEnd);let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["video"],tImageBlob(fromVideo));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromActivityStart=getValueByPath(fromObject,["activityStart"]);fromActivityStart!=null&&setValueByPath(toObject,["activityStart"],fromActivityStart);let fromActivityEnd=getValueByPath(fromObject,["activityEnd"]);return fromActivityEnd!=null&&setValueByPath(toObject,["activityEnd"],fromActivityEnd),toObject}function liveServerMessageFromVertex(fromObject){let toObject={},fromSetupComplete=getValueByPath(fromObject,["setupComplete"]);fromSetupComplete!=null&&setValueByPath(toObject,["setupComplete"],fromSetupComplete);let fromServerContent=getValueByPath(fromObject,["serverContent"]);fromServerContent!=null&&setValueByPath(toObject,["serverContent"],fromServerContent);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolCallCancellation=getValueByPath(fromObject,["toolCallCancellation"]);fromToolCallCancellation!=null&&setValueByPath(toObject,["toolCallCancellation"],fromToolCallCancellation);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],usageMetadataFromVertex(fromUsageMetadata));let fromGoAway=getValueByPath(fromObject,["goAway"]);fromGoAway!=null&&setValueByPath(toObject,["goAway"],fromGoAway);let fromSessionResumptionUpdate=getValueByPath(fromObject,["sessionResumptionUpdate"]);fromSessionResumptionUpdate!=null&&setValueByPath(toObject,["sessionResumptionUpdate"],fromSessionResumptionUpdate);let fromVoiceActivityDetectionSignal=getValueByPath(fromObject,["voiceActivityDetectionSignal"]);fromVoiceActivityDetectionSignal!=null&&setValueByPath(toObject,["voiceActivityDetectionSignal"],fromVoiceActivityDetectionSignal);let fromVoiceActivity=getValueByPath(fromObject,["voiceActivity"]);return fromVoiceActivity!=null&&setValueByPath(toObject,["voiceActivity"],voiceActivityFromVertex(fromVoiceActivity)),toObject}function mcpServerToVertex$1(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function multiSpeakerVoiceConfigToVertex$1(fromObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex$1(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$2(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$2(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$2(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$2(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$2(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function replicatedVoiceConfigToVertex$1(fromObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetySettingToMldev$2(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev$1(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function speakerVoiceConfigToVertex$1(fromObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex$1(fromVoiceConfig)),toObject}function speechConfigToVertex$1(fromObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex$1(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex$1(fromMultiSpeakerVoiceConfig)),toObject}function toolToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$2(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$2(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$1(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$1(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$1(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function usageMetadataFromVertex(fromObject){let toObject={},fromResponseTokenCount=getValueByPath(fromObject,["candidatesTokenCount"]);fromResponseTokenCount!=null&&setValueByPath(toObject,["responseTokenCount"],fromResponseTokenCount);let fromResponseTokensDetails=getValueByPath(fromObject,["candidatesTokensDetails"]);if(fromResponseTokensDetails!=null){let transformedList=fromResponseTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseTokensDetails"],transformedList)}let fromCacheTokensDetails=getValueByPath(fromObject,["cacheTokensDetails"]);if(fromCacheTokensDetails!=null){let transformedList=fromCacheTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cacheTokensDetails"],transformedList)}let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount);let fromPromptTokenCount=getValueByPath(fromObject,["promptTokenCount"]);fromPromptTokenCount!=null&&setValueByPath(toObject,["promptTokenCount"],fromPromptTokenCount);let fromPromptTokensDetails=getValueByPath(fromObject,["promptTokensDetails"]);if(fromPromptTokensDetails!=null){let transformedList=fromPromptTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["promptTokensDetails"],transformedList)}let fromThoughtsTokenCount=getValueByPath(fromObject,["thoughtsTokenCount"]);fromThoughtsTokenCount!=null&&setValueByPath(toObject,["thoughtsTokenCount"],fromThoughtsTokenCount);let fromToolUsePromptTokenCount=getValueByPath(fromObject,["toolUsePromptTokenCount"]);fromToolUsePromptTokenCount!=null&&setValueByPath(toObject,["toolUsePromptTokenCount"],fromToolUsePromptTokenCount);let fromToolUsePromptTokensDetails=getValueByPath(fromObject,["toolUsePromptTokensDetails"]);if(fromToolUsePromptTokensDetails!=null){let transformedList=fromToolUsePromptTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["toolUsePromptTokensDetails"],transformedList)}let fromTotalTokenCount=getValueByPath(fromObject,["totalTokenCount"]);fromTotalTokenCount!=null&&setValueByPath(toObject,["totalTokenCount"],fromTotalTokenCount);let fromTrafficType=getValueByPath(fromObject,["trafficType"]);return fromTrafficType!=null&&setValueByPath(toObject,["trafficType"],fromTrafficType),toObject}function voiceActivityFromVertex(fromObject){let toObject={},fromVoiceActivityType=getValueByPath(fromObject,["type"]);fromVoiceActivityType!=null&&setValueByPath(toObject,["voiceActivityType"],fromVoiceActivityType);let fromAudioOffset=getValueByPath(fromObject,["audioOffset"]);return fromAudioOffset!=null&&setValueByPath(toObject,["audioOffset"],fromAudioOffset),toObject}function voiceConfigToVertex$1(fromObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex$1(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}function authConfigToMldev$1(fromObject,_rootObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev(fromObject,_rootObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function computeTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}return toObject}function computeTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function computerUseToVertex(fromObject,_rootObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["controlType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType==="PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONTENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embedContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtraction"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents==="PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),toObject}function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==void 0&&fromImageSize!=null&&setValueByPath(parentObject,["parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubTopic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameters","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameters","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosSourceToMldev(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$1(fromObject,rootObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$1(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$1(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToMldev(fromConfig,toObject),toObject}function updateModelParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}function createFileSearchStoreConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromEmbeddingModel=getValueByPath(fromObject,["embeddingModel"]);return parentObject!==void 0&&fromEmbeddingModel!=null&&setValueByPath(parentObject,["embeddingModel"],tModel(apiClient,fromEmbeddingModel)),toObject}function createFileSearchStoreParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createFileSearchStoreConfigToMldev(apiClient,fromConfig,toObject),toObject}function deleteFileSearchStoreConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteFileSearchStoreParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteFileSearchStoreConfigToMldev(fromConfig,toObject),toObject}function getFileSearchStoreParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function importFileConfigToMldev(fromObject,parentObject){let toObject={},fromCustomMetadata=getValueByPath(fromObject,["customMetadata"]);if(parentObject!==void 0&&fromCustomMetadata!=null){let transformedList=fromCustomMetadata;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["customMetadata"],transformedList)}let fromChunkingConfig=getValueByPath(fromObject,["chunkingConfig"]);return parentObject!==void 0&&fromChunkingConfig!=null&&setValueByPath(parentObject,["chunkingConfig"],fromChunkingConfig),toObject}function importFileOperationFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],importFileResponseFromMldev(fromResponse)),toObject}function importFileParametersToMldev(fromObject){let toObject={},fromFileSearchStoreName=getValueByPath(fromObject,["fileSearchStoreName"]);fromFileSearchStoreName!=null&&setValueByPath(toObject,["_url","file_search_store_name"],fromFileSearchStoreName);let fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&importFileConfigToMldev(fromConfig,toObject),toObject}function importFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function listFileSearchStoresConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listFileSearchStoresParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFileSearchStoresConfigToMldev(fromConfig,toObject),toObject}function listFileSearchStoresResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFileSearchStores=getValueByPath(fromObject,["fileSearchStores"]);if(fromFileSearchStores!=null){let transformedList=fromFileSearchStores;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["fileSearchStores"],transformedList)}return toObject}function uploadToFileSearchStoreConfigToMldev(fromObject,parentObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["mimeType"],fromMimeType);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromCustomMetadata=getValueByPath(fromObject,["customMetadata"]);if(parentObject!==void 0&&fromCustomMetadata!=null){let transformedList=fromCustomMetadata;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["customMetadata"],transformedList)}let fromChunkingConfig=getValueByPath(fromObject,["chunkingConfig"]);return parentObject!==void 0&&fromChunkingConfig!=null&&setValueByPath(parentObject,["chunkingConfig"],fromChunkingConfig),toObject}function uploadToFileSearchStoreParametersToMldev(fromObject){let toObject={},fromFileSearchStoreName=getValueByPath(fromObject,["fileSearchStoreName"]);fromFileSearchStoreName!=null&&setValueByPath(toObject,["_url","file_search_store_name"],fromFileSearchStoreName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&uploadToFileSearchStoreConfigToMldev(fromConfig,toObject),toObject}function uploadToFileSearchStoreResumableResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}var CONTENT_TYPE_HEADER="Content-Type",SERVER_TIMEOUT_HEADER="X-Server-Timeout",USER_AGENT_HEADER="User-Agent",GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.21.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`,VERTEX_AI_API_DEFAULT_VERSION="v1beta1",GOOGLE_AI_API_DEFAULT_VERSION="v1beta",MULTI_REGIONAL_LOCATIONS=new Set(["us","eu"]);function raiseUndiciTimeouts(timeout){let globalDispatcher=globalThis[Symbol.for("undici.globalDispatcher.1")];if(globalDispatcher)for(let sym of Object.getOwnPropertySymbols(globalDispatcher)){let desc=sym.description;if(desc?.includes("headers timeout")||desc?.includes("body timeout")){let currentTimeout=globalDispatcher[sym];typeof currentTimeout=="number"&&(globalDispatcher[sym]=Math.max(currentTimeout,timeout))}}}function createAttemptSignal(timeout,callerSignal){let noop=()=>{};if(!(timeout&&timeout>0)&&!callerSignal)return{signal:void 0,dispose:noop};let controller=new AbortController,timeoutHandle;timeout&&timeout>0&&(timeoutHandle=setTimeout(()=>controller.abort(),timeout),timeoutHandle&&typeof timeoutHandle.unref=="function"&&timeoutHandle.unref());let onCallerAbort=()=>controller.abort();return callerSignal&&(callerSignal.aborted?controller.abort():callerSignal.addEventListener("abort",onCallerAbort)),{signal:controller.signal,dispose:()=>{timeoutHandle!==void 0&&clearTimeout(timeoutHandle),callerSignal?.removeEventListener("abort",onCallerAbort)}}}var DEFAULT_RETRY_ATTEMPTS=5,DEFAULT_RETRY_INITIAL_DELAY=1,DEFAULT_RETRY_MAX_DELAY=60,DEFAULT_RETRY_EXP_BASE=2,DEFAULT_RETRY_JITTER=1,DEFAULT_RETRY_HTTP_STATUS_CODES=[408,429,500,502,503,504],ApiClient=class{constructor(opts){var _a2,_b,_c;this.clientOptions=Object.assign({},opts),this.customBaseUrl=(_a2=opts.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl;let initHttpOptions={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let hasConstructorAuth=opts.project&&opts.location||!!opts.apiKey;this.customBaseUrl&&!hasConstructorAuth?(initHttpOptions.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?initHttpOptions.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&MULTI_REGIONAL_LOCATIONS.has(this.clientOptions.location)?initHttpOptions.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(initHttpOptions.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),initHttpOptions.apiVersion=(_b=this.clientOptions.apiVersion)!==null&&_b!==void 0?_b:VERTEX_AI_API_DEFAULT_VERSION}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),initHttpOptions.apiVersion=(_c=this.clientOptions.apiVersion)!==null&&_c!==void 0?_c:GOOGLE_AI_API_DEFAULT_VERSION,initHttpOptions.baseUrl="https://generativelanguage.googleapis.com/";initHttpOptions.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=initHttpOptions,opts.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(initHttpOptions,opts.httpOptions))}isVertexAI(){var _a2;return(_a2=this.clientOptions.vertexai)!==null&&_a2!==void 0?_a2:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let headers=new Headers;return await this.clientOptions.auth.addAuthHeaders(headers),headers}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(httpOptions){if(!httpOptions||httpOptions.baseUrl===void 0||httpOptions.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let urlElement=[httpOptions.baseUrl.endsWith("/")?httpOptions.baseUrl.slice(0,-1):httpOptions.baseUrl];return httpOptions.apiVersion&&httpOptions.apiVersion!==""&&urlElement.push(httpOptions.apiVersion),urlElement.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let baseUrl=this.getBaseUrl(),urlParts=new URL(baseUrl);return urlParts.protocol=urlParts.protocol=="http:"?"ws":"wss",urlParts.toString()}setBaseUrl(url){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=url;else throw new Error("HTTP options are not correctly set.")}constructUrl(path2,httpOptions,prependProjectLocation){let urlElement=[this.getRequestUrlInternal(httpOptions)];return prependProjectLocation&&urlElement.push(this.getBaseResourcePath()),path2!==""&&urlElement.push(path2),new URL(`${urlElement.join("/")}`)}shouldPrependVertexProjectPath(request,httpOptions){return!(httpOptions.baseUrl&&httpOptions.baseUrlResourceScope===ResourceScope.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||request.path.startsWith("projects/")||request.httpMethod==="GET"&&request.path.startsWith("publishers/google/models"))}async request(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);if(request.queryParams)for(let[key,value]of Object.entries(request.queryParams))url.searchParams.append(key,String(value));let requestInit={};if(request.httpMethod==="GET"){if(request.body&&request.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else requestInit.body=request.body;return requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.unaryApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal)}patchHttpOptions(baseHttpOptions,requestHttpOptions){let patchedHttpOptions=JSON.parse(JSON.stringify(baseHttpOptions));for(let[key,value]of Object.entries(requestHttpOptions))typeof value=="object"?patchedHttpOptions[key]=Object.assign(Object.assign({},patchedHttpOptions[key]),value):value!==void 0&&(patchedHttpOptions[key]=value);return patchedHttpOptions}async requestStream(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);(!url.searchParams.has("alt")||url.searchParams.get("alt")!=="sse")&&url.searchParams.set("alt","sse");let requestInit={};return requestInit.body=request.body,requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.streamApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal)}async includeExtraHttpOptionsToRequestInit(requestInit,httpOptions,url){return httpOptions?.timeout&&httpOptions.timeout>0&&raiseUndiciTimeouts(httpOptions.timeout),httpOptions&&httpOptions.extraBody!==null&&includeExtraBodyToRequestInit(requestInit,httpOptions.extraBody),requestInit.headers=await this.getHeadersInternal(httpOptions,url),requestInit}async unaryApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal).then(async response=>(await throwErrorIfNotOK(response),new HttpResponse(response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}async streamApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal).then(async response=>(await throwErrorIfNotOK(response),this.processStreamResponse(response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}processStreamResponse(response){return __asyncGenerator(this,arguments,function*(){var _a2;let reader=(_a2=response?.body)===null||_a2===void 0?void 0:_a2.getReader(),decoder=new TextDecoder("utf-8");if(!reader)throw new Error("Response body is empty");try{let buffer="",dataPrefix="data:",delimiters=[`
`,"\r\r",`\r
\r
`];for(;;){let{done,value}=yield __await(reader.read());if(done){if(buffer.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let chunkString=decoder.decode(value,{stream:!0});try{let chunkJson=JSON.parse(chunkString);if("error"in chunkJson){let errorJson=JSON.parse(JSON.stringify(chunkJson.error)),status=errorJson.status,code=errorJson.code,errorMessage=`got status: ${status}. ${JSON.stringify(chunkJson)}`;if(code>=400&&code<600)throw new ApiError({message:errorMessage,status:code})}}catch(e){if(e.name==="ApiError")throw e}buffer+=chunkString;let delimiterIndex=-1,delimiterLength=0;for(;;){delimiterIndex=-1,delimiterLength=0;for(let delimiter of delimiters){let index=buffer.indexOf(delimiter);index!==-1&&(delimiterIndex===-1||index<delimiterIndex)&&(delimiterIndex=index,delimiterLength=delimiter.length)}if(delimiterIndex===-1)break;let eventString=buffer.substring(0,delimiterIndex);buffer=buffer.substring(delimiterIndex+delimiterLength);let trimmedEvent=eventString.trim();if(trimmedEvent.startsWith(dataPrefix)){let processedChunkString=trimmedEvent.substring(dataPrefix.length).trim();try{let partialResponse=new Response(processedChunkString,{headers:response?.headers,status:response?.status,statusText:response?.statusText});yield yield __await(new HttpResponse(partialResponse))}catch(e){throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`)}}}}}finally{reader.releaseLock()}})}async apiCall(url,requestInit,retryOptions,timeout,abortSignal){var _a2,_b,_c,_d,_e,_f;let retryableStatusCodes=(_a2=retryOptions?.httpStatusCodes)!==null&&_a2!==void 0?_a2:DEFAULT_RETRY_HTTP_STATUS_CODES,runFetch=async()=>{let attempt=createAttemptSignal(timeout,abortSignal),response;try{response=await fetch(url,Object.assign(Object.assign({},requestInit),{signal:attempt.signal}))}catch(e){throw attempt.dispose(),e}if(!retryOptions||response.ok||!retryableStatusCodes.includes(response.status))return response;try{await throwErrorIfNotOK(response)}finally{attempt.dispose()}return response};if(!retryOptions)return runFetch();let attempts=Math.max(1,(_b=retryOptions.attempts)!==null&&_b!==void 0?_b:DEFAULT_RETRY_ATTEMPTS),minTimeout=Math.round(((_c=retryOptions.initialDelay)!==null&&_c!==void 0?_c:DEFAULT_RETRY_INITIAL_DELAY)*1e3),maxTimeout=Math.max(minTimeout,Math.round(((_d=retryOptions.maxDelay)!==null&&_d!==void 0?_d:DEFAULT_RETRY_MAX_DELAY)*1e3));return(0,import_p_retry.default)(runFetch,{retries:attempts-1,factor:(_e=retryOptions.expBase)!==null&&_e!==void 0?_e:DEFAULT_RETRY_EXP_BASE,minTimeout,maxTimeout,randomize:((_f=retryOptions.jitter)!==null&&_f!==void 0?_f:DEFAULT_RETRY_JITTER)>0,onFailedAttempt:info=>{var _a3;if(abortSignal?.aborted)throw(_a3=info.error)!==null&&_a3!==void 0?_a3:info}})}getDefaultHeaders(){let headers={},versionHeaderValue=LIBRARY_LABEL+" "+this.clientOptions.userAgentExtra;return headers[USER_AGENT_HEADER]=versionHeaderValue,headers[GOOGLE_API_CLIENT_HEADER]=versionHeaderValue,headers[CONTENT_TYPE_HEADER]="application/json",headers}async getHeadersInternal(httpOptions,url){let headers=new Headers;if(httpOptions&&httpOptions.headers)for(let[key,value]of Object.entries(httpOptions.headers))headers.append(key,value);return httpOptions?.timeout&&httpOptions.timeout>0&&headers.append(SERVER_TIMEOUT_HEADER,String(Math.ceil(httpOptions.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(headers,url),headers}getFileName(file){var _a2;let fileName="";return typeof file=="string"&&(fileName=file.replace(/[/\\]+$/,""),fileName=(_a2=fileName.split(/[/\\]/).pop())!==null&&_a2!==void 0?_a2:""),fileName}async uploadFile(file,config){var _a2;let fileToUpload={};config!=null&&(fileToUpload.mimeType=config.mimeType,fileToUpload.name=config.name,fileToUpload.displayName=config.displayName),fileToUpload.name&&!fileToUpload.name.startsWith("files/")&&(fileToUpload.name=`files/${fileToUpload.name}`);let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file);fileToUpload.sizeBytes=String(fileStat.size);let mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");fileToUpload.mimeType=mimeType;let body={file:fileToUpload},fileName=this.getFileName(file),path2=formatMap("upload/v1beta/files",body._url),uploadUrl=await this.fetchUploadUrl(path2,fileToUpload.sizeBytes,fileToUpload.mimeType,fileName,body,config?.httpOptions);return uploader.upload(file,uploadUrl,this)}async uploadFileToFileSearchStore(fileSearchStoreName,file,config){var _a2;let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file),sizeBytes=String(fileStat.size),mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let path2=`upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`,fileName=this.getFileName(file),body={};config!=null&&uploadToFileSearchStoreConfigToMldev(config,body);let uploadUrl=await this.fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,config?.httpOptions);return uploader.uploadToFileSearchStore(file,uploadUrl,this)}async downloadFile(params){await this.clientOptions.downloader.download(params,this)}async fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,configHttpOptions){var _a2;let httpOptions={};configHttpOptions?httpOptions=configHttpOptions:httpOptions={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${sizeBytes}`,"X-Goog-Upload-Header-Content-Type":`${mimeType}`},fileName?{"X-Goog-Upload-File-Name":fileName}:{})};let httpResponse=await this.request({path:path2,body:JSON.stringify(body),httpMethod:"POST",httpOptions});if(!httpResponse||!httpResponse?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let uploadUrl=(_a2=httpResponse?.headers)===null||_a2===void 0?void 0:_a2["x-goog-upload-url"];if(uploadUrl===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return uploadUrl}};async function throwErrorIfNotOK(response){var _a2;if(response===void 0)throw new Error("response is undefined");if(!response.ok){let status=response.status,errorBody;!((_a2=response.headers.get("content-type"))===null||_a2===void 0)&&_a2.includes("application/json")?errorBody=await response.json():errorBody={error:{message:await response.text(),code:response.status,status:response.statusText}};let errorMessage=JSON.stringify(errorBody);throw status>=400&&status<600?new ApiError({message:errorMessage,status}):new Error(errorMessage)}}function includeExtraBodyToRequestInit(requestInit,extraBody){if(!extraBody||Object.keys(extraBody).length===0)return;if(requestInit.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let currentBodyObject={};if(typeof requestInit.body=="string"&&requestInit.body.length>0)try{let parsedBody=JSON.parse(requestInit.body);if(typeof parsedBody=="object"&&parsedBody!==null&&!Array.isArray(parsedBody))currentBodyObject=parsedBody;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function deepMerge(target,source){let output=Object.assign({},target);for(let key in source)if(Object.prototype.hasOwnProperty.call(source,key)){let sourceValue=source[key],targetValue=output[key];sourceValue&&typeof sourceValue=="object"&&!Array.isArray(sourceValue)&&targetValue&&typeof targetValue=="object"&&!Array.isArray(targetValue)?output[key]=deepMerge(targetValue,sourceValue):(targetValue&&sourceValue&&typeof targetValue!=typeof sourceValue&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`),output[key]=sourceValue)}return output}let mergedBody=deepMerge(currentBodyObject,extraBody);requestInit.body=JSON.stringify(mergedBody)}var MCP_LABEL="mcp_used/unknown",hasMcpToolUsageFromMcpToTool=!1;function hasMcpToolUsage(tools){for(let tool of tools)if(isMcpCallableTool(tool)||typeof tool=="object"&&"inputSchema"in tool)return!0;return hasMcpToolUsageFromMcpToTool}function setMcpUsageHeader(headers){var _a2;let existingHeader=(_a2=headers[GOOGLE_API_CLIENT_HEADER])!==null&&_a2!==void 0?_a2:"";headers[GOOGLE_API_CLIENT_HEADER]=(existingHeader+` ${MCP_LABEL}`).trimStart()}function isMcpCallableTool(object){return object!==null&&typeof object=="object"&&object instanceof McpCallableTool}function listAllTools(mcpClient_1){return __asyncGenerator(this,arguments,function*(mcpClient,maxTools=100){let cursor,numTools=0;for(;numTools<maxTools;){let t=yield __await(mcpClient.listTools({cursor}));for(let tool of t.tools)yield yield __await(tool),numTools++;if(!t.nextCursor)break;cursor=t.nextCursor}})}var McpCallableTool=class _McpCallableTool{constructor(mcpClients=[],config){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=mcpClients,this.config=config}static create(mcpClients,config){return new _McpCallableTool(mcpClients,config)}async initialize(){var _a2,e_1,_b,_c;if(this.mcpTools.length>0)return;let functionMap={},mcpTools=[];for(let mcpClient of this.mcpClients)try{for(var _d=!0,_e=(e_1=void 0,__asyncValues(listAllTools(mcpClient))),_f;_f=await _e.next(),_a2=_f.done,!_a2;_d=!0){_c=_f.value,_d=!1;let mcpTool=_c;mcpTools.push(mcpTool);let mcpToolName=mcpTool.name;if(functionMap[mcpToolName])throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);functionMap[mcpToolName]=mcpClient}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=_e.return)&&await _b.call(_e)}finally{if(e_1)throw e_1.error}}this.mcpTools=mcpTools,this.functionNameToMcpClient=functionMap}async tool(){return await this.initialize(),mcpToolsToGeminiTool(this.mcpTools,this.config)}async callTool(functionCalls){await this.initialize();let functionCallResponseParts=[];for(let functionCall of functionCalls)if(functionCall.name in this.functionNameToMcpClient){let mcpClient=this.functionNameToMcpClient[functionCall.name],requestOptions;this.config.timeout&&(requestOptions={timeout:this.config.timeout});let callToolResponse=await mcpClient.callTool({name:functionCall.name,arguments:functionCall.args},void 0,requestOptions);functionCallResponseParts.push({functionResponse:{name:functionCall.name,response:callToolResponse.isError?{error:callToolResponse}:callToolResponse}})}return functionCallResponseParts}};async function handleWebSocketMessage$1(apiClient,onmessage,event){let serverMessage=new LiveMusicServerMessage,data;event.data instanceof Blob?data=JSON.parse(await event.data.text()):data=JSON.parse(event.data),Object.assign(serverMessage,data),onmessage(serverMessage)}var LiveMusic=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory}async connect(params){var _a2,_b;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),headers=mapToHeaders$1(this.apiClient.getDefaultHeaders()),apiKey=this.apiClient.getApiKey(),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`,onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){onopenResolve({})},apiClient=this.apiClient,websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage$1(apiClient,callbacks.onmessage,event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap$1(headers),websocketCallbacks);conn.connect(),await onopenPromise;let clientMessage={setup:{model:tModel(this.apiClient,params.model)}};return conn.send(JSON.stringify(clientMessage)),new LiveMusicSession(conn,this.apiClient)}},LiveMusicSession=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}async setWeightedPrompts(params){if(!params.weightedPrompts||Object.keys(params.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let clientContent=liveMusicSetWeightedPromptsParametersToMldev(params);this.conn.send(JSON.stringify({clientContent}))}async setMusicGenerationConfig(params){params.musicGenerationConfig||(params.musicGenerationConfig={});let setConfigParameters=liveMusicSetConfigParametersToMldev(params);this.conn.send(JSON.stringify(setConfigParameters))}sendPlaybackControl(playbackControl){let clientMessage={playbackControl};this.conn.send(JSON.stringify(clientMessage))}play(){this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY)}pause(){this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE)}stop(){this.sendPlaybackControl(LiveMusicPlaybackControl.STOP)}resetContext(){this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT)}close(){this.conn.close()}};function headersToMap$1(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders$1(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var FUNCTION_RESPONSE_REQUIRES_ID="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function handleWebSocketMessage(apiClient,onmessage,event){let serverMessage=new LiveServerMessage,jsonData;event.data instanceof Blob?jsonData=await event.data.text():event.data instanceof ArrayBuffer?jsonData=new TextDecoder().decode(event.data):jsonData=event.data;let data=JSON.parse(jsonData);if(apiClient.isVertexAI()){let resp=liveServerMessageFromVertex(data);Object.assign(serverMessage,resp)}else Object.assign(serverMessage,data);onmessage(serverMessage)}var Live=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory,this.music=new LiveMusic(this.apiClient,this.auth,this.webSocketFactory)}async connect(params){var _a2,_b,_c,_d,_e,_f;if(params.config&¶ms.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),url,clientHeaders=this.apiClient.getHeaders();params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)&&setMcpUsageHeader(clientHeaders);let headers=mapToHeaders(clientHeaders);if(this.apiClient.isVertexAI()){let project=this.apiClient.getProject(),location=this.apiClient.getLocation(),apiKey=this.apiClient.getApiKey(),hasStandardAuth=!!project&&!!location||!!apiKey;this.apiClient.getCustomBaseUrl()&&!hasStandardAuth?url=websocketBaseUrl:(url=`${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(headers,url))}else{let apiKey=this.apiClient.getApiKey(),method="BidiGenerateContent",keyName="key";apiKey?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),apiVersion!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),method="BidiGenerateContentConstrained",keyName="access_token"),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`}let onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){var _a3;(_a3=callbacks?.onopen)===null||_a3===void 0||_a3.call(callbacks),onopenResolve({})},apiClient=this.apiClient,sessionResolved=!1,messageQueue=[],setupCompleteResolve=()=>{},setupCompletePromise=new Promise(resolve=>{setupCompleteResolve=resolve}),websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage(apiClient,msg=>{msg.setupComplete&&!session.setupComplete&&(session.setupComplete=msg.setupComplete,setupCompleteResolve({})),sessionResolved?callbacks.onmessage(msg):messageQueue.push(msg)},event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap(headers),websocketCallbacks);conn.connect(),await onopenPromise;let transformedModel=tModel(this.apiClient,params.model);if(this.apiClient.isVertexAI()&&transformedModel.startsWith("publishers/")){let project=this.apiClient.getProject(),location=this.apiClient.getLocation();project&&location&&(transformedModel=`projects/${project}/locations/${location}/`+transformedModel)}let clientMessage={};this.apiClient.isVertexAI()&&((_c=params.config)===null||_c===void 0?void 0:_c.responseModalities)===void 0&&(params.config===void 0?params.config={responseModalities:[Modality.AUDIO]}:params.config.responseModalities=[Modality.AUDIO]),!((_d=params.config)===null||_d===void 0)&&_d.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let inputTools=(_f=(_e=params.config)===null||_e===void 0?void 0:_e.tools)!==null&&_f!==void 0?_f:[],convertedTools=[];for(let tool of inputTools)if(this.isCallableTool(tool)){let callableTool=tool;convertedTools.push(await callableTool.tool())}else convertedTools.push(tool);convertedTools.length>0&&(params.config.tools=convertedTools);let liveConnectParameters={model:transformedModel,config:params.config,callbacks:params.callbacks};this.apiClient.isVertexAI()?clientMessage=liveConnectParametersToVertex(this.apiClient,liveConnectParameters):clientMessage=liveConnectParametersToMldev(this.apiClient,liveConnectParameters),delete clientMessage.config;let session=new Session(conn,this.apiClient);conn.send(JSON.stringify(clientMessage)),await setupCompletePromise,sessionResolved=!0;for(let msg of messageQueue)callbacks.onmessage(msg);return session}isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}},defaultLiveSendClientContentParamerters={turnComplete:!0},Session=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}tLiveClientContent(apiClient,params){if(params.turns!==null&¶ms.turns!==void 0){let contents=[];try{contents=tContents(params.turns),apiClient.isVertexAI()||(contents=contents.map(item=>contentToMldev$1(item)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`)}return{clientContent:{turns:contents,turnComplete:params.turnComplete}}}return{clientContent:{turnComplete:params.turnComplete}}}tLiveClienttToolResponse(apiClient,params){let functionResponses=[];if(params.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(params.functionResponses)?functionResponses=params.functionResponses:functionResponses=[params.functionResponses],functionResponses.length===0)throw new Error("functionResponses is required.");for(let functionResponse of functionResponses){if(typeof functionResponse!="object"||functionResponse===null||!("name"in functionResponse)||!("response"in functionResponse))throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);if(!apiClient.isVertexAI()&&!("id"in functionResponse))throw new Error(FUNCTION_RESPONSE_REQUIRES_ID)}return{toolResponse:{functionResponses}}}sendClientContent(params){params=Object.assign(Object.assign({},defaultLiveSendClientContentParamerters),params);let clientMessage=this.tLiveClientContent(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}sendRealtimeInput(params){let clientMessage={};this.apiClient.isVertexAI()?clientMessage={realtimeInput:liveSendRealtimeInputParametersToVertex(params)}:clientMessage={realtimeInput:liveSendRealtimeInputParametersToMldev(params)},this.conn.send(JSON.stringify(clientMessage))}sendToolResponse(params){if(params.functionResponses==null)throw new Error("Tool response parameters are required.");let clientMessage=this.tLiveClienttToolResponse(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}close(){this.conn.close()}};function headersToMap(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===null||_a2===void 0)&&_a2.tools&¶ms.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&¶ms.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x=>this.listInternal(x),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&¶ms.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromVertex(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromMldev(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_2,_b2,_c2;try{for(var _d2=!0,apiResponse_1=__asyncValues(apiResponse),apiResponse_1_1;apiResponse_1_1=yield __await(apiResponse_1.next()),_a3=apiResponse_1_1.done,!_a3;_d2=!0){_c2=apiResponse_1_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromVertex(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_1.return)&&(yield __await(_b2.call(apiResponse_1)))}finally{if(e_2)throw e_2.error}}})})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_3,_b2,_c2;try{for(var _d2=!0,apiResponse_2=__asyncValues(apiResponse),apiResponse_2_1;apiResponse_2_1=yield __await(apiResponse_2.next()),_a3=apiResponse_2_1.done,!_a3;_d2=!0){_c2=apiResponse_2_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromMldev(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_2.return)&&(yield __await(_b2.call(apiResponse_2)))}finally{if(e_3)throw e_3.error}}})})}}async embedContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path2=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path2=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateImagesResponseFromVertex(apiResponse),typedResp=new GenerateImagesResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=editImageResponseFromVertex(apiResponse),typedResp=new EditImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=upscaleImageResponseFromVertex(apiResponse),typedResp=new UpscaleImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=recontextImageResponseFromVertex(apiResponse),typedResp=new RecontextImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=segmentImageResponseFromVertex(apiResponse),typedResp=new SegmentImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=getModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromVertex(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromMldev(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path2=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=updateModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromVertex(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromMldev(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromVertex(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=computeTokensResponseFromVertex(apiResponse),typedResp=new ComputeTokensResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromVertex(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromMldev(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;var Operations=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async getVideosOperation(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async get(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async getVideosOperationInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getOperationParametersToVertex(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else{let body=getOperationParametersToMldev(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response}}async fetchPredictVideosOperationInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=fetchPredictOperationParametersToVertex(params);return path2=formatMap("{resourceName}:fetchPredictOperation",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function authConfigToMldev(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function contentToMldev(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createAuthTokenConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromNewSessionExpireTime=getValueByPath(fromObject,["newSessionExpireTime"]);parentObject!==void 0&&fromNewSessionExpireTime!=null&&setValueByPath(parentObject,["newSessionExpireTime"],fromNewSessionExpireTime);let fromUses=getValueByPath(fromObject,["uses"]);parentObject!==void 0&&fromUses!=null&&setValueByPath(parentObject,["uses"],fromUses);let fromLiveConnectConstraints=getValueByPath(fromObject,["liveConnectConstraints"]);parentObject!==void 0&&fromLiveConnectConstraints!=null&&setValueByPath(parentObject,["bidiGenerateContentSetup"],liveConnectConstraintsToMldev(apiClient,fromLiveConnectConstraints));let fromLockAdditionalFields=getValueByPath(fromObject,["lockAdditionalFields"]);return parentObject!==void 0&&fromLockAdditionalFields!=null&&setValueByPath(parentObject,["fieldMask"],fromLockAdditionalFields),toObject}function createAuthTokenParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],createAuthTokenConfigToMldev(apiClient,fromConfig,toObject)),toObject}function fileDataToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleMapsToMldev(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConstraintsToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev(fromConfig,toObject)),toObject}function partToMldev(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function safetySettingToMldev(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function toolToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function getFieldMasks(setup){let fields=[];for(let key in setup)if(Object.prototype.hasOwnProperty.call(setup,key)){let value=setup[key];if(typeof value=="object"&&value!=null&&Object.keys(value).length>0){let field=Object.keys(value).map(kk=>`${key}.${kk}`);fields.push(...field)}else fields.push(key)}return fields.join(",")}function convertBidiSetupToTokenSetup(requestDict,config){let setupForMaskGeneration=null,bidiGenerateContentSetupValue=requestDict.bidiGenerateContentSetup;if(typeof bidiGenerateContentSetupValue=="object"&&bidiGenerateContentSetupValue!==null&&"setup"in bidiGenerateContentSetupValue){let innerSetup=bidiGenerateContentSetupValue.setup;typeof innerSetup=="object"&&innerSetup!==null?(requestDict.bidiGenerateContentSetup=innerSetup,setupForMaskGeneration=innerSetup):delete requestDict.bidiGenerateContentSetup}else bidiGenerateContentSetupValue!==void 0&&delete requestDict.bidiGenerateContentSetup;let preExistingFieldMask=requestDict.fieldMask;if(setupForMaskGeneration){let generatedMaskFromBidi=getFieldMasks(setupForMaskGeneration);if(Array.isArray(config?.lockAdditionalFields)&&config?.lockAdditionalFields.length===0)generatedMaskFromBidi?requestDict.fieldMask=generatedMaskFromBidi:delete requestDict.fieldMask;else if(config?.lockAdditionalFields&&config.lockAdditionalFields.length>0&&preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0){let generationConfigFields=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],mappedFieldsFromPreExisting=[];preExistingFieldMask.length>0&&(mappedFieldsFromPreExisting=preExistingFieldMask.map(field=>generationConfigFields.includes(field)?`generationConfig.${field}`:field));let finalMaskParts=[];generatedMaskFromBidi&&finalMaskParts.push(generatedMaskFromBidi),mappedFieldsFromPreExisting.length>0&&finalMaskParts.push(...mappedFieldsFromPreExisting),finalMaskParts.length>0?requestDict.fieldMask=finalMaskParts.join(","):delete requestDict.fieldMask}else delete requestDict.fieldMask}else preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0?requestDict.fieldMask=preExistingFieldMask.join(","):delete requestDict.fieldMask;return requestDict}var Tokens=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let body=createAuthTokenParametersToMldev(this.apiClient,params);path2=formatMap("auth_tokens",body._url),queryParams=body._query,delete body.config,delete body._url,delete body._query;let transformedBody=convertBidiSetupToTokenSetup(body,params.config);return response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(transformedBody),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}};function deleteDocumentConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteDocumentConfigToMldev(fromConfig,toObject),toObject}function getDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listDocumentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listDocumentsParametersToMldev(fromObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listDocumentsConfigToMldev(fromConfig,toObject),toObject}function listDocumentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromDocuments=getValueByPath(fromObject,["documents"]);if(fromDocuments!=null){let transformedList=fromDocuments;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["documents"],transformedList)}return toObject}var Documents=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async params=>new Pager(PagedItem.PAGED_ITEM_DOCUMENTS,x=>this.listInternal({parent:params.parent,config:x.config}),await this.listInternal(params),params)}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getDocumentParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteDocumentParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listDocumentsParametersToMldev(params);return path2=formatMap("{parent}/documents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listDocumentsResponseFromMldev(apiResponse),typedResp=new ListDocumentsResponse;return Object.assign(typedResp,resp),typedResp})}}};var FileSearchStores=class extends BaseModule{constructor(apiClient,documents=new Documents(apiClient)){super(),this.apiClient=apiClient,this.documents=documents,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,x=>this.listInternal(x),await this.listInternal(params),params)}async uploadToFileSearchStore(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName,params.file,params.config)}async downloadMedia(uri,config){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let parsedUri=new URL(uri,"http://dummy.com"),pathname=parsedUri.pathname;if(pathname.startsWith("/")&&(pathname=pathname.slice(1)),!pathname.includes("/media/"))throw new Error(`Invalid uri format: ${uri}. Expected to contain /media/`);let queryParams={};parsedUri.searchParams.forEach((value,key)=>{queryParams[key]=value}),queryParams.alt="media";let httpOptions=Object.assign({},config?.httpOptions),response=await this.apiClient.request({path:pathname,httpMethod:"GET",queryParams,httpOptions});if(response instanceof HttpResponse){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}else throw new Error("Unexpected response type from downloadMedia")}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileSearchStoreParametersToMldev(this.apiClient,params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileSearchStoreParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileSearchStoreParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFileSearchStoresParametersToMldev(params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listFileSearchStoresResponseFromMldev(apiResponse),typedResp=new ListFileSearchStoresResponse;return Object.assign(typedResp,resp),typedResp})}}async uploadToFileSearchStoreInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=uploadToFileSearchStoreParametersToMldev(params);return path2=formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=uploadToFileSearchStoreResumableResponseFromMldev(apiResponse),typedResp=new UploadToFileSearchStoreResumableResponse;return Object.assign(typedResp,resp),typedResp})}}async importFile(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=importFileParametersToMldev(params);return path2=formatMap("{file_search_store_name}:importFile",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=importFileOperationFromMldev(apiResponse),typedResp=new ImportFileOperation;return Object.assign(typedResp,resp),typedResp})}}};function isDeno(){return"Deno"in globalThis}var envMemo;function env(){var _a2,_b,_c,_d,_e,_f;if(envMemo)return envMemo;let globals=globalThis,envObject={};return isDeno()?envObject=(_d=(_c=(_b=(_a2=globals.Deno)===null||_a2===void 0?void 0:_a2.env)===null||_b===void 0?void 0:_b.toObject)===null||_c===void 0?void 0:_c.call(_b))!==null&&_d!==void 0?_d:{}:envObject=(_f=(_e=globals.process)===null||_e===void 0?void 0:_e.env)!==null&&_f!==void 0?_f:{},envMemo=envObject,envMemo}function fillGlobals(options){var _a2,_b;let clone=Object.assign({},options),envVars=env();return typeof envVars.GOOGLE_GENAI_API_VERSION<"u"&&((_a2=clone.api_version)!==null&&_a2!==void 0||(clone.api_version=envVars.GOOGLE_GENAI_API_VERSION)),typeof envVars.GOOGLE_GENAI_USER_PROJECT<"u"&&((_b=clone.user_project)!==null&&_b!==void 0||(clone.user_project=envVars.GOOGLE_GENAI_USER_PROJECT)),clone}var GoogleGenAISecurityProvider=class{constructor(options){this.options=options}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(url){return securityFromHeaders(await this.options.getAuthHeaders(url))}},GoogleGenAIAuthHook=class{beforeCreateRequest(_hookCtx,input){return Object.assign(Object.assign({},input),{url:decodeSDKLevelAPIVersionPath(input.url)})}async beforeRequest(hookCtx,request){if(applyDefaultHeaders(request.headers,getStaticDefaultHeaders(hookCtx.security_source)),applyUserProject(hookCtx,request.headers),hasAuthHeaders(request.headers))return request;let security=await resolveSecurity$1(hookCtx.security_source,request.url);return applyDefaultHeaders(request.headers,security?.default_headers),applyAuth(request.headers,security),request}};function decodeSDKLevelAPIVersionPath(url){let[,apiVersion,...rest]=url.pathname.split("/");if(!apiVersion)return url;let decodedAPIVersion=decodeURIComponent(apiVersion);if(!decodedAPIVersion.includes("/"))return url;let nextURL=new URL(url);return nextURL.pathname=`/${decodedAPIVersion}/${rest.join("/")}`,nextURL}async function resolveSecurity$1(securitySource,requestURL){if(isSecurityResolver(securitySource))return securitySource.resolveGoogleGenAISecurity(requestURL);let security=typeof securitySource=="function"?await securitySource():securitySource;return isSecurity(security)?withEnvSecurity(security):withEnvSecurity(void 0)}function getStaticDefaultHeaders(securitySource){var _a2,_b;if(isSecurityResolver(securitySource))return(_b=(_a2=securitySource.getDefaultHeaders)===null||_a2===void 0?void 0:_a2.call(securitySource))!==null&&_b!==void 0?_b:securitySource.defaultHeaders;if(isSecurity(securitySource))return securitySource.default_headers}function withEnvSecurity(security){var _a2,_b;let envVars=env(),nextSecurity=Object.assign(Object.assign({},security),{api_key:(_a2=security?.api_key)!==null&&_a2!==void 0?_a2:envVars.GOOGLE_GENAI_API_KEY,access_token:(_b=security?.access_token)!==null&&_b!==void 0?_b:envVars.GOOGLE_GENAI_ACCESS_TOKEN});return hasSecurityValue(nextSecurity)?nextSecurity:void 0}function securityFromHeaders(headers){var _a2,_b;let defaultHeaders={};for(let[key,value]of headers){let lowerKey=key.toLowerCase();lowerKey!=="authorization"&&lowerKey!=="x-goog-api-key"&&(defaultHeaders[key]=value)}let security={access_token:(_a2=headers.get("authorization"))!==null&&_a2!==void 0?_a2:void 0,api_key:(_b=headers.get("x-goog-api-key"))!==null&&_b!==void 0?_b:void 0,default_headers:Object.keys(defaultHeaders).length?defaultHeaders:void 0};return hasSecurityValue(security)?security:void 0}function applyDefaultHeaders(target,source){if(source)for(let[key,value]of new Headers(source))target.get(key)===null&&target.set(key,value)}function applyUserProject(hookCtx,headers){hookCtx.options.user_project!==void 0&&headers.get("x-goog-user-project")===null&&headers.set("x-goog-user-project",hookCtx.options.user_project)}function applyAuth(headers,security){if(security){if(security.api_key){headers.set("x-goog-api-key",security.api_key);return}security.access_token&&headers.set("Authorization",bearer(security.access_token))}}function hasAuthHeaders(headers){return headers.get("authorization")!==null||headers.get("x-goog-api-key")!==null}function bearer(token){return token.slice(0,7).toLowerCase()==="bearer "?token:`Bearer ${token}`}function isSecurity(value){return typeof value=="object"&&value!==null}function isSecurityResolver(value){return typeof value=="object"&&value!==null&&"resolveGoogleGenAISecurity"in value&&typeof value.resolveGoogleGenAISecurity=="function"}function hasSecurityValue(security){return security.api_key!==void 0||security.access_token!==void 0||security.default_headers!==void 0}var HTTPClientError=class extends Error{constructor(message,opts){let msg=message;opts?.cause&&(msg+=`: ${opts.cause}`),super(msg,opts),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=opts?.cause)}},UnexpectedClientError=class extends HTTPClientError{constructor(){super(...arguments),this.name="UnexpectedClientError"}},InvalidRequestError=class extends HTTPClientError{constructor(){super(...arguments),this.name="InvalidRequestError"}},RequestAbortedError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestAbortedError"}},RequestTimeoutError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestTimeoutError"}},ConnectionError=class extends HTTPClientError{constructor(){super(...arguments),this.name="ConnectionError"}};var GoogleGenAiError=class extends Error{constructor(message,httpMeta){var _a2,_b,_c,_d;super(message),this.statusCode=(_a2=httpMeta?.response)===null||_a2===void 0?void 0:_a2.status,this.body=(_b=httpMeta?.body)!==null&&_b!==void 0?_b:"",this.headers=(_c=httpMeta?.response)===null||_c===void 0?void 0:_c.headers,this.contentType=((_d=httpMeta?.response)===null||_d===void 0?void 0:_d.headers.get("content-type"))||"",this.rawResponse=httpMeta?.response,this.name="GoogleGenAiError"}};var GeminiNextGenAPIClientError=class extends Error{},APIError=class _APIError extends GeminiNextGenAPIClientError{constructor(status,error,message,headers){super(_APIError.makeMessage(status,error,message)),this.status=status,this.headers=headers,this.error=error,this.statusCode=status,this.body=stringifyErrorBody(error),this.contentType=headers?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(status,error,message){var _a2;let errorMessage=error&&isPlainObject$2(error)&&typeof error.message=="string"?error.message:void 0,errorBody=stringifyErrorBody(error),msg=(_a2=errorMessage??message)!==null&&_a2!==void 0?_a2:errorBody||"An error occurred";return`${status?`${status} `:""}${msg}`}static generate(status,errorResponse,message,headers){return!status||!headers?new APIConnectionError({message,cause:errorResponse instanceof Error?errorResponse:void 0}):status===400?new BadRequestError(status,errorResponse,message,headers):status===401?new AuthenticationError(status,errorResponse,message,headers):status===403?new PermissionDeniedError(status,errorResponse,message,headers):status===404?new NotFoundError(status,errorResponse,message,headers):status===409?new ConflictError(status,errorResponse,message,headers):status===422?new UnprocessableEntityError(status,errorResponse,message,headers):status===429?new RateLimitError(status,errorResponse,message,headers):status>=500?new InternalServerError(status,errorResponse,message,headers):new _APIError(status,errorResponse,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),this.cause=cause}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{};function wrapSDKError(error){return isCompatAPIErrorInstance(error)?error:error instanceof GoogleGenAiError?wrapAPIError(error):error instanceof HTTPClientError?wrapHTTPClientError(error):error}function wrapAPIError(error){let errorPayload=getErrorPayload(error),wrapped=APIError.generate(error.statusCode,errorPayload,error.message,error.headers);return defineReadonly(wrapped,"body",error.body),defineReadonly(wrapped,"contentType",error.contentType),defineReadonly(wrapped,"rawResponse",error.rawResponse),defineReadonly(wrapped,"statusCode",error.statusCode),defineReadonly(wrapped,"cause",error),wrapped}function wrapHTTPClientError(error){return error instanceof RequestTimeoutError?new APIConnectionTimeoutError({message:error.message}):error instanceof RequestAbortedError?new APIUserAbortError({message:error.message}):error instanceof ConnectionError?new APIConnectionError({message:error.message,cause:error}):new APIConnectionError({message:error.message,cause:error})}function getErrorPayload(error){let data=getObjectProperty(error,"data$");if(data&&typeof data=="object")return data;try{let parsed=JSON.parse(error.body);if(parsed&&typeof parsed=="object")return parsed}catch{}let dataError=getObjectProperty(error,"error");return dataError&&typeof dataError=="object"?dataError:void 0}function getObjectProperty(value,key){return value&&typeof value=="object"?value[key]:void 0}function stringifyErrorBody(error){if(!error)return"";try{return JSON.stringify(error)}catch{return String(error)}}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isCompatAPIErrorInstance(value){return typeof value=="object"&&value!==null?APIError.prototype.isPrototypeOf(value):!1}function defineReadonly(target,key,value){Object.defineProperty(target,key,{configurable:!0,enumerable:!0,value,writable:!1})}function initHooks(hooks){let googleGenAIAuthHook=new GoogleGenAIAuthHook;hooks.registerBeforeCreateRequestHook(googleGenAIAuthHook),hooks.registerBeforeRequestHook(googleGenAIAuthHook)}var SDKHooks=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let presetHooks=[];for(let hook of presetHooks)"sdkInit"in hook&&this.registerSDKInitHook(hook),"beforeCreateRequest"in hook&&this.registerBeforeCreateRequestHook(hook),"beforeRequest"in hook&&this.registerBeforeRequestHook(hook),"afterSuccess"in hook&&this.registerAfterSuccessHook(hook),"afterError"in hook&&this.registerAfterErrorHook(hook);initHooks(this)}registerSDKInitHook(hook){this.sdkInitHooks.push(hook)}registerBeforeCreateRequestHook(hook){this.beforeCreateRequestHooks.push(hook)}registerBeforeRequestHook(hook){this.beforeRequestHooks.push(hook)}registerAfterSuccessHook(hook){this.afterSuccessHooks.push(hook)}registerAfterErrorHook(hook){this.afterErrorHooks.push(hook)}sdkInit(opts){return this.sdkInitHooks.reduce((opts2,hook)=>hook.sdkInit(opts2),opts)}beforeCreateRequest(hookCtx,input){let inp=input;for(let hook of this.beforeCreateRequestHooks)inp=hook.beforeCreateRequest(hookCtx,inp);return inp}async beforeRequest(hookCtx,request){let req=request;for(let hook of this.beforeRequestHooks)req=await hook.beforeRequest(hookCtx,req);return req}async afterSuccess(hookCtx,response){let res=response;for(let hook of this.afterSuccessHooks)res=await hook.afterSuccess(hookCtx,res);return res}async afterError(hookCtx,response,error){let res=response,err=error;for(let hook of this.afterErrorHooks){let result=await hook.afterError(hookCtx,res,err);res=result.response,err=result.error}return{response:res,error:err}}};function OK(value){return{ok:!0,value}}function ERR(error){return{ok:!1,error}}function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}function stringToBytes(str){return new TextEncoder().encode(str)}function stringToBase64(str){return bytesToBase64(stringToBytes(str))}var hasOwn=Object.prototype.hasOwnProperty;function pathToFunc(pathPattern,options){let paramRE=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(params={}){return pathPattern.replace(paramRE,function(_,placeholder){if(!hasOwn.call(params,placeholder))throw new Error(`Parameter '${placeholder}' is required`);let value=params[placeholder];if(typeof value!="string"&&typeof value!="number")throw new Error(`Parameter '${placeholder}' must be a string or number`);return`${value}`}).replace(/^\/+/,"")}}var ServerList=["https://generativelanguage.googleapis.com"];function serverURLFromOptions(options){var _a2;let serverURL=options.server_url,params={};if(!serverURL){let serverIdx=(_a2=options.server_idx)!==null&&_a2!==void 0?_a2:0;if(serverIdx<0||serverIdx>=ServerList.length)throw new Error(`Invalid server index ${serverIdx}`);serverURL=ServerList[serverIdx]||""}let u=pathToFunc(serverURL)(params);return new URL(u)}var SDK_METADATA={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function combineSignals(...signals){let filtered=[];for(let signal of signals)signal&&filtered.push(signal);switch(filtered.length){case 0:case 1:return filtered[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(filtered):abortSignalAny(filtered)}}function abortSignalAny(signals){let controller=new AbortController,result=controller.signal;if(!signals.length)return controller.signal;if(signals.length===1)return signals[0]||controller.signal;for(let signal of signals)if(signal.aborted)return signal;function abort(){controller.abort(this.reason),clean()}let signalRefs=[];function clean(){for(let signalRef of signalRefs){let signal=signalRef.deref();signal&&signal.removeEventListener("abort",abort)}}for(let signal of signals)signalRefs.push(new WeakRef(signal)),signal.addEventListener("abort",abort);return result}function compactMap(values){let out={};for(let[k,v]of Object.entries(values))typeof v<"u"&&(out[k]=v);return out}function isPlainObject$1(value){if(value===null||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;try{return Object.getPrototypeOf(proto)===null}catch{return!1}}function formEncoder(sep){return(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encodeValue=v=>encodeString(serializeValue(v)),encodedSep=encodeString(sep);return pairs.forEach(([pk,pv])=>{var _a2,_b;let tmp="",encValue=null;pv!=null&&(Array.isArray(pv)?encValue=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(encodedSep):isPlainObject$1(pv)?encValue=(_b=mapDefinedEntries(Object.entries(pv),([k,v])=>`${encodeString(k)}${encodedSep}${encodeValue(v)}`))===null||_b===void 0?void 0:_b.join(encodedSep):encValue=`${encodeValue(pv)}`,encValue!=null&&(tmp=`${encodeString(pk)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");function encodeJSON(key,value,options){if(typeof value>"u")return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encVal=encodeString(JSON.stringify(value,jsonReplacer));return options?.explode?encVal:`${encodeString(key)}=${encVal}`}var encodeSimple=(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encodeValue=v=>encodeString(serializeValue(v));return pairs.forEach(([pk,pv])=>{var _a2;let tmp="";if(pv!=null){if(Array.isArray(pv))tmp=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(",");else if(isPlainObject$1(pv)){let mapped=mapDefinedEntries(Object.entries(pv),([k,v])=>`,${encodeString(k)},${encodeValue(v)}`);tmp=mapped?.join("").slice(1)}else tmp=`${options?.explode&&isPlainObject$1(value)?`${pk}=`:""}${encodeValue(pv)}`;out+=tmp?`,${tmp}`:""}}),out.slice(1)};function explode(key,value){return Array.isArray(value)?value.map(v=>[key,v]):isPlainObject$1(value)?Object.entries(value??{}).map(([k,v])=>[k,v]):[[key,value]]}function serializeValue(value){return value==null?"":value instanceof Date?value.toISOString():value instanceof Uint8Array?bytesToBase64(value):typeof value=="object"?JSON.stringify(value,jsonReplacer):`${value}`}function jsonReplacer(_,value){return value instanceof Uint8Array?bytesToBase64(value):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m=mapper(v);return m==null||acc.push(m),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m=mapper([k,v]);m!=null&&acc.push(m)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f){return function(values,options){var _a2,_b,_c;let opts=Object.assign(Object.assign({},options),{explode:(_a2=options?.explode)!==null&&_a2!==void 0?_a2:!0,charEncoding:(_b=options?.charEncoding)!==null&&_b!==void 0?_b:"percent"}),allowEmptySet=new Set((_c=options?.allowEmptyValue)!==null&&_c!==void 0?_c:[]),encoded=Object.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var DEFAULT_FETCHER=(input,init)=>init==null?fetch(input):fetch(input,init),HTTPClient=class _HTTPClient{constructor(options={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=options,this.fetcher=options.fetcher||DEFAULT_FETCHER}async request(request){let req=request;for(let hook of this.requestHooks){let nextRequest=await hook(req);nextRequest&&(req=nextRequest)}try{let res=await this.fetcher(req);for(let hook of this.responseHooks)await hook(res,req);return res}catch(err){for(let hook of this.requestErrorHooks)await hook(err,req);throw err}}addHook(...args){if(args[0]==="beforeRequest")this.requestHooks.push(args[1]);else if(args[0]==="requestError")this.requestErrorHooks.push(args[1]);else if(args[0]==="response")this.responseHooks.push(args[1]);else throw new Error(`Invalid hook type: ${args[0]}`);return this}removeHook(...args){let target;if(args[0]==="beforeRequest")target=this.requestHooks;else if(args[0]==="requestError")target=this.requestErrorHooks;else if(args[0]==="response")target=this.responseHooks;else throw new Error(`Invalid hook type: ${args[0]}`);let index=target.findIndex(v=>v===args[1]);return index>=0&&target.splice(index,1),this}clone(){let child=new _HTTPClient(this.options);return child.requestHooks=this.requestHooks.slice(),child.requestErrorHooks=this.requestErrorHooks.slice(),child.responseHooks=this.responseHooks.slice(),child}},mediaParamSeparator=/\s*;\s*/g;function matchContentType(response,pattern){var _a2;if(pattern==="*")return!0;let contentType=((_a2=response.headers.get("content-type"))===null||_a2===void 0?void 0:_a2.trim())||"application/octet-stream";contentType=contentType.toLowerCase();let wantParts=pattern.toLowerCase().trim().split(mediaParamSeparator),[wantType="",...wantParams]=wantParts;if(wantType.split("/").length!==2)return!1;let gotParts=contentType.split(mediaParamSeparator),[gotType="",...gotParams]=gotParts,[type="",subtype=""]=gotType.split("/");if(!type||!subtype||wantType!=="*/*"&&gotType!==wantType&&`${type}/*`!==wantType&&`*/${subtype}`!==wantType||gotParams.length<wantParams.length)return!1;let params=new Set(gotParams);for(let wantParam of wantParams)if(!params.has(wantParam))return!1;return!0}var codeRangeRE$1=new RegExp("^[0-9]xx$","i");function matchStatusCode(response,codes){let actual=`${response.status}`,expectedCodes=Array.isArray(codes)?codes:[codes];return expectedCodes.length?expectedCodes.some(ec=>{let code=`${ec}`;if(code==="default")return!0;if(!codeRangeRE$1.test(`${code}`))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily}):!1}function matchResponse(response,code,contentTypePattern){return matchStatusCode(response,code)&&matchContentType(response,contentTypePattern)}function isConnectionError(err){if(typeof err!="object"||err==null)return!1;let isBrowserErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("failed to fetch"),isNodeErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("fetch failed"),isBunErr="name"in err&&err.name==="ConnectionError",isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnreset";return isBrowserErr||isNodeErr||isGenericErr||isBunErr}function isTimeoutError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="TimeoutError",isLegacyNative="code"in err&&err.code===23,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function isAbortError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="AbortError",isLegacyNative="code"in err&&err.code===20,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}var defaultBackoff={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},PermanentError=class _PermanentError extends Error{constructor(message,options){let msg=message;options?.cause&&(msg+=`: ${options.cause}`),super(msg,options),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=options?.cause),Object.setPrototypeOf(this,_PermanentError.prototype)}},TemporaryError=class _TemporaryError extends Error{constructor(message,response){super(message),this.response=response,this.name="TemporaryError",Object.setPrototypeOf(this,_TemporaryError.prototype)}};async function retry(fetchFn,options){var _a2;switch(options.config.strategy){case"backoff":return retryBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),(_a2=options.config.backoff)!==null&&_a2!==void 0?_a2:defaultBackoff);case"attempt-count-backoff":return retryAttemptCountBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),Object.assign(Object.assign({},defaultBackoff),options.config.backoff),options.config);default:return await fetchFn(0)}}function wrapFetcher(fn,options){return async attempt=>{try{let res=await fn(attempt);if(isRetryableResponse(res,options.statusCodes))throw new TemporaryError("Response failed with retryable status code",res);return res}catch(err){throw err instanceof TemporaryError||options.retryConnectionErrors&&(isTimeoutError(err)||isConnectionError(err))?err:new PermanentError("Permanent error",{cause:err})}}}var codeRangeRE=new RegExp("^[0-9]xx$","i");function isRetryableResponse(res,statusCodes){let actual=`${res.status}`;return statusCodes.some(code=>{if(!codeRangeRE.test(code))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily})}async function retryBackoff(fn,strategy){let{maxElapsedTime,initialInterval,exponent,maxInterval}=strategy,start=Date.now(),x=0;for(;;)try{return await fn(x)}catch(err){if(err instanceof PermanentError)throw err.cause;if(Date.now()-start>maxElapsedTime){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=initialInterval*Math.pow(x,exponent)+Math.random()*1e3);let d=Math.min(retryInterval,maxInterval);await delay(d),x++}}async function retryAttemptCountBackoff(fn,strategy,config){let attempt=0;for(;;)try{return await fn(attempt)}catch(err){if(err instanceof PermanentError)throw err.cause;if(attempt>=config.maxRetries){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=strategy.initialInterval*Math.pow(strategy.exponent,attempt)*(1-Math.random()*.25));let d=Math.min(retryInterval,strategy.maxInterval);await delay(d),attempt++}}function retryIntervalFromResponse(res){let retryAfterMsVal=res.headers.get("retry-after-ms");if(retryAfterMsVal){let parsedMs=Number(retryAfterMsVal);if(Number.isFinite(parsedMs)&&parsedMs>=0)return parsedMs}let retryVal=res.headers.get("retry-after")||"";if(!retryVal)return 0;let parsedNumber=Number(retryVal);if(Number.isInteger(parsedNumber))return parsedNumber*1e3;let parsedDate=Date.parse(retryVal);if(Number.isInteger(parsedDate)){let deltaMS=parsedDate-Date.now();return deltaMS>0?Math.ceil(deltaMS):0}return 0}async function delay(delay2){return new Promise(resolve=>setTimeout(resolve,delay2))}var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",ClientSDK=class{constructor(options={}){let opt=options;typeof opt=="object"&&opt!=null&&"hooks"in opt&&opt.hooks instanceof SDKHooks?this._hooks=opt.hooks:this._hooks=new SDKHooks;let defaultHttpClient=new HTTPClient;options.http_client=options.http_client||defaultHttpClient,options=this._hooks.sdkInit(options);let url=serverURLFromOptions(options);url&&(url.pathname=url.pathname.replace(/\/+$/,"")+"/"),this._baseURL=url,this._httpClient=options.http_client||defaultHttpClient,this._options=Object.assign(Object.assign({},fillGlobals(options)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&env().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(context,conf,options){var _a2,_b,_c,_d,_e;let{method,path:path2,query,headers:opHeaders,security}=conf,base=(_a2=conf.baseURL)!==null&&_a2!==void 0?_a2:this._baseURL;if(!base)return ERR(new InvalidRequestError("No base URL provided for operation"));let baseURL=new URL(base),reqURL;path2?(baseURL.pathname=baseURL.pathname.replace(/\/+$/,"")+"/",reqURL=new URL(path2,baseURL),!reqURL.search&&baseURL.search&&(reqURL.search=baseURL.search)):reqURL=baseURL,reqURL.hash="";let mergeQuery=(current,additions)=>{if(!additions)return current;let additionKeys=new Set(additions.split("&").filter(pair=>pair!=="").map(pair=>{var _a3;return(_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:""}));return[...current.split("&").filter(pair=>{var _a3;return pair!==""&&!additionKeys.has((_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:"")}),additions].join("&")},encodeQueryRecord=record=>Object.entries(record).map(([k,v])=>{if(v==null)return;let value=isPlainObject$1(v)?JSON.stringify(v):v;return encodeForm(k,value,{explode:Array.isArray(value),charEncoding:"percent"})}).filter(pair=>typeof pair<"u").join("&"),finalQuery=[query||"",encodeQueryRecord(options?.extra_query||{}),encodeQueryRecord(security?.queryParams||{})].reduce(mergeQuery,reqURL.search.slice(1));finalQuery&&(reqURL.search=`?${finalQuery}`);let headers=new Headers(opHeaders),username=security?.basic.username,password=security?.basic.password;if(username!=null||password!=null){let encoded=stringToBase64([username||"",password||""].join(":"));headers.set("Authorization",`Basic ${encoded}`)}let securityHeaders=new Headers(security?.headers||{});for(let[k,v]of securityHeaders)headers.set(k,v);let cookie=headers.get("cookie")||"";for(let[k,v]of Object.entries(security?.cookies||{}))cookie+=`; ${k}=${v}`;cookie=cookie.startsWith("; ")?cookie.slice(2):cookie,headers.set("cookie",cookie);let userHeaders=new Headers((_b=options?.headers)!==null&&_b!==void 0?_b:(_c=options?.fetch_options)===null||_c===void 0?void 0:_c.headers);for(let[k,v]of userHeaders)headers.set(k,v);isBrowserLike||headers.set((_d=conf.uaHeader)!==null&&_d!==void 0?_d:"user-agent",(_e=conf.userAgent)!==null&&_e!==void 0?_e:SDK_METADATA.userAgent);let reqBody=conf.body,extraBody=Object.fromEntries(Object.entries(options?.extra_body||{}).filter(([,v])=>typeof v<"u"));if(Object.keys(extraBody).length>0){let contentType=new Headers(opHeaders).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(contentType)||typeof reqBody!="string"&&reqBody!=null)return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));let parsedBody;try{parsedBody=reqBody?JSON.parse(reqBody):{}}catch(err){return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies",{cause:err}))}if(!isPlainObject$1(parsedBody))return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));reqBody=JSON.stringify(Object.assign(Object.assign({},parsedBody),extraBody)),headers.delete("content-length")}let fetchOptions=Object.assign(Object.assign({},options?.fetch_options),options);!fetchOptions?.signal&&conf.timeout_ms!=null&&conf.timeout_ms>0&&(context.timeout_ms=conf.timeout_ms),conf.body instanceof ReadableStream&&Object.assign(fetchOptions,{duplex:"half"});let input;try{input=this._hooks.beforeCreateRequest(context,{url:reqURL,options:Object.assign(Object.assign({},fetchOptions),{body:reqBody??null,headers,method})})}catch(err){return ERR(new UnexpectedClientError("Create request hook failed to execute",{cause:err}))}return OK(new Request(input.url,input.options))}async _do(request,options){let{context,isErrorStatusCode}=options,timeout_ms=context.timeout_ms;return retry(async()=>{var _a2;let cloned=request.clone(),attempt=cloned;if(timeout_ms!=null&&timeout_ms>0){let timeoutSignal=AbortSignal.timeout(timeout_ms),combined=(_a2=combineSignals(cloned.signal,timeoutSignal))!==null&&_a2!==void 0?_a2:timeoutSignal;attempt=new Request(cloned,{signal:combined})}let req=await this._hooks.beforeRequest(context,attempt);await logRequest(this._logger,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log request:",e)});let response=await this._httpClient.request(req);try{if(isErrorStatusCode(response.status)){let result=await this._hooks.afterError(context,response,null);if(result.error)throw result.error;response=result.response||response}else response=await this._hooks.afterSuccess(context,response)}finally{await logResponse(this._logger,response,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log response:",e)})}return response},{config:options.retryConfig,statusCodes:options.retryCodes}).then(r=>OK(r),err=>{switch(!0){case isAbortError(err):return ERR(new RequestAbortedError("Request aborted by client",{cause:err}));case isTimeoutError(err):return ERR(new RequestTimeoutError("Request timed out",{cause:err}));case isConnectionError(err):return ERR(new ConnectionError("Unable to make request",{cause:err}));default:return ERR(new UnexpectedClientError("Unexpected HTTP client error",{cause:err}))}})}},jsonLikeContentTypeRE=/^(application|text)\/([^+]+\+)*json.*/,jsonlLikeContentTypeRE=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function logRequest(logger,req){if(!logger)return;let contentType=req.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`> Request: ${req.method} ${req.url}`),logger.group("Headers:");for(let[k,v]of req.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case jsonLikeContentTypeRE.test(ct):logger.log(await req.clone().json());break;case ct.startsWith("text/"):logger.log(await req.clone().text());break;case ct==="multipart/form-data":{let body=await req.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}async function logResponse(logger,res,req){if(!logger)return;let contentType=res.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`< Response: ${req.method} ${req.url}`),logger.log("Status Code:",res.status,res.statusText),logger.group("Headers:");for(let[k,v]of res.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case(matchContentType(res,"application/json")||jsonLikeContentTypeRE.test(ct)&&!jsonlLikeContentTypeRE.test(ct)):logger.log(await res.clone().json());break;case(matchContentType(res,"application/jsonl")||jsonlLikeContentTypeRE.test(ct)):case matchContentType(res,"text/event-stream"):logger.log(`<${contentType}>`);break;case matchContentType(res,"text/*"):logger.log(await res.clone().text());break;case matchContentType(res,"multipart/form-data"):{let body=await res.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}var GoogleGenAiDefaultError=class extends GoogleGenAiError{constructor(message,httpMeta){message&&(message+=": "),message+=`Status ${httpMeta.response.status}`;let contentType=httpMeta.response.headers.get("content-type")||'""';contentType!=="application/json"&&(message+=` Content-Type ${contentType.includes(" ")?`"${contentType}"`:contentType}`);let body=httpMeta.body||'""';message+=body.length>100?`
`:". ";let bodyDisplay=body;if(body.length>1e4){let truncated=body.substring(0,1e4),remaining=body.length-1e4;bodyDisplay=`${truncated}...and ${remaining} more chars`}message+=`Body: ${bodyDisplay}`,message=message.trim(),super(message,httpMeta),this.name="GoogleGenAiDefaultError"}};function tryParseJson(s){try{return JSON.parse(s)}catch{return s}}function wrapEventStreamResponse(body,opts={}){var _a2,_b;let flattened=opts.flattened===!0,sentinel=(_a2=opts.sentinel)!==null&&_a2!==void 0?_a2:"";return new Stream(body,rawEvent=>sentinel!==""&&rawEvent.data===sentinel?{done:!0,value:void 0}:flattened?{done:!1,value:rawEvent.data==null?void 0:tryParseJson(rawEvent.data)}:{done:!1,value:Object.assign(Object.assign({},rawEvent),{data:rawEvent.data==null?rawEvent.data:tryParseJson(rawEvent.data)})},{dataRequired:(_b=opts.dataRequired)!==null&&_b!==void 0?_b:!0})}var Stream=class extends ReadableStream{constructor(responseBody,parse,opts){var _a2;let upstream=responseBody.getReader(),buffer=new Uint8Array(4096),bufferLen=0,searchStart=0,state={eventId:void 0},dataRequired=(_a2=opts?.dataRequired)!==null&&_a2!==void 0?_a2:!0;super({async pull(downstream){try{for(;;){let match2=findBoundary(buffer,bufferLen,searchStart);if(!match2){searchStart=Math.max(0,bufferLen-MAX_BOUNDARY_LEN+1);let chunk=await upstream.read();if(chunk.done)return downstream.close();if(bufferLen+chunk.value.length>buffer.length){let grown=new Uint8Array(Math.max(buffer.length*2,bufferLen+chunk.value.length));grown.set(buffer.subarray(0,bufferLen)),buffer=grown}buffer.set(chunk.value,bufferLen),bufferLen+=chunk.value.length;continue}let message=buffer.slice(0,match2.index);if(buffer.copyWithin(0,match2.index+match2.length,bufferLen),bufferLen-=match2.index+match2.length,buffer.length>4096&&bufferLen<=buffer.length>>2){let shrunk=new Uint8Array(Math.max(4096,bufferLen*2));shrunk.set(buffer.subarray(0,bufferLen)),buffer=shrunk}searchStart=0;let item=parseMessage(message,parse,state,dataRequired);if(item&&!item.done)return downstream.enqueue(item.value);if(item?.done)return await upstream.cancel("done"),downstream.close()}}catch(e){downstream.error(e),await upstream.cancel(e)}},cancel:reason=>upstream.cancel(reason)})}[Symbol.asyncIterator](options){let fn=ReadableStream.prototype[Symbol.asyncIterator];if(typeof fn=="function")return fn.call(this,options);let reader=this.getReader(),iterator={next:async()=>{let r=await reader.read();return r.done?(reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r.value}},throw:async e=>(await reader.cancel(e),reader.releaseLock(),{done:!0,value:void 0}),return:async()=>(await reader.cancel("done"),reader.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},asyncDispose=Symbol.asyncDispose;return asyncDispose&&(iterator[asyncDispose]=async()=>{var _a2;await((_a2=iterator.return)===null||_a2===void 0?void 0:_a2.call(iterator))}),iterator}values(options){return this[Symbol.asyncIterator](options)}},CR=13,LF=10,BOUNDARIES=[[CR,LF,CR,LF],[CR,LF,CR],[CR,LF,LF],[CR,CR,LF],[LF,CR,LF],[CR,CR],[LF,CR],[LF,LF]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m,b)=>Math.max(m,b.length),0);function findBoundary(buf,len,from){for(let i=from;i<len;i++)if(!(buf[i]!==CR&&buf[i]!==LF))for(let boundary of BOUNDARIES){if(i+boundary.length>len)continue;let match2=!0;for(let j=0;j<boundary.length;j++)if(buf[i+j]!==boundary[j]){match2=!1;break}if(match2)return{index:i,length:boundary.length}}return null}function parseMessage(chunk,parse,state,dataRequired){let lines=new TextDecoder().decode(chunk).split(/\r\n|\r|\n/),dataLines=[],ret={},ignore=!0;for(let line of lines){if(!line||line.startsWith(":"))continue;ignore=!1;let i=line.indexOf(":"),field=line,value="";i>0&&(field=line.slice(0,i),value=line[i+1]===" "?line.slice(i+2):line.slice(i+1)),field==="data"?dataLines.push(value):field==="event"?ret.event=value:field==="id"&&!value.includes("\0")?state.eventId=value:field==="retry"&&/^\d+$/.test(value)&&(ret.retry=Number(value))}if(!ignore){if(ret.id=state.eventId,dataLines.length)ret.data=dataLines.join(`
`);else if(dataRequired)return;return parse(ret)}}var DEFAULT_CONTENT_TYPES={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jsonErr(codes,errorClass,options){return Object.assign(Object.assign({},options),{err:!0,enc:"json",codes,errorClass})}function json(codes,options){return Object.assign(Object.assign({},options),{enc:"json",codes})}function sse(codes,sse2,options){return Object.assign(Object.assign(Object.assign({},options),{enc:"sse",codes}),sse2?{sse:sse2}:{})}function nil(codes,options){return Object.assign(Object.assign({},options),{enc:"nil",codes})}function fail(codes){return{enc:"fail",codes}}function match(...matchers){return async function(response,request,options){let raw,matcher;for(let match2 of matchers){let{codes}=match2,ctpattern="ctype"in match2?match2.ctype:DEFAULT_CONTENT_TYPES[match2.enc];if(ctpattern&&matchResponse(response,codes,ctpattern)){matcher=match2;break}else if(!ctpattern&&matchStatusCode(response,codes)){matcher=match2;break}}if(!matcher)return[{ok:!1,error:new GoogleGenAiDefaultError("Unexpected Status or Content-Type",{response,request,body:await response.text().catch(()=>"")})},raw];let encoding=matcher.enc,body="";switch(encoding){case"json":body=await response.text();try{raw=JSON.parse(body)}catch(err){if(!("err"in matcher))throw err;raw=body}break;case"jsonl":raw=response.body;break;case"bytes":raw=new Uint8Array(await response.arrayBuffer());break;case"stream":raw=response.body;break;case"text":body=await response.text(),raw=body;break;case"sse":if(response.body){let sseOpts="sse"in matcher&&matcher.sse||{};raw=wrapEventStreamResponse(response.body,sseOpts)}else raw=null;break;case"nil":body=await response.text(),raw=void 0;break;case"fail":body=await response.text(),raw=body;break;default:throw new Error(`Unsupported response type: ${encoding}`)}if(matcher.enc==="fail")return[{ok:!1,error:new GoogleGenAiDefaultError("API error occurred",{request,response,body})},raw];let resultKey=matcher.key||options?.resultKey,data,headersField=matcher.hdrs?{headers:unpackHeaders(response.headers)}:null;return"err"in matcher?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):resultKey?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),{[resultKey]:raw}):matcher.hdrs?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):data=raw,"err"in matcher?[{ok:!1,error:matcher.errorClass?new matcher.errorClass(data,{request,response,body}):data},raw]:[{ok:!0,value:data},raw]}}var headerValRE=/, */;function unpackHeaders(headers){let out={};for(let[k,v]of headers.entries())out[k]=v.split(headerValRE);return out}var SecurityErrorCode={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},SecurityError=class _SecurityError extends Error{constructor(code,message){super(message),this.code=code,this.name="SecurityError"}static incomplete(){return new _SecurityError(SecurityErrorCode.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(type){return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType,`Unrecognised security type: ${type}`)}};function resolveSecurity(...options){let state={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},option=options.find(opts=>opts.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return option==null?null:(option.forEach(spec=>{if(spec.value==null)return;let{type}=spec;switch(type){case"apiKey:header":state.headers[spec.fieldName]=spec.value;break;case"apiKey:query":state.queryParams[spec.fieldName]=spec.value;break;case"apiKey:cookie":state.cookies[spec.fieldName]=spec.value;break;case"http:basic":applyBasic(state,spec);break;case"http:custom":break;case"http:bearer":applyBearer(state,spec);break;case"oauth2":applyBearer(state,spec);break;case"oauth2:password":applyBearer(state,spec);break;case"oauth2:client_credentials":break;case"openIdConnect":applyBearer(state,spec);break;default:throw SecurityError.unrecognizedType(type)}}),state)}function applyBasic(state,spec){spec.value!=null&&(state.basic=spec.value)}function applyBearer(state,spec){if(typeof spec.value!="string"||!spec.value)return;let value=spec.value;value.slice(0,7).toLowerCase()!=="bearer "&&(value=`Bearer ${value}`),spec.fieldName!==void 0&&(state.headers[spec.fieldName]=value)}function resolveGlobalSecurity(security,allowedFields){var _a2,_b;let inputs=[[{fieldName:"accessToken",type:"http:custom",value:(_a2=security?.access_token)!==null&&_a2!==void 0?_a2:env().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(_b=security?.api_key)!==null&&_b!==void 0?_b:env().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:security?.default_headers}]];return resolveSecurity(...inputs)}async function extractSecurity(sec){if(sec!=null)return typeof sec=="function"?sec():sec}var _a,APIPromise=class _APIPromise{constructor(p,callSource){this[_a]="APIPromise",this._promise=p instanceof Promise?p:Promise.resolve(p),this._unwrapped=p instanceof Promise?null:Promise.resolve(p[0]),this._callSource=callSource??null}_getUnwrapped(){var _b;return(_b=this._unwrapped)!==null&&_b!==void 0?_b:this._unwrapped=this._promise.then(([value])=>value)}then(onfulfilled,onrejected){return this._promise.then(onfulfilled?([value])=>onfulfilled(value):void 0,onrejected)}catch(onrejected){return this._getUnwrapped().catch(onrejected)}finally(onfinally){return this._getUnwrapped().finally(onfinally)}$inspect(){return this._promise}asResponse(){var _b;return((_b=this._callSource)!==null&&_b!==void 0?_b:this._callSource=this._promise.then(([,call])=>call)).then(call=>{if(!call.response)throw new Error("APIPromise.asResponse: response unavailable");return call.response})}async withResponse(){let[[data],response]=await Promise.all([this._promise,this.asResponse()]);return{data,response}}_thenUnwrap(transform){var _b;let data=this._promise.then(([value,call])=>[transform(value),call]);return data.catch(()=>{}),new _APIPromise(data,(_b=this._callSource)!==null&&_b!==void 0?_b:void 0)}};_a=Symbol.toStringTag;function unwrapAsAPIPromise(p){let inner=p.$inspect(),data=inner.then(([r,call])=>{if(!r.ok)throw r.error;return[r.value,call]}),callSource=inner.then(([r,call])=>{var _b;if(!r.ok&&!(!((_b=call.response)===null||_b===void 0)&&_b.ok))throw r.error;return call});return data.catch(()=>{}),callSource.catch(()=>{}),new APIPromise(data,callSource)}function agentsCreate(client,body,api_version,options){return new APIPromise($do$q(client,body,api_version,options))}async function $do$q(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsDelete(client,id,api_version,options){return new APIPromise($do$p(client,id,api_version,options))}async function $do$p(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsGet(client,id,api_version,options){return new APIPromise($do$o(client,id,api_version,options))}async function $do$o(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsList(client,api_version,page_size,page_token,parent,options){return new APIPromise($do$n(client,api_version,page_size,page_token,parent,options))}async function $do$n(client,api_version,page_size,page_token,parent,options){var _a2,_b,_c;let payload={api_version,page_size,page_token,parent},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token,parent:payload?.parent}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Agents=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(agentsList(this,params?.api_version,params?.page_size,params?.page_token,params?.parent,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(agentsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(agentsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(agentsGet(this,id,params?.api_version,options))}};function environmentsCreateEnvironment(client,body,api_version,options){return new APIPromise($do$m(client,body,api_version,options))}async function $do$m(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsDeleteEnvironment(client,id,api_version,options){return new APIPromise($do$l(client,id,api_version,options))}async function $do$l(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsGetEnvironment(client,id,api_version,options){return new APIPromise($do$k(client,id,api_version,options))}async function $do$k(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsListEnvironments(client,api_version,page_size,page_token,options){return new APIPromise($do$j(client,api_version,page_size,page_token,options))}async function $do$j(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsFilesList(client,environment,path2,api_version,page_size,page_token,recursive,options){return new APIPromise($do$i(client,environment,path2,api_version,page_size,page_token,recursive,options))}async function $do$i(client,environment,path2,api_version,page_size,page_token,recursive,options){var _a2,_b,_c;let payload={environment,path:path2,api_version,page_size,page_token,recursive},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percent"})},path$=pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token,recursive:payload.recursive}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Files2=class extends ClientSDK{list(environment,path2,params,options){return unwrapAsAPIPromise(environmentsFilesList(this,environment,path2,params?.api_version,params?.page_size,params?.page_token,params?.recursive,options))}};var Environments=class extends ClientSDK{get files(){var _a2;return(_a2=this._files)!==null&&_a2!==void 0?_a2:this._files=new Files2(this._options)}listEnvironments(params,options){return unwrapAsAPIPromise(environmentsListEnvironments(this,params?.api_version,params?.page_size,params?.page_token,options))}createEnvironment(body,api_version,options){return unwrapAsAPIPromise(environmentsCreateEnvironment(this,body,api_version,options))}deleteEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsDeleteEnvironment(this,id,params?.api_version,options))}getEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsGetEnvironment(this,id,params?.api_version,options))}};var CancelInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdServerError"}},CancelInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdClientError"}};var CreateInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionServerError"}},CreateInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionClientError"}};var DeleteInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionServerError"}},DeleteInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionClientError"}};var GetInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdServerError"}},GetInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdClientError"}};function interactionsCancel(client,id,api_version,options){return new APIPromise($do$h(client,id,api_version,options))}async function $do$h(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),jsonErr("4XX",CancelInteractionByIdClientError),jsonErr("5XX",CancelInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsCreate(client,body,api_version,options){return new APIPromise($do$g(client,body,api_version,options))}async function $do$g(client,body,api_version,options){var _a2,_b,_c,_d;let input={body,api_version},payload=input,body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:!((_b=input?.body)===null||_b===void 0)&&_b.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_d=(_c=options?.server_url)!==null&&_c!==void 0?_c:client._baseURL)!==null&&_d!==void 0?_d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",CreateInteractionClientError),jsonErr("5XX",CreateInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsDelete(client,id,api_version,options){return new APIPromise($do$f(client,id,api_version,options))}async function $do$f(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200),jsonErr("4XX",DeleteInteractionClientError),jsonErr("5XX",DeleteInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsGet(client,id,api_version,include_input,last_event_id,stream,options){return new APIPromise($do$e(client,id,api_version,include_input,last_event_id,stream,options))}async function $do$e(client,id,api_version,include_input,last_event_id,stream,options){var _a2,_b,_c;let input={id,api_version,include_input,last_event_id,stream},payload=input,body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),query=encodeFormQuery({include_input:payload.include_input,last_event_id:payload.last_event_id,stream:payload.stream}),headers=new Headers(compactMap({Accept:input?.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",GetInteractionByIdClientError),jsonErr("5XX",GetInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Interactions=class extends ClientSDK{create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(interactionsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(interactionsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(interactionsGet(this,id,params?.api_version,params?.include_input,params?.last_event_id,params?.stream,options))}cancel(id,params,options){return unwrapAsAPIPromise(interactionsCancel(this,id,params?.api_version,options))}};function triggersCreate(client,body,api_version,options){return new APIPromise($do$d(client,body,api_version,options))}async function $do$d(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersDelete(client,id,api_version,options){return new APIPromise($do$c(client,id,api_version,options))}async function $do$c(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersGet(client,id,api_version,options){return new APIPromise($do$b(client,id,api_version,options))}async function $do$b(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersListExecutions(client,trigger_id,api_version,page_size,page_token,options){return new APIPromise($do$a(client,trigger_id,api_version,page_size,page_token,options))}async function $do$a(client,trigger_id,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={trigger_id,api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersList(client,api_version,filter,page_size,page_token,options){return new APIPromise($do$9(client,api_version,filter,page_size,page_token,options))}async function $do$9(client,api_version,filter,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,filter,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),query=encodeFormQuery({filter:payload?.filter,page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersRun(client,trigger_id,api_version,options){return new APIPromise($do$8(client,trigger_id,api_version,options))}async function $do$8(client,trigger_id,api_version,options){var _a2,_b,_c;let payload={trigger_id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersUpdate(client,id,body,api_version,options){return new APIPromise($do$7(client,id,body,api_version,options))}async function $do$7(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Triggers=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(triggersList(this,params?.api_version,params?.filter,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(triggersDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(triggersGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersUpdate(this,id,body,api_version,options))}listExecutions(trigger_id,params,options){return unwrapAsAPIPromise(triggersListExecutions(this,trigger_id,params?.api_version,params?.page_size,params?.page_token,options))}run(trigger_id,params,options){return unwrapAsAPIPromise(triggersRun(this,trigger_id,params?.api_version,options))}};function webhooksCreate(client,body,api_version,options){return new APIPromise($do$6(client,body,api_version,options))}async function $do$6(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksDelete(client,id,api_version,options){return new APIPromise($do$5(client,id,api_version,options))}async function $do$5(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksGet(client,id,api_version,options){return new APIPromise($do$4(client,id,api_version,options))}async function $do$4(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksList(client,api_version,page_size,page_token,options){return new APIPromise($do$3(client,api_version,page_size,page_token,options))}async function $do$3(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e;return new GoogleGenAI$1(Object.assign(Object.assign({},options),{api_version:(_a2=options.api_version)!==null&&_a2!==void 0?_a2:getGoogleGenAIAPIVersion(parentClient),security:(_b=options.security)!==null&&_b!==void 0?_b:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_c=parentClient.getDefaultHeaders)===null||_c===void 0?void 0:_c.call(parentClient)),(_d=parentClient.getHeaders)===null||_d===void 0?void 0:_d.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_e=options.server_url)!==null&&_e!==void 0?_e:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,pageSize,pageToken,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,pageSize,pageToken,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient){this.resolveClient=resolveClient}async list(params,options){let{environment,path:path2,page_size,page_token,recursive,api_version}=params;return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(api_version),environment,path2,api_version,page_size,page_token,recursive,toGoogleGenAIRequestOptions(options)))}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion))}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.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(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(toObject,["pipelineRootDirectory"],fromPipelineRootDirectory);let fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromStudentModel=getValueByPath(fromObject,["studentModel"]);fromStudentModel!=null&&setValueByPath(toObject,["studentModel"],fromStudentModel);let fromTrainingDatasetUri=getValueByPath(fromObject,["trainingDatasetUri"]);fromTrainingDatasetUri!=null&&setValueByPath(toObject,["trainingDatasetUri"],fromTrainingDatasetUri);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);fromTuningMode!=null&&setValueByPath(toObject,["tuningMode"],fromTuningMode);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);return fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri),toObject}function generationConfigFromVertex(fromObject,_rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelSelectionConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],fromSpeechConfig);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);return fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),toObject}function getTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function getTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listTuningJobsConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listTuningJobsParametersToVertex(fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listTuningJobsConfigToVertex(fromConfig,toObject),toObject}function listTuningJobsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromTuningJobs=getValueByPath(fromObject,["tuningJobs"]);if(fromTuningJobs!=null){let transformedList=fromTuningJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>tuningJobFromVertex(item))),setValueByPath(toObject,["tuningJobs"],transformedList)}return toObject}function partToVertex(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function reinforcementTuningExampleToVertex(fromObject,rootObject){let toObject={},fromReferences=getValueByPath(fromObject,["references"]);fromReferences!=null&&setValueByPath(toObject,["references"],fromReferences);let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);return fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction)),toObject}function tunedModelFromMldev(fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromExamples=getValueByPath(fromObject,["examples"]);if(fromExamples!=null){let transformedList=fromExamples;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["examples","examples"],transformedList)}return toObject}function tuningDatasetToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorGcsUri=getValueByPath(rootObject,["config","method"]);if(discriminatorGcsUri===void 0&&(discriminatorGcsUri="SUPERVISED_FINE_TUNING"),discriminatorGcsUri==="SUPERVISED_FINE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="PREFERENCE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="DISTILLATION"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="REINFORCEMENT_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromGcsUri)}let discriminatorVertexDatasetResource=getValueByPath(rootObject,["config","method"]);if(discriminatorVertexDatasetResource===void 0&&(discriminatorVertexDatasetResource="SUPERVISED_FINE_TUNING"),discriminatorVertexDatasetResource==="SUPERVISED_FINE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="PREFERENCE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="DISTILLATION"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="REINFORCEMENT_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}if(getValueByPath(fromObject,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tuningJobFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["tuningTask","startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["tuningTask","completeTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["_self"]);return fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],tunedModelFromMldev(fromTunedModel)),toObject}function tuningJobFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["tunedModel"]);fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],fromTunedModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromSupervisedTuningSpec=getValueByPath(fromObject,["supervisedTuningSpec"]);fromSupervisedTuningSpec!=null&&setValueByPath(toObject,["supervisedTuningSpec"],fromSupervisedTuningSpec);let fromPreferenceOptimizationSpec=getValueByPath(fromObject,["preferenceOptimizationSpec"]);fromPreferenceOptimizationSpec!=null&&setValueByPath(toObject,["preferenceOptimizationSpec"],fromPreferenceOptimizationSpec);let fromDistillationSamplingSpec=getValueByPath(fromObject,["distillationSamplingSpec"]);fromDistillationSamplingSpec!=null&&setValueByPath(toObject,["distillationSamplingSpec"],distillationSamplingSpecFromVertex(fromDistillationSamplingSpec));let fromDistillationSpec=getValueByPath(fromObject,["distillationSpec"]);fromDistillationSpec!=null&&setValueByPath(toObject,["distillationSpec"],distillationSpecFromVertex(fromDistillationSpec));let fromReinforcementTuningSpec=getValueByPath(fromObject,["reinforcementTuningSpec"]);fromReinforcementTuningSpec!=null&&setValueByPath(toObject,["reinforcementTuningSpec"],fromReinforcementTuningSpec);let fromTuningDataStats=getValueByPath(fromObject,["tuningDataStats"]);fromTuningDataStats!=null&&setValueByPath(toObject,["tuningDataStats"],fromTuningDataStats);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);fromEncryptionSpec!=null&&setValueByPath(toObject,["encryptionSpec"],fromEncryptionSpec);let fromPartnerModelTuningSpec=getValueByPath(fromObject,["partnerModelTuningSpec"]);fromPartnerModelTuningSpec!=null&&setValueByPath(toObject,["partnerModelTuningSpec"],fromPartnerModelTuningSpec);let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);fromCustomBaseModel!=null&&setValueByPath(toObject,["customBaseModel"],fromCustomBaseModel);let fromEvaluateDatasetRuns=getValueByPath(fromObject,["evaluateDatasetRuns"]);if(fromEvaluateDatasetRuns!=null){let transformedList=fromEvaluateDatasetRuns;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["evaluateDatasetRuns"],transformedList)}let fromExperiment=getValueByPath(fromObject,["experiment"]);fromExperiment!=null&&setValueByPath(toObject,["experiment"],fromExperiment);let fromFullFineTuningSpec=getValueByPath(fromObject,["fullFineTuningSpec"]);fromFullFineTuningSpec!=null&&setValueByPath(toObject,["fullFineTuningSpec"],fromFullFineTuningSpec);let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);fromOutputUri!=null&&setValueByPath(toObject,["outputUri"],fromOutputUri);let fromPipelineJob=getValueByPath(fromObject,["pipelineJob"]);fromPipelineJob!=null&&setValueByPath(toObject,["pipelineJob"],fromPipelineJob);let fromServiceAccount=getValueByPath(fromObject,["serviceAccount"]);fromServiceAccount!=null&&setValueByPath(toObject,["serviceAccount"],fromServiceAccount);let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);fromTunedModelDisplayName!=null&&setValueByPath(toObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromTuningJobMetadata=getValueByPath(fromObject,["tuningJobMetadata"]);fromTuningJobMetadata!=null&&setValueByPath(toObject,["tuningJobMetadata"],fromTuningJobMetadata);let fromTuningJobState=getValueByPath(fromObject,["tuningJobState"]);fromTuningJobState!=null&&setValueByPath(toObject,["tuningJobState"],fromTuningJobState);let fromVeoLoraTuningSpec=getValueByPath(fromObject,["veoLoraTuningSpec"]);fromVeoLoraTuningSpec!=null&&setValueByPath(toObject,["veoLoraTuningSpec"],fromVeoLoraTuningSpec);let fromVeoTuningSpec=getValueByPath(fromObject,["veoTuningSpec"]);return fromVeoTuningSpec!=null&&setValueByPath(toObject,["veoTuningSpec"],fromVeoTuningSpec),toObject}function tuningOperationFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function tuningValidationDatasetToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromGcsUri);let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);return fromVertexDatasetResource!=null&&setValueByPath(toObject,["validationDatasetUri"],fromVertexDatasetResource),toObject}function validateRewardParametersToVertex(fromObject,rootObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromSampleResponse=getValueByPath(fromObject,["sampleResponse"]);fromSampleResponse!=null&&setValueByPath(toObject,["sampleResponse"],contentToVertex(fromSampleResponse));let fromExample=getValueByPath(fromObject,["example"]);fromExample!=null&&setValueByPath(toObject,["example"],reinforcementTuningExampleToVertex(fromExample));let fromSingleRewardConfig=getValueByPath(fromObject,["singleRewardConfig"]);fromSingleRewardConfig!=null&&setValueByPath(toObject,["singleRewardConfig"],fromSingleRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);return fromCompositeRewardConfig!=null&&setValueByPath(toObject,["compositeRewardConfig"],fromCompositeRewardConfig),toObject}function validateRewardResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromOverallReward=getValueByPath(fromObject,["overallReward"]);fromOverallReward!=null&&setValueByPath(toObject,["overallReward"],fromOverallReward);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromRewardInfoDetails=getValueByPath(fromObject,["rewardInfoDetails"]);return fromRewardInfoDetails!=null&&setValueByPath(toObject,["rewardInfoDetails"],fromRewardInfoDetails),toObject}var Tunings=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.get=async params=>await this.getInternal(params),this.tune=async params=>{var _a2;if(this.apiClient.isVertexAI())if(params.baseModel.startsWith("projects/")){let preTunedModel={tunedModelName:params.baseModel};!((_a2=params.config)===null||_a2===void 0)&&_a2.preTunedModelCheckpointId&&(preTunedModel.checkpointId=params.config.preTunedModelCheckpointId);let paramsPrivate=Object.assign(Object.assign({},params),{preTunedModel});return paramsPrivate.baseModel=void 0,await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params);return await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params),operation=await this.tuneMldevInternal(paramsPrivate),tunedModelName="";return operation.metadata!==void 0&&operation.metadata.tunedModel!==void 0?tunedModelName=operation.metadata.tunedModel:operation.name!==void 0&&operation.name.includes("/operations/")&&(tunedModelName=operation.name.split("/operations/")[0]),{name:tunedModelName,state:JobState.JOB_STATE_QUEUED}}}}async getInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getTuningJobParametersToVertex(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else{let body=getTuningJobParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromMldev(apiResponse))}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listTuningJobsParametersToVertex(params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listTuningJobsResponseFromVertex(apiResponse),typedResp=new ListTuningJobsResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelTuningJobParametersToVertex(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromVertex(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=cancelTuningJobParametersToMldev(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromMldev(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}}async tuneInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createTuningJobParametersPrivateToVertex(params,params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createTuningJobParametersPrivateToMldev(params);return path2=formatMap("tunedModels",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningOperationFromMldev(apiResponse))}}async validateReward(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=validateRewardParametersToVertex(params);return path2=formatMap("{parent}/tuningJobs:validateReinforcementTuningReward",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=validateRewardResponseFromVertex(apiResponse),typedResp=new ValidateRewardResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},MAX_CHUNK_SIZE=1024*1024*8,MAX_RETRY_COUNT=3,INITIAL_RETRY_DELAY_MS=1e3,DELAY_MULTIPLIER=2,X_GOOG_UPLOAD_STATUS_HEADER_FIELD="x-goog-upload-status";async function uploadBlob(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async function uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async function uploadBlobInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload";for(fileSize=file.size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset),chunk=file.slice(offset,offset+chunkSize);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset)});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=chunkSize,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}async function getBlobStat(file){return{size:file.size,type:file.type}}function sleep(ms){return new Promise(resolvePromise=>setTimeout(resolvePromise,ms))}var NodeUploader=class{async stat(file){let fileStat={size:0,type:void 0};if(typeof file=="string"){let originalStat=await fs.stat(file);return fileStat.size=originalStat.size,fileStat.type=this.inferMimeType(file),fileStat}else return await getBlobStat(file)}async upload(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlob(file,uploadUrl,apiClient,httpOptions)}async uploadToFileSearchStore(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions)}inferMimeType(filePath){let fileExtension=filePath.slice(filePath.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[fileExtension.toLowerCase()]}async uploadFileFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload",fileHandle,fileName=path.basename(file);try{if(fileHandle=await fs.open(file,"r"),!fileHandle)throw new Error("Failed to open file");for(fileSize=(await fileHandle.stat()).size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let buffer=new Uint8Array(chunkSize),{bytesRead}=await fileHandle.read(buffer,0,chunkSize,offset);if(bytesRead!==chunkSize)throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);let chunk=new Blob([buffer]),retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset),"X-Goog-Upload-File-Name":fileName});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=bytesRead,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}finally{fileHandle&&await fileHandle.close()}}};var NodeFiles=class extends Files$1{async registerFiles(params){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let authHeaders=await params.auth.getRequestHeaders(),config=params.config||{},httpOptions=config.httpOptions||{},headers=Object.assign({},httpOptions.headers||{});if(authHeaders)if(typeof authHeaders[Symbol.iterator]=="function")for(let[key,value]of authHeaders)headers[key]=value;else for(let[key,value]of Object.entries(authHeaders))headers[key]=value;return this._registerFiles({uris:params.uris,config:Object.assign(Object.assign({},config),{httpOptions:Object.assign(Object.assign({},httpOptions),{headers})})})}};var LANGUAGE_LABEL_PREFIX="gl-node/";function resolveCloudFlag(options){var _a2;if(options&&(options.enterprise!==void 0||options.vertexai!==void 0)){if(options.enterprise!==void 0&&options.vertexai!==void 0&&options.enterprise!==options.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(_a2=options.enterprise)!==null&&_a2!==void 0?_a2:options.vertexai}let envEnterpriseStr=getEnv("GOOGLE_GENAI_USE_ENTERPRISE"),envVertexaiStr=getEnv("GOOGLE_GENAI_USE_VERTEXAI"),useEnterpriseEnv=stringToBoolean(envEnterpriseStr),useVertexaiEnv=stringToBoolean(envVertexaiStr);return envEnterpriseStr!==void 0&&envVertexaiStr!==void 0&&useEnterpriseEnv!==useVertexaiEnv&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),envEnterpriseStr!==void 0?useEnterpriseEnv:envVertexaiStr!==void 0?useVertexaiEnv:!1}var GoogleGenAI2=class{getNextGenClient(){let httpOpts=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=buildGoogleGenAIClient(this.apiClient,{timeout_ms:httpOpts?.timeout})),httpOpts?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new GeminiNextGenInteractions(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new GeminiNextGenWebhooks(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new GeminiNextGenAgents(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new GeminiNextGenTriggers(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new GeminiNextGenEnvironments(this.apiClient),this._environments)}constructor(options={}){var _a2,_b,_c,_d;if(this.vertexai=resolveCloudFlag(options),(options.project||options.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let envApiKey=getApiKeyFromEnv(),envProject=getEnv("GOOGLE_CLOUD_PROJECT"),envLocation=getEnv("GOOGLE_CLOUD_LOCATION");this.apiKey=(_a2=options.apiKey)!==null&&_a2!==void 0?_a2:envApiKey,this.project=(_b=options.project)!==null&&_b!==void 0?_b:envProject,this.location=(_c=options.location)!==null&&_c!==void 0?_c:envLocation,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((_d=options.googleAuthOptions)===null||_d===void 0)&&_d.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!options.project&&!options.location&&(envProject||envLocation)&&options.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(options.project||options.location)&&!options.apiKey&&envApiKey?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!options.project&&!options.location&&!options.apiKey&&(envProject||envLocation)&&envApiKey&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let baseUrl=getBaseUrl(options.httpOptions,this.vertexai,getEnv("GOOGLE_VERTEX_BASE_URL"),getEnv("GOOGLE_GEMINI_BASE_URL"));baseUrl&&(options.httpOptions?options.httpOptions.baseUrl=baseUrl:options.httpOptions={baseUrl}),this.apiVersion=options.apiVersion,this.httpOptions=options.httpOptions;let auth=new NodeAuth({apiKey:this.apiKey,googleAuthOptions:options.googleAuthOptions});this.apiClient=new ApiClient({auth,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LANGUAGE_LABEL_PREFIX+process.version,uploader:new NodeUploader,downloader:new NodeDownloader}),this.models=new Models(this.apiClient),this.live=new Live(this.apiClient,auth,new NodeWebSocketFactory),this.batches=new Batches(this.apiClient),this.chats=new Chats(this.models,this.apiClient),this.caches=new Caches(this.apiClient),this.files=new NodeFiles(this.apiClient),this.operations=new Operations(this.apiClient),this.authTokens=new Tokens(this.apiClient),this.tunings=new Tunings(this.apiClient),this.fileSearchStores=new FileSearchStores(this.apiClient)}};function getEnv(env2){var _a2,_b,_c;return(_c=(_b=(_a2=process==null?void 0:process.env)===null||_a2===void 0?void 0:_a2[env2])===null||_b===void 0?void 0:_b.trim())!==null&&_c!==void 0?_c:void 0}function stringToBoolean(str){return str===void 0?!1:str.toLowerCase()==="true"}function getApiKeyFromEnv(){let envGoogleApiKey=getEnv("GOOGLE_API_KEY"),envGeminiApiKey=getEnv("GEMINI_API_KEY");return envGoogleApiKey&&envGeminiApiKey&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),envGoogleApiKey||envGeminiApiKey||void 0}var GOOGLE_SDK_THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH};function resolveGoogleThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function usesGoogleThinkingLevel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id)||/gemini-(?:[4-9]|[1-9]\d)/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"||/gemma-?4/.test(id)}function toGoogleThinkingLevel(level){switch(level){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function toGoogleSdkThinkingLevel(level){return GOOGLE_SDK_THINKING_LEVEL_MAP[level]}function getDisabledGoogleThinkingConfig(model){if(!usesGoogleThinkingLevel(model))return{thinkingBudget:0};let fallback=clampThinkingLevel(model,"off");if(fallback==="off")return{thinkingBudget:0};let resolvedLevel=resolveGoogleThinkingLevel(model,fallback),apiLevel=toGoogleThinkingLevel(resolvedLevel);return{thinkingLevel:toGoogleSdkThinkingLevel(apiLevel)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match2=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match2)return Number.parseInt(match2[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function convertMessages(model,context){let conversation=withoutInitialSystemMessage(collapseSystemMessages(context).messages),contents=[],transformedMessages=transformMessages(conversation,model,id=>requiresToolCallId(model.id)?id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):id);for(let msg of transformedMessages)if(msg.role==="user")if(typeof msg.content=="string")contents.push({role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;contents.push({role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}if(parts.length===0)continue;contents.push({role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
`),imageContent=model.input.includes("image")?msg.content.filter(c=>c.type==="image"):[],hasText=textResult.trim().length>0,hasImages=imageContent.length>0,modelSupportsMultimodalFunctionResponse=supportsMultimodalFunctionResponse(model.id),responseValue=hasText?sanitizeSurrogates(textResult):hasImages?"(see attached image)":"",imageParts=imageContent.map(imageBlock=>({inlineData:{mimeType:imageBlock.mimeType,data:imageBlock.data}})),includeId=requiresToolCallId(model.id),functionResponsePart={functionResponse:{name:msg.toolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}},lastContent=contents[contents.length-1];lastContent?.role==="user"&&lastContent.parts?.some(p=>p.functionResponse)?lastContent.parts.push(functionResponsePart):contents.push({role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&contents.push({role:"user",parts:[{text:"Tool result image:"},...imageParts]})}return contents}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return schema;let result={};for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(result[key]=sanitizeForOpenApi(value));return result}var JSON_SCHEMA_NAME_MAPS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),JSON_SCHEMA_SUBSCHEMAS=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function rewriteConstAsEnum(schema,isNameMap=!1){if(Array.isArray(schema))return schema.map(item=>rewriteConstAsEnum(item));if(typeof schema!="object"||schema===null)return schema;let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[value])}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:rewriteConstAsEnum(parameters)}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};