shiplightai 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agentHelpers-MOO2YPML.js +3 -0
- package/dist/{agentLogin-U7QWF4AY.js → agentLogin-2SSRFZ2U.js} +1 -1
- package/dist/{chunk-HECRJRKW.js → chunk-4JBGAENP.js} +9 -9
- package/dist/{chunk-LZ2F7OA3.js → chunk-ESJGKHJ4.js} +5 -5
- package/dist/chunk-JY6U4L7Q.js +216 -0
- package/dist/{chunk-JNVFLK5Q.js → chunk-NDYQF4WM.js} +5 -5
- package/dist/chunk-QU5HYOUM.js +5 -0
- package/dist/chunk-SGXLY5OU.js +33 -0
- package/dist/chunk-SUZXLRAA.js +18 -0
- package/dist/{chunk-OM5W5GBC.js → chunk-VXL4KP4U.js} +31 -28
- package/dist/cjs/debugger-pw.cjs +7 -0
- package/dist/cjs/fixture.cjs +236 -258
- package/dist/cjs/index.cjs +230 -252
- package/dist/cli.js +1027 -1683
- package/dist/copilot-7JTVJQXP.js +5 -0
- package/dist/debugger-pw.d.ts +145 -0
- package/dist/debugger-pw.js +3 -0
- package/dist/dist-HN2P3FRX.js +14 -0
- package/dist/dist-OOFTSMK3.js +3 -0
- package/dist/dist-WQ66EMT6.js +3 -0
- package/dist/fixture.js +1 -1
- package/dist/{handler-YM2CNJMM.js → handler-XD2P4DE3.js} +1 -1
- package/dist/index.js +11 -11
- package/dist/intRunner-5A6M6JSJ.js +7 -0
- package/dist/{multipart-parser-IEIT2KXO.js → multipart-parser-KQFLHJKK.js} +1 -1
- package/dist/src-CXU6MEQY.js +5 -0
- package/dist/{task-SZERT63E.js → task-7OWMRRUU.js} +1 -1
- package/dist/testFlow-OQWWSEQT.js +3 -0
- package/package.json +7 -1
- package/dist/agentHelpers-YAPGMNDU.js +0 -3
- package/dist/chunk-5OEE46TI.js +0 -230
- package/dist/chunk-A2VNNKWB.js +0 -18
- package/dist/chunk-CYBAFQLF.js +0 -5
- package/dist/chunk-IMX7PO3X.js +0 -18
- package/dist/chunk-STSHJEMG.js +0 -3
- package/dist/chunk-SWUSVR2K.js +0 -30
- package/dist/chunk-Y2QWBQXE.js +0 -8
- package/dist/dist-5LVWKFH4.js +0 -3
- package/dist/dist-DAIQ7AOS.js +0 -14
- package/dist/dist-IH5NPMQ7.js +0 -3
- package/dist/fileFromPath-ROF7A3FH.js +0 -3
- package/dist/src-2RQUBO3W.js +0 -5
|
@@ -1,55 +1,55 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
const require = __createRequire(import.meta.url);
|
|
3
|
-
import{a as
|
|
4
|
-
`)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};It.GaxiosError=li;function db(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function zu(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(a){a&&a.forEach((i,s)=>{(/^authentication$/i.test(s)||/^authorization$/i.test(s)||/secret/i.test(s))&&a.set(s,e)})}function n(a,i){if(typeof a=="object"&&a!==null&&typeof a[i]=="string"){let s=a[i];(/grant_type=/i.test(s)||/assertion=/i.test(s)||/secret/i.test(s))&&(a[i]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((i,s)=>{(["grant_type","assertion"].includes(s)||/secret/.test(s))&&a.set(s,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(zu({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var Ju=ee(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.getRetryConfig=pb;async function pb(t){let e=Wu(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||hb)(t))return{shouldRetry:!1,config:t.config};let o=fb(e);t.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await a,{shouldRetry:!0,config:t.config}}function hb(t){let e=Wu(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,o]of e.statusCodesToRetry){let a=t.response.status;if(a>=n&&a<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Wu(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function fb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var pi=ee(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.GaxiosInterceptorManager=void 0;var di=class extends Set{};Co.GaxiosInterceptorManager=di});var Xu=ee(Xr=>{"use strict";var mb=Xr&&Xr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Yr;Object.defineProperty(Xr,"__esModule",{value:!0});Xr.Gaxios=void 0;var gb=mb(ii()),yb=be("https"),Hr=ci(),vb=Ju(),Ku=be("stream"),Yu=pi(),bb=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),_b=204,Io=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Yu.GaxiosInterceptorManager,response:new Yu.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,a=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Yr.mergeHeaders(a,r.headers),n&&Yr.mergeHeaders(a,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Yr.#l(),n={...e};delete n.data;let o=await r(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let o=[];for await(let a of r.data)o.push(a);r.data=o.toString()}let n=Hr.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new Hr.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof Hr.GaxiosError?n=r:r instanceof Error?n=new Hr.GaxiosError(r.message,e,void 0,r):n=new Hr.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:a}=await(0,vb.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(r.status===_b)return"";if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new Hr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":{let n=await r.text();try{return JSON.parse(n)}catch{return n}}case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),o=[...r],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of a)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(n.toString()))return!1}else if(i instanceof URL){if(i.origin===n.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let s=i.replace(/^\*\./,".");if(n.hostname.endsWith(s))return!1}else if(i===n.origin||i===n.hostname||i===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Yr.mergeHeaders(r,e.headers);let n=(0,gb.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let i=n.paramsSerializer(n.params);i.startsWith("?")&&(i=i.slice(1));let s=n.url.toString().includes("?")?"&":"?";n.url=n.url+s+i}else{let i=n.url instanceof URL?n.url:new URL(n.url);for(let[s,l]of new URLSearchParams(n.params))i.searchParams.append(s,l);n.url=i}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof Ku.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let i=await bb();r.set("content-type",`multipart/related; boundary=${i}`),n.body=Ku.Readable.from(this.getMultipartRequest(n.multipart,i))}else o?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let a=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(a&&this.#e(n.url,n.noProxy)){let i=await Yr.#s();this.agentCache.has(a)?n.agent=this.agentCache.get(a):(n.agent=new i(a,{cert:n.cert,key:n.key}),this.agentCache.set(a,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new yb.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=Hr.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
|
|
3
|
+
import{a as lg}from"./chunk-YU3XZJIJ.js";import{a as ce}from"./chunk-QU5HYOUM.js";import{c as Sn}from"./chunk-FBJSHHRD.js";import{a as _e,c as te,d as Fa}from"./chunk-CSINHOOD.js";var ii=te(($A,Hu)=>{"use strict";var So=Object.prototype.hasOwnProperty,Uu=Object.prototype.toString,Mu=Object.defineProperty,Pu=Object.getOwnPropertyDescriptor,Du=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Uu.call(e)==="[object Array]"},ju=function(e){if(!e||Uu.call(e)!=="[object Object]")return!1;var r=So.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&So.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||So.call(e,o)},Lu=function(e,r){Mu&&r.name==="__proto__"?Mu(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Fu=function(e,r){if(r==="__proto__")if(So.call(e,r)){if(Pu)return Pu(e,r).value}else return;return e[r]};Hu.exports=function t(){var e,r,n,o,a,i,s=arguments[0],l=1,c=arguments.length,p=!1;for(typeof s=="boolean"&&(p=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<c;++l)if(e=arguments[l],e!=null)for(r in e)n=Fu(s,r),o=Fu(e,r),s!==o&&(p&&o&&(ju(o)||(a=Du(o)))?(a?(a=!1,i=n&&Du(n)?n:[]):i=n&&ju(n)?n:{},Lu(s,{name:r,newValue:t(p,i,o)})):typeof o<"u"&&Lu(s,{name:r,newValue:o}));return s}});var qu=te((GA,lb)=>{lb.exports={name:"gaxios",version:"7.1.3",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2",rimraf:"^5.0.1"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}});var Gu=te((BA,$u)=>{"use strict";var cb=qu();$u.exports={pkg:cb}});var ci=te(It=>{"use strict";var Vu=It&&It.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(It,"__esModule",{value:!0});It.GaxiosError=It.GAXIOS_ERROR_SYMBOL=void 0;It.defaultErrorRedactor=zu;var Bu=Vu(ii()),ub=Vu(Gu()),si=ub.default.pkg;It.GAXIOS_ERROR_SYMBOL=Symbol.for(`${si.name}-gaxios-error`);var li=class t extends Error{config;response;code;status;error;[It.GAXIOS_ERROR_SYMBOL]=si.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&It.GAXIOS_ERROR_SYMBOL in e&&e[It.GAXIOS_ERROR_SYMBOL]===si.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Bu.default)(!0,{},r),this.response&&(this.response.config=(0,Bu.default)(!0,{},this.response.config)),this.response){try{this.response.data=db(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let s of e.data.error.errors)typeof s=="object"&&"message"in s&&typeof s.message=="string"&&i.push(s.message);return Object.assign({message:i.join(`
|
|
4
|
+
`)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};It.GaxiosError=li;function db(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function zu(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(a){a&&a.forEach((i,s)=>{(/^authentication$/i.test(s)||/^authorization$/i.test(s)||/secret/i.test(s))&&a.set(s,e)})}function n(a,i){if(typeof a=="object"&&a!==null&&typeof a[i]=="string"){let s=a[i];(/grant_type=/i.test(s)||/assertion=/i.test(s)||/secret/i.test(s))&&(a[i]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((i,s)=>{(["grant_type","assertion"].includes(s)||/secret/.test(s))&&a.set(s,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(zu({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var Ju=te(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.getRetryConfig=pb;async function pb(t){let e=Wu(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||hb)(t))return{shouldRetry:!1,config:t.config};let o=fb(e);t.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await a,{shouldRetry:!0,config:t.config}}function hb(t){let e=Wu(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,o]of e.statusCodesToRetry){let a=t.response.status;if(a>=n&&a<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Wu(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function fb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var pi=te(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.GaxiosInterceptorManager=void 0;var di=class extends Set{};Co.GaxiosInterceptorManager=di});var Xu=te(Xr=>{"use strict";var mb=Xr&&Xr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Yr;Object.defineProperty(Xr,"__esModule",{value:!0});Xr.Gaxios=void 0;var gb=mb(ii()),yb=_e("https"),Hr=ci(),vb=Ju(),Ku=_e("stream"),Yu=pi(),bb=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),_b=204,Io=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Yu.GaxiosInterceptorManager,response:new Yu.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,a=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Yr.mergeHeaders(a,r.headers),n&&Yr.mergeHeaders(a,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Yr.#l(),n={...e};delete n.data;let o=await r(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let o=[];for await(let a of r.data)o.push(a);r.data=o.toString()}let n=Hr.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new Hr.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof Hr.GaxiosError?n=r:r instanceof Error?n=new Hr.GaxiosError(r.message,e,void 0,r):n=new Hr.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:a}=await(0,vb.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(r.status===_b)return"";if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new Hr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":{let n=await r.text();try{return JSON.parse(n)}catch{return n}}case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),o=[...r],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of a)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(n.toString()))return!1}else if(i instanceof URL){if(i.origin===n.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let s=i.replace(/^\*\./,".");if(n.hostname.endsWith(s))return!1}else if(i===n.origin||i===n.hostname||i===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Yr.mergeHeaders(r,e.headers);let n=(0,gb.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let i=n.paramsSerializer(n.params);i.startsWith("?")&&(i=i.slice(1));let s=n.url.toString().includes("?")?"&":"?";n.url=n.url+s+i}else{let i=n.url instanceof URL?n.url:new URL(n.url);for(let[s,l]of new URLSearchParams(n.params))i.searchParams.append(s,l);n.url=i}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof Ku.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let i=await bb();r.set("content-type",`multipart/related; boundary=${i}`),n.body=Ku.Readable.from(this.getMultipartRequest(n.multipart,i))}else o?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let a=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(a&&this.#e(n.url,n.noProxy)){let i=await Yr.#s();this.agentCache.has(a)?n.agent=this.agentCache.get(a):(n.agent=new i(a,{cert:n.cert,key:n.key}),this.agentCache.set(a,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new yb.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=Hr.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
|
|
5
5
|
Content-Type: ${a}\r
|
|
6
6
|
\r
|
|
7
7
|
`,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
|
|
8
|
-
`}yield n}static#a;static#i;static async#s(){return this.#a||=(await import("./dist-DAIQ7AOS.js")).HttpsProxyAgent,this.#a}static async#l(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await import("./src-2RQUBO3W.js")).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((a,i)=>{i==="set-cookie"?e.append(i,a):e.set(i,a)});return e}};Xr.Gaxios=Io;Yr=Io});var rt=ee(ct=>{"use strict";var wb=ct&&ct.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Eb=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wb(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.instance=ct.Gaxios=ct.GaxiosError=void 0;ct.request=xb;var Zu=Xu();Object.defineProperty(ct,"Gaxios",{enumerable:!0,get:function(){return Zu.Gaxios}});var Tb=ci();Object.defineProperty(ct,"GaxiosError",{enumerable:!0,get:function(){return Tb.GaxiosError}});Eb(pi(),ct);ct.instance=new Zu.Gaxios;async function xb(t){return ct.instance.request(t)}});var hi=ee((Qu,Ao)=>{"use strict";(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,a="[BigNumber Error] ",i=a+"Number primitive has more than 15 significant digits: ",s=1e14,l=14,c=9007199254740991,p=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,m=1e9;function g(P){var N,R,Q,E=F.prototype={constructor:F,toString:null,valueOf:null},re=new F(1),Z=20,Y=4,ce=-7,B=21,J=-1e7,fe=1e7,j=!1,ye=1,Se=0,he={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ue="0123456789abcdefghijklmnopqrstuvwxyz",z=!0;function F(d,f){var v,C,S,k,M,x,A,O,I=this;if(!(I instanceof F))return new F(d,f);if(f==null){if(d&&d._isBigNumber===!0){I.s=d.s,!d.c||d.e>fe?I.c=I.e=null:d.e<J?I.c=[I.e=0]:(I.e=d.e,I.c=d.c.slice());return}if((x=typeof d=="number")&&d*0==0){if(I.s=1/d<0?(d=-d,-1):1,d===~~d){for(k=0,M=d;M>=10;M/=10,k++);k>fe?I.c=I.e=null:(I.e=k,I.c=[d]);return}O=String(d)}else{if(!r.test(O=String(d)))return Q(I,O,x);I.s=O.charCodeAt(0)==45?(O=O.slice(1),-1):1}(k=O.indexOf("."))>-1&&(O=O.replace(".","")),(M=O.search(/e/i))>0?(k<0&&(k=M),k+=+O.slice(M+1),O=O.substring(0,M)):k<0&&(k=O.length)}else{if(_(f,2,Ue.length,"Base"),f==10&&z)return I=new F(d),ae(I,Z+I.e+1,Y);if(O=String(d),x=typeof d=="number"){if(d*0!=0)return Q(I,O,x,f);if(I.s=1/d<0?(O=O.slice(1),-1):1,F.DEBUG&&O.replace(/^0\.0*|\./,"").length>15)throw Error(i+d)}else I.s=O.charCodeAt(0)===45?(O=O.slice(1),-1):1;for(v=Ue.slice(0,f),k=M=0,A=O.length;M<A;M++)if(v.indexOf(C=O.charAt(M))<0){if(C=="."){if(M>k){k=A;continue}}else if(!S&&(O==O.toUpperCase()&&(O=O.toLowerCase())||O==O.toLowerCase()&&(O=O.toUpperCase()))){S=!0,M=-1,k=0;continue}return Q(I,String(d),x,f)}x=!1,O=R(O,f,10,I.s),(k=O.indexOf("."))>-1?O=O.replace(".",""):k=O.length}for(M=0;O.charCodeAt(M)===48;M++);for(A=O.length;O.charCodeAt(--A)===48;);if(O=O.slice(M,++A)){if(A-=M,x&&F.DEBUG&&A>15&&(d>c||d!==o(d)))throw Error(i+I.s*d);if((k=k-M-1)>fe)I.c=I.e=null;else if(k<J)I.c=[I.e=0];else{if(I.e=k,I.c=[],M=(k+1)%l,k<0&&(M+=l),M<A){for(M&&I.c.push(+O.slice(0,M)),A-=l;M<A;)I.c.push(+O.slice(M,M+=l));M=l-(O=O.slice(M)).length}else M-=A;for(;M--;O+="0");I.c.push(+O)}}else I.c=[I.e=0]}F.clone=g,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(d){var f,v;if(d!=null)if(typeof d=="object"){if(d.hasOwnProperty(f="DECIMAL_PLACES")&&(v=d[f],_(v,0,m,f),Z=v),d.hasOwnProperty(f="ROUNDING_MODE")&&(v=d[f],_(v,0,8,f),Y=v),d.hasOwnProperty(f="EXPONENTIAL_AT")&&(v=d[f],v&&v.pop?(_(v[0],-m,0,f),_(v[1],0,m,f),ce=v[0],B=v[1]):(_(v,-m,m,f),ce=-(B=v<0?-v:v))),d.hasOwnProperty(f="RANGE"))if(v=d[f],v&&v.pop)_(v[0],-m,-1,f),_(v[1],1,m,f),J=v[0],fe=v[1];else if(_(v,-m,m,f),v)J=-(fe=v<0?-v:v);else throw Error(a+f+" cannot be zero: "+v);if(d.hasOwnProperty(f="CRYPTO"))if(v=d[f],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))j=v;else throw j=!v,Error(a+"crypto unavailable");else j=v;else throw Error(a+f+" not true or false: "+v);if(d.hasOwnProperty(f="MODULO_MODE")&&(v=d[f],_(v,0,9,f),ye=v),d.hasOwnProperty(f="POW_PRECISION")&&(v=d[f],_(v,0,m,f),Se=v),d.hasOwnProperty(f="FORMAT"))if(v=d[f],typeof v=="object")he=v;else throw Error(a+f+" not an object: "+v);if(d.hasOwnProperty(f="ALPHABET"))if(v=d[f],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))z=v.slice(0,10)=="0123456789",Ue=v;else throw Error(a+f+" invalid: "+v)}else throw Error(a+"Object expected: "+d);return{DECIMAL_PLACES:Z,ROUNDING_MODE:Y,EXPONENTIAL_AT:[ce,B],RANGE:[J,fe],CRYPTO:j,MODULO_MODE:ye,POW_PRECISION:Se,FORMAT:he,ALPHABET:Ue}},F.isBigNumber=function(d){if(!d||d._isBigNumber!==!0)return!1;if(!F.DEBUG)return!0;var f,v,C=d.c,S=d.e,k=d.s;e:if({}.toString.call(C)=="[object Array]"){if((k===1||k===-1)&&S>=-m&&S<=m&&S===o(S)){if(C[0]===0){if(S===0&&C.length===1)return!0;break e}if(f=(S+1)%l,f<1&&(f+=l),String(C[0]).length==f){for(f=0;f<C.length;f++)if(v=C[f],v<0||v>=s||v!==o(v))break e;if(v!==0)return!0}}}else if(C===null&&S===null&&(k===null||k===1||k===-1))return!0;throw Error(a+"Invalid BigNumber: "+d)},F.maximum=F.max=function(){return _e(arguments,-1)},F.minimum=F.min=function(){return _e(arguments,1)},F.random=function(){var d=9007199254740992,f=Math.random()*d&2097151?function(){return o(Math.random()*d)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(v){var C,S,k,M,x,A=0,O=[],I=new F(re);if(v==null?v=Z:_(v,0,m),M=n(v/l),j)if(crypto.getRandomValues){for(C=crypto.getRandomValues(new Uint32Array(M*=2));A<M;)x=C[A]*131072+(C[A+1]>>>11),x>=9e15?(S=crypto.getRandomValues(new Uint32Array(2)),C[A]=S[0],C[A+1]=S[1]):(O.push(x%1e14),A+=2);A=M/2}else if(crypto.randomBytes){for(C=crypto.randomBytes(M*=7);A<M;)x=(C[A]&31)*281474976710656+C[A+1]*1099511627776+C[A+2]*4294967296+C[A+3]*16777216+(C[A+4]<<16)+(C[A+5]<<8)+C[A+6],x>=9e15?crypto.randomBytes(7).copy(C,A):(O.push(x%1e14),A+=7);A=M/7}else throw j=!1,Error(a+"crypto unavailable");if(!j)for(;A<M;)x=f(),x<9e15&&(O[A++]=x%1e14);for(M=O[--A],v%=l,M&&v&&(x=p[l-v],O[A]=o(M/x)*x);O[A]===0;O.pop(),A--);if(A<0)O=[k=0];else{for(k=-1;O[0]===0;O.splice(0,1),k-=l);for(A=1,x=O[0];x>=10;x/=10,A++);A<l&&(k-=l-A)}return I.e=k,I.c=O,I}}(),F.sum=function(){for(var d=1,f=arguments,v=new F(f[0]);d<f.length;)v=v.plus(f[d++]);return v},R=function(){var d="0123456789";function f(v,C,S,k){for(var M,x=[0],A,O=0,I=v.length;O<I;){for(A=x.length;A--;x[A]*=C);for(x[0]+=k.indexOf(v.charAt(O++)),M=0;M<x.length;M++)x[M]>S-1&&(x[M+1]==null&&(x[M+1]=0),x[M+1]+=x[M]/S|0,x[M]%=S)}return x.reverse()}return function(v,C,S,k,M){var x,A,O,I,U,se,ie,Ce,me=v.indexOf("."),Be=Z,Ie=Y;for(me>=0&&(I=Se,Se=0,v=v.replace(".",""),Ce=new F(C),se=Ce.pow(v.length-me),Se=I,Ce.c=f(X(y(se.c),se.e,"0"),10,S,d),Ce.e=Ce.c.length),ie=f(v,C,S,M?(x=Ue,d):(x=d,Ue)),O=I=ie.length;ie[--I]==0;ie.pop());if(!ie[0])return x.charAt(0);if(me<0?--O:(se.c=ie,se.e=O,se.s=k,se=N(se,Ce,Be,Ie,S),ie=se.c,U=se.r,O=se.e),A=O+Be+1,me=ie[A],I=S/2,U=U||A<0||ie[A+1]!=null,U=Ie<4?(me!=null||U)&&(Ie==0||Ie==(se.s<0?3:2)):me>I||me==I&&(Ie==4||U||Ie==6&&ie[A-1]&1||Ie==(se.s<0?8:7)),A<1||!ie[0])v=U?X(x.charAt(1),-Be,x.charAt(0)):x.charAt(0);else{if(ie.length=A,U)for(--S;++ie[--A]>S;)ie[A]=0,A||(++O,ie=[1].concat(ie));for(I=ie.length;!ie[--I];);for(me=0,v="";me<=I;v+=x.charAt(ie[me++]));v=X(v,O,x.charAt(0))}return v}}(),N=function(){function d(C,S,k){var M,x,A,O,I=0,U=C.length,se=S%h,ie=S/h|0;for(C=C.slice();U--;)A=C[U]%h,O=C[U]/h|0,M=ie*A+O*se,x=se*A+M%h*h+I,I=(x/k|0)+(M/h|0)+ie*O,C[U]=x%k;return I&&(C=[I].concat(C)),C}function f(C,S,k,M){var x,A;if(k!=M)A=k>M?1:-1;else for(x=A=0;x<k;x++)if(C[x]!=S[x]){A=C[x]>S[x]?1:-1;break}return A}function v(C,S,k,M){for(var x=0;k--;)C[k]-=x,x=C[k]<S[k]?1:0,C[k]=x*M+C[k]-S[k];for(;!C[0]&&C.length>1;C.splice(0,1));}return function(C,S,k,M,x){var A,O,I,U,se,ie,Ce,me,Be,Ie,ge,Oe,xe,at,zr,dt,sr,Xe=C.s==S.s?1:-1,Ye=C.c,He=S.c;if(!Ye||!Ye[0]||!He||!He[0])return new F(!C.s||!S.s||(Ye?He&&Ye[0]==He[0]:!He)?NaN:Ye&&Ye[0]==0||!He?Xe*0:Xe/0);for(me=new F(Xe),Be=me.c=[],O=C.e-S.e,Xe=k+O+1,x||(x=s,O=T(C.e/l)-T(S.e/l),Xe=Xe/l|0),I=0;He[I]==(Ye[I]||0);I++);if(He[I]>(Ye[I]||0)&&O--,Xe<0)Be.push(1),U=!0;else{for(at=Ye.length,dt=He.length,I=0,Xe+=2,se=o(x/(He[0]+1)),se>1&&(He=d(He,se,x),Ye=d(Ye,se,x),dt=He.length,at=Ye.length),xe=dt,Ie=Ye.slice(0,dt),ge=Ie.length;ge<dt;Ie[ge++]=0);sr=He.slice(),sr=[0].concat(sr),zr=He[0],He[1]>=x/2&&zr++;do{if(se=0,A=f(He,Ie,dt,ge),A<0){if(Oe=Ie[0],dt!=ge&&(Oe=Oe*x+(Ie[1]||0)),se=o(Oe/zr),se>1)for(se>=x&&(se=x-1),ie=d(He,se,x),Ce=ie.length,ge=Ie.length;f(ie,Ie,Ce,ge)==1;)se--,v(ie,dt<Ce?sr:He,Ce,x),Ce=ie.length,A=1;else se==0&&(A=se=1),ie=He.slice(),Ce=ie.length;if(Ce<ge&&(ie=[0].concat(ie)),v(Ie,ie,ge,x),ge=Ie.length,A==-1)for(;f(He,Ie,dt,ge)<1;)se++,v(Ie,dt<ge?sr:He,ge,x),ge=Ie.length}else A===0&&(se++,Ie=[0]);Be[I++]=se,Ie[0]?Ie[ge++]=Ye[xe]||0:(Ie=[Ye[xe]],ge=1)}while((xe++<at||Ie[0]!=null)&&Xe--);U=Ie[0]!=null,Be[0]||Be.splice(0,1)}if(x==s){for(I=1,Xe=Be[0];Xe>=10;Xe/=10,I++);ae(me,k+(me.e=I+O*l-1)+1,M,U)}else me.e=O,me.r=+U;return me}}();function ve(d,f,v,C){var S,k,M,x,A;if(v==null?v=Y:_(v,0,8),!d.c)return d.toString();if(S=d.c[0],M=d.e,f==null)A=y(d.c),A=C==1||C==2&&(M<=ce||M>=B)?V(A,M):X(A,M,"0");else if(d=ae(new F(d),f,v),k=d.e,A=y(d.c),x=A.length,C==1||C==2&&(f<=k||k<=ce)){for(;x<f;A+="0",x++);A=V(A,k)}else if(f-=M+(C===2&&k>M),A=X(A,k,"0"),k+1>x){if(--f>0)for(A+=".";f--;A+="0");}else if(f+=k-x,f>0)for(k+1==x&&(A+=".");f--;A+="0");return d.s<0&&S?"-"+A:A}function _e(d,f){for(var v,C,S=1,k=new F(d[0]);S<d.length;S++)C=new F(d[S]),(!C.s||(v=b(k,C))===f||v===0&&k.s===f)&&(k=C);return k}function ue(d,f,v){for(var C=1,S=f.length;!f[--S];f.pop());for(S=f[0];S>=10;S/=10,C++);return(v=C+v*l-1)>fe?d.c=d.e=null:v<J?d.c=[d.e=0]:(d.e=v,d.c=f),d}Q=function(){var d=/^(-?)0([xbo])(?=\w[\w.]*$)/i,f=/^([^.]+)\.$/,v=/^\.([^.]+)$/,C=/^-?(Infinity|NaN)$/,S=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(k,M,x,A){var O,I=x?M:M.replace(S,"");if(C.test(I))k.s=isNaN(I)?null:I<0?-1:1;else{if(!x&&(I=I.replace(d,function(U,se,ie){return O=(ie=ie.toLowerCase())=="x"?16:ie=="b"?2:8,!A||A==O?se:U}),A&&(O=A,I=I.replace(f,"$1").replace(v,"0.$1")),M!=I))return new F(I,O);if(F.DEBUG)throw Error(a+"Not a"+(A?" base "+A:"")+" number: "+M);k.s=null}k.c=k.e=null}}();function ae(d,f,v,C){var S,k,M,x,A,O,I,U=d.c,se=p;if(U){e:{for(S=1,x=U[0];x>=10;x/=10,S++);if(k=f-S,k<0)k+=l,M=f,A=U[O=0],I=o(A/se[S-M-1]%10);else if(O=n((k+1)/l),O>=U.length)if(C){for(;U.length<=O;U.push(0));A=I=0,S=1,k%=l,M=k-l+1}else break e;else{for(A=x=U[O],S=1;x>=10;x/=10,S++);k%=l,M=k-l+S,I=M<0?0:o(A/se[S-M-1]%10)}if(C=C||f<0||U[O+1]!=null||(M<0?A:A%se[S-M-1]),C=v<4?(I||C)&&(v==0||v==(d.s<0?3:2)):I>5||I==5&&(v==4||C||v==6&&(k>0?M>0?A/se[S-M]:0:U[O-1])%10&1||v==(d.s<0?8:7)),f<1||!U[0])return U.length=0,C?(f-=d.e+1,U[0]=se[(l-f%l)%l],d.e=-f||0):U[0]=d.e=0,d;if(k==0?(U.length=O,x=1,O--):(U.length=O+1,x=se[l-k],U[O]=M>0?o(A/se[S-M]%se[M])*x:0),C)for(;;)if(O==0){for(k=1,M=U[0];M>=10;M/=10,k++);for(M=U[0]+=x,x=1;M>=10;M/=10,x++);k!=x&&(d.e++,U[0]==s&&(U[0]=1));break}else{if(U[O]+=x,U[O]!=s)break;U[O--]=0,x=1}for(k=U.length;U[--k]===0;U.pop());}d.e>fe?d.c=d.e=null:d.e<J&&(d.c=[d.e=0])}return d}function K(d){var f,v=d.e;return v===null?d.toString():(f=y(d.c),f=v<=ce||v>=B?V(f,v):X(f,v,"0"),d.s<0?"-"+f:f)}return E.absoluteValue=E.abs=function(){var d=new F(this);return d.s<0&&(d.s=1),d},E.comparedTo=function(d,f){return b(this,new F(d,f))},E.decimalPlaces=E.dp=function(d,f){var v,C,S,k=this;if(d!=null)return _(d,0,m),f==null?f=Y:_(f,0,8),ae(new F(k),d+k.e+1,f);if(!(v=k.c))return null;if(C=((S=v.length-1)-T(this.e/l))*l,S=v[S])for(;S%10==0;S/=10,C--);return C<0&&(C=0),C},E.dividedBy=E.div=function(d,f){return N(this,new F(d,f),Z,Y)},E.dividedToIntegerBy=E.idiv=function(d,f){return N(this,new F(d,f),0,1)},E.exponentiatedBy=E.pow=function(d,f){var v,C,S,k,M,x,A,O,I,U=this;if(d=new F(d),d.c&&!d.isInteger())throw Error(a+"Exponent not an integer: "+K(d));if(f!=null&&(f=new F(f)),x=d.e>14,!U.c||!U.c[0]||U.c[0]==1&&!U.e&&U.c.length==1||!d.c||!d.c[0])return I=new F(Math.pow(+K(U),x?d.s*(2-D(d)):+K(d))),f?I.mod(f):I;if(A=d.s<0,f){if(f.c?!f.c[0]:!f.s)return new F(NaN);C=!A&&U.isInteger()&&f.isInteger(),C&&(U=U.mod(f))}else{if(d.e>9&&(U.e>0||U.e<-1||(U.e==0?U.c[0]>1||x&&U.c[1]>=24e7:U.c[0]<8e13||x&&U.c[0]<=9999975e7)))return k=U.s<0&&D(d)?-0:0,U.e>-1&&(k=1/k),new F(A?1/k:k);Se&&(k=n(Se/l+2))}for(x?(v=new F(.5),A&&(d.s=1),O=D(d)):(S=Math.abs(+K(d)),O=S%2),I=new F(re);;){if(O){if(I=I.times(U),!I.c)break;k?I.c.length>k&&(I.c.length=k):C&&(I=I.mod(f))}if(S){if(S=o(S/2),S===0)break;O=S%2}else if(d=d.times(v),ae(d,d.e+1,1),d.e>14)O=D(d);else{if(S=+K(d),S===0)break;O=S%2}U=U.times(U),k?U.c&&U.c.length>k&&(U.c.length=k):C&&(U=U.mod(f))}return C?I:(A&&(I=re.div(I)),f?I.mod(f):k?ae(I,Se,Y,M):I)},E.integerValue=function(d){var f=new F(this);return d==null?d=Y:_(d,0,8),ae(f,f.e+1,d)},E.isEqualTo=E.eq=function(d,f){return b(this,new F(d,f))===0},E.isFinite=function(){return!!this.c},E.isGreaterThan=E.gt=function(d,f){return b(this,new F(d,f))>0},E.isGreaterThanOrEqualTo=E.gte=function(d,f){return(f=b(this,new F(d,f)))===1||f===0},E.isInteger=function(){return!!this.c&&T(this.e/l)>this.c.length-2},E.isLessThan=E.lt=function(d,f){return b(this,new F(d,f))<0},E.isLessThanOrEqualTo=E.lte=function(d,f){return(f=b(this,new F(d,f)))===-1||f===0},E.isNaN=function(){return!this.s},E.isNegative=function(){return this.s<0},E.isPositive=function(){return this.s>0},E.isZero=function(){return!!this.c&&this.c[0]==0},E.minus=function(d,f){var v,C,S,k,M=this,x=M.s;if(d=new F(d,f),f=d.s,!x||!f)return new F(NaN);if(x!=f)return d.s=-f,M.plus(d);var A=M.e/l,O=d.e/l,I=M.c,U=d.c;if(!A||!O){if(!I||!U)return I?(d.s=-f,d):new F(U?M:NaN);if(!I[0]||!U[0])return U[0]?(d.s=-f,d):new F(I[0]?M:Y==3?-0:0)}if(A=T(A),O=T(O),I=I.slice(),x=A-O){for((k=x<0)?(x=-x,S=I):(O=A,S=U),S.reverse(),f=x;f--;S.push(0));S.reverse()}else for(C=(k=(x=I.length)<(f=U.length))?x:f,x=f=0;f<C;f++)if(I[f]!=U[f]){k=I[f]<U[f];break}if(k&&(S=I,I=U,U=S,d.s=-d.s),f=(C=U.length)-(v=I.length),f>0)for(;f--;I[v++]=0);for(f=s-1;C>x;){if(I[--C]<U[C]){for(v=C;v&&!I[--v];I[v]=f);--I[v],I[C]+=s}I[C]-=U[C]}for(;I[0]==0;I.splice(0,1),--O);return I[0]?ue(d,I,O):(d.s=Y==3?-1:1,d.c=[d.e=0],d)},E.modulo=E.mod=function(d,f){var v,C,S=this;return d=new F(d,f),!S.c||!d.s||d.c&&!d.c[0]?new F(NaN):!d.c||S.c&&!S.c[0]?new F(S):(ye==9?(C=d.s,d.s=1,v=N(S,d,0,3),d.s=C,v.s*=C):v=N(S,d,0,ye),d=S.minus(v.times(d)),!d.c[0]&&ye==1&&(d.s=S.s),d)},E.multipliedBy=E.times=function(d,f){var v,C,S,k,M,x,A,O,I,U,se,ie,Ce,me,Be,Ie=this,ge=Ie.c,Oe=(d=new F(d,f)).c;if(!ge||!Oe||!ge[0]||!Oe[0])return!Ie.s||!d.s||ge&&!ge[0]&&!Oe||Oe&&!Oe[0]&&!ge?d.c=d.e=d.s=null:(d.s*=Ie.s,!ge||!Oe?d.c=d.e=null:(d.c=[0],d.e=0)),d;for(C=T(Ie.e/l)+T(d.e/l),d.s*=Ie.s,A=ge.length,U=Oe.length,A<U&&(Ce=ge,ge=Oe,Oe=Ce,S=A,A=U,U=S),S=A+U,Ce=[];S--;Ce.push(0));for(me=s,Be=h,S=U;--S>=0;){for(v=0,se=Oe[S]%Be,ie=Oe[S]/Be|0,M=A,k=S+M;k>S;)O=ge[--M]%Be,I=ge[M]/Be|0,x=ie*O+I*se,O=se*O+x%Be*Be+Ce[k]+v,v=(O/me|0)+(x/Be|0)+ie*I,Ce[k--]=O%me;Ce[k]=v}return v?++C:Ce.splice(0,1),ue(d,Ce,C)},E.negated=function(){var d=new F(this);return d.s=-d.s||null,d},E.plus=function(d,f){var v,C=this,S=C.s;if(d=new F(d,f),f=d.s,!S||!f)return new F(NaN);if(S!=f)return d.s=-f,C.minus(d);var k=C.e/l,M=d.e/l,x=C.c,A=d.c;if(!k||!M){if(!x||!A)return new F(S/0);if(!x[0]||!A[0])return A[0]?d:new F(x[0]?C:S*0)}if(k=T(k),M=T(M),x=x.slice(),S=k-M){for(S>0?(M=k,v=A):(S=-S,v=x),v.reverse();S--;v.push(0));v.reverse()}for(S=x.length,f=A.length,S-f<0&&(v=A,A=x,x=v,f=S),S=0;f;)S=(x[--f]=x[f]+A[f]+S)/s|0,x[f]=s===x[f]?0:x[f]%s;return S&&(x=[S].concat(x),++M),ue(d,x,M)},E.precision=E.sd=function(d,f){var v,C,S,k=this;if(d!=null&&d!==!!d)return _(d,1,m),f==null?f=Y:_(f,0,8),ae(new F(k),d,f);if(!(v=k.c))return null;if(S=v.length-1,C=S*l+1,S=v[S]){for(;S%10==0;S/=10,C--);for(S=v[0];S>=10;S/=10,C++);}return d&&k.e+1>C&&(C=k.e+1),C},E.shiftedBy=function(d){return _(d,-c,c),this.times("1e"+d)},E.squareRoot=E.sqrt=function(){var d,f,v,C,S,k=this,M=k.c,x=k.s,A=k.e,O=Z+4,I=new F("0.5");if(x!==1||!M||!M[0])return new F(!x||x<0&&(!M||M[0])?NaN:M?k:1/0);if(x=Math.sqrt(+K(k)),x==0||x==1/0?(f=y(M),(f.length+A)%2==0&&(f+="0"),x=Math.sqrt(+f),A=T((A+1)/2)-(A<0||A%2),x==1/0?f="5e"+A:(f=x.toExponential(),f=f.slice(0,f.indexOf("e")+1)+A),v=new F(f)):v=new F(x+""),v.c[0]){for(A=v.e,x=A+O,x<3&&(x=0);;)if(S=v,v=I.times(S.plus(N(k,S,O,1))),y(S.c).slice(0,x)===(f=y(v.c)).slice(0,x))if(v.e<A&&--x,f=f.slice(x-3,x+1),f=="9999"||!C&&f=="4999"){if(!C&&(ae(S,S.e+Z+2,0),S.times(S).eq(k))){v=S;break}O+=4,x+=4,C=1}else{(!+f||!+f.slice(1)&&f.charAt(0)=="5")&&(ae(v,v.e+Z+2,1),d=!v.times(v).eq(k));break}}return ae(v,v.e+Z+1,Y,d)},E.toExponential=function(d,f){return d!=null&&(_(d,0,m),d++),ve(this,d,f,1)},E.toFixed=function(d,f){return d!=null&&(_(d,0,m),d=d+this.e+1),ve(this,d,f)},E.toFormat=function(d,f,v){var C,S=this;if(v==null)d!=null&&f&&typeof f=="object"?(v=f,f=null):d&&typeof d=="object"?(v=d,d=f=null):v=he;else if(typeof v!="object")throw Error(a+"Argument not an object: "+v);if(C=S.toFixed(d,f),S.c){var k,M=C.split("."),x=+v.groupSize,A=+v.secondaryGroupSize,O=v.groupSeparator||"",I=M[0],U=M[1],se=S.s<0,ie=se?I.slice(1):I,Ce=ie.length;if(A&&(k=x,x=A,A=k,Ce-=k),x>0&&Ce>0){for(k=Ce%x||x,I=ie.substr(0,k);k<Ce;k+=x)I+=O+ie.substr(k,x);A>0&&(I+=O+ie.slice(k)),se&&(I="-"+I)}C=U?I+(v.decimalSeparator||"")+((A=+v.fractionGroupSize)?U.replace(new RegExp("\\d{"+A+"}\\B","g"),"$&"+(v.fractionGroupSeparator||"")):U):I}return(v.prefix||"")+C+(v.suffix||"")},E.toFraction=function(d){var f,v,C,S,k,M,x,A,O,I,U,se,ie=this,Ce=ie.c;if(d!=null&&(x=new F(d),!x.isInteger()&&(x.c||x.s!==1)||x.lt(re)))throw Error(a+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+K(x));if(!Ce)return new F(ie);for(f=new F(re),O=v=new F(re),C=A=new F(re),se=y(Ce),k=f.e=se.length-ie.e-1,f.c[0]=p[(M=k%l)<0?l+M:M],d=!d||x.comparedTo(f)>0?k>0?f:O:x,M=fe,fe=1/0,x=new F(se),A.c[0]=0;I=N(x,f,0,1),S=v.plus(I.times(C)),S.comparedTo(d)!=1;)v=C,C=S,O=A.plus(I.times(S=O)),A=S,f=x.minus(I.times(S=f)),x=S;return S=N(d.minus(v),C,0,1),A=A.plus(S.times(O)),v=v.plus(S.times(C)),A.s=O.s=ie.s,k=k*2,U=N(O,C,k,Y).minus(ie).abs().comparedTo(N(A,v,k,Y).minus(ie).abs())<1?[O,C]:[A,v],fe=M,U},E.toNumber=function(){return+K(this)},E.toPrecision=function(d,f){return d!=null&&_(d,1,m),ve(this,d,f,2)},E.toString=function(d){var f,v=this,C=v.s,S=v.e;return S===null?C?(f="Infinity",C<0&&(f="-"+f)):f="NaN":(d==null?f=S<=ce||S>=B?V(y(v.c),S):X(y(v.c),S,"0"):d===10&&z?(v=ae(new F(v),Z+S+1,Y),f=X(y(v.c),v.e,"0")):(_(d,2,Ue.length,"Base"),f=R(X(y(v.c),S,"0"),10,d,C,!0)),C<0&&v.c[0]&&(f="-"+f)),f},E.valueOf=E.toJSON=function(){return K(this)},E._isBigNumber=!0,P!=null&&F.set(P),F}function T(P){var N=P|0;return P>0||P===N?N:N-1}function y(P){for(var N,R,Q=1,E=P.length,re=P[0]+"";Q<E;){for(N=P[Q++]+"",R=l-N.length;R--;N="0"+N);re+=N}for(E=re.length;re.charCodeAt(--E)===48;);return re.slice(0,E+1||1)}function b(P,N){var R,Q,E=P.c,re=N.c,Z=P.s,Y=N.s,ce=P.e,B=N.e;if(!Z||!Y)return null;if(R=E&&!E[0],Q=re&&!re[0],R||Q)return R?Q?0:-Y:Z;if(Z!=Y)return Z;if(R=Z<0,Q=ce==B,!E||!re)return Q?0:!E^R?1:-1;if(!Q)return ce>B^R?1:-1;for(Y=(ce=E.length)<(B=re.length)?ce:B,Z=0;Z<Y;Z++)if(E[Z]!=re[Z])return E[Z]>re[Z]^R?1:-1;return ce==B?0:ce>B^R?1:-1}function _(P,N,R,Q){if(P<N||P>R||P!==o(P))throw Error(a+(Q||"Argument")+(typeof P=="number"?P<N||P>R?" out of range: ":" not an integer: ":" not a primitive number: ")+String(P))}function D(P){var N=P.c.length-1;return T(P.e/l)==N&&P.c[N]%2!=0}function V(P,N){return(P.length>1?P.charAt(0)+"."+P.slice(1):P)+(N<0?"e":"e+")+N}function X(P,N,R){var Q,E;if(N<0){for(E=R+".";++N;E+=R);P=E+P}else if(Q=P.length,++N>Q){for(E=R,N-=Q;--N;E+=R);P+=E}else N<Q&&(P=P.slice(0,N)+"."+P.slice(N));return P}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Ao<"u"&&Ao.exports?Ao.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Qu)});var nd=ee((YA,rd)=>{"use strict";var ed=hi(),td=rd.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,a={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function s(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(p){var h=a[p];return typeof h=="string"?h:"\\u"+("0000"+p.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function l(c,p){var h,m,g,T,y=n,b,_=p[c],D=_!=null&&(_ instanceof ed||ed.isBigNumber(_));switch(_&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(c)),typeof i=="function"&&(_=i.call(p,c,_)),typeof _){case"string":return D?_:s(_);case"number":return isFinite(_)?String(_):"null";case"boolean":case"null":case"bigint":return String(_);case"object":if(!_)return"null";if(n+=o,b=[],Object.prototype.toString.apply(_)==="[object Array]"){for(T=_.length,h=0;h<T;h+=1)b[h]=l(h,_)||"null";return g=b.length===0?"[]":n?`[
|
|
8
|
+
`}yield n}static#a;static#i;static async#s(){return this.#a||=(await import("./dist-HN2P3FRX.js")).HttpsProxyAgent,this.#a}static async#l(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await import("./src-CXU6MEQY.js")).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((a,i)=>{i==="set-cookie"?e.append(i,a):e.set(i,a)});return e}};Xr.Gaxios=Io;Yr=Io});var rt=te(ct=>{"use strict";var wb=ct&&ct.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Eb=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wb(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.instance=ct.Gaxios=ct.GaxiosError=void 0;ct.request=xb;var Zu=Xu();Object.defineProperty(ct,"Gaxios",{enumerable:!0,get:function(){return Zu.Gaxios}});var Tb=ci();Object.defineProperty(ct,"GaxiosError",{enumerable:!0,get:function(){return Tb.GaxiosError}});Eb(pi(),ct);ct.instance=new Zu.Gaxios;async function xb(t){return ct.instance.request(t)}});var hi=te((Qu,Ao)=>{"use strict";(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,a="[BigNumber Error] ",i=a+"Number primitive has more than 15 significant digits: ",s=1e14,l=14,c=9007199254740991,p=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,g=1e9;function y(N){var R,O,ee,E=U.prototype={constructor:U,toString:null,valueOf:null},Q=new U(1),X=20,W=4,ue=-7,V=21,K=-1e7,me=1e7,j=!1,ve=1,Se=0,fe={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Fe="0123456789abcdefghijklmnopqrstuvwxyz",z=!0;function U(d,m){var v,C,x,k,D,T,A,P,I=this;if(!(I instanceof U))return new U(d,m);if(m==null){if(d&&d._isBigNumber===!0){I.s=d.s,!d.c||d.e>me?I.c=I.e=null:d.e<K?I.c=[I.e=0]:(I.e=d.e,I.c=d.c.slice());return}if((T=typeof d=="number")&&d*0==0){if(I.s=1/d<0?(d=-d,-1):1,d===~~d){for(k=0,D=d;D>=10;D/=10,k++);k>me?I.c=I.e=null:(I.e=k,I.c=[d]);return}P=String(d)}else{if(!r.test(P=String(d)))return ee(I,P,T);I.s=P.charCodeAt(0)==45?(P=P.slice(1),-1):1}(k=P.indexOf("."))>-1&&(P=P.replace(".","")),(D=P.search(/e/i))>0?(k<0&&(k=D),k+=+P.slice(D+1),P=P.substring(0,D)):k<0&&(k=P.length)}else{if(_(m,2,Fe.length,"Base"),m==10&&z)return I=new U(d),ae(I,X+I.e+1,W);if(P=String(d),T=typeof d=="number"){if(d*0!=0)return ee(I,P,T,m);if(I.s=1/d<0?(P=P.slice(1),-1):1,U.DEBUG&&P.replace(/^0\.0*|\./,"").length>15)throw Error(i+d)}else I.s=P.charCodeAt(0)===45?(P=P.slice(1),-1):1;for(v=Fe.slice(0,m),k=D=0,A=P.length;D<A;D++)if(v.indexOf(C=P.charAt(D))<0){if(C=="."){if(D>k){k=A;continue}}else if(!x&&(P==P.toUpperCase()&&(P=P.toLowerCase())||P==P.toLowerCase()&&(P=P.toUpperCase()))){x=!0,D=-1,k=0;continue}return ee(I,String(d),T,m)}T=!1,P=O(P,m,10,I.s),(k=P.indexOf("."))>-1?P=P.replace(".",""):k=P.length}for(D=0;P.charCodeAt(D)===48;D++);for(A=P.length;P.charCodeAt(--A)===48;);if(P=P.slice(D,++A)){if(A-=D,T&&U.DEBUG&&A>15&&(d>c||d!==o(d)))throw Error(i+I.s*d);if((k=k-D-1)>me)I.c=I.e=null;else if(k<K)I.c=[I.e=0];else{if(I.e=k,I.c=[],D=(k+1)%l,k<0&&(D+=l),D<A){for(D&&I.c.push(+P.slice(0,D)),A-=l;D<A;)I.c.push(+P.slice(D,D+=l));D=l-(P=P.slice(D)).length}else D-=A;for(;D--;P+="0");I.c.push(+P)}}else I.c=[I.e=0]}U.clone=y,U.ROUND_UP=0,U.ROUND_DOWN=1,U.ROUND_CEIL=2,U.ROUND_FLOOR=3,U.ROUND_HALF_UP=4,U.ROUND_HALF_DOWN=5,U.ROUND_HALF_EVEN=6,U.ROUND_HALF_CEIL=7,U.ROUND_HALF_FLOOR=8,U.EUCLID=9,U.config=U.set=function(d){var m,v;if(d!=null)if(typeof d=="object"){if(d.hasOwnProperty(m="DECIMAL_PLACES")&&(v=d[m],_(v,0,g,m),X=v),d.hasOwnProperty(m="ROUNDING_MODE")&&(v=d[m],_(v,0,8,m),W=v),d.hasOwnProperty(m="EXPONENTIAL_AT")&&(v=d[m],v&&v.pop?(_(v[0],-g,0,m),_(v[1],0,g,m),ue=v[0],V=v[1]):(_(v,-g,g,m),ue=-(V=v<0?-v:v))),d.hasOwnProperty(m="RANGE"))if(v=d[m],v&&v.pop)_(v[0],-g,-1,m),_(v[1],1,g,m),K=v[0],me=v[1];else if(_(v,-g,g,m),v)K=-(me=v<0?-v:v);else throw Error(a+m+" cannot be zero: "+v);if(d.hasOwnProperty(m="CRYPTO"))if(v=d[m],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))j=v;else throw j=!v,Error(a+"crypto unavailable");else j=v;else throw Error(a+m+" not true or false: "+v);if(d.hasOwnProperty(m="MODULO_MODE")&&(v=d[m],_(v,0,9,m),ve=v),d.hasOwnProperty(m="POW_PRECISION")&&(v=d[m],_(v,0,g,m),Se=v),d.hasOwnProperty(m="FORMAT"))if(v=d[m],typeof v=="object")fe=v;else throw Error(a+m+" not an object: "+v);if(d.hasOwnProperty(m="ALPHABET"))if(v=d[m],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))z=v.slice(0,10)=="0123456789",Fe=v;else throw Error(a+m+" invalid: "+v)}else throw Error(a+"Object expected: "+d);return{DECIMAL_PLACES:X,ROUNDING_MODE:W,EXPONENTIAL_AT:[ue,V],RANGE:[K,me],CRYPTO:j,MODULO_MODE:ve,POW_PRECISION:Se,FORMAT:fe,ALPHABET:Fe}},U.isBigNumber=function(d){if(!d||d._isBigNumber!==!0)return!1;if(!U.DEBUG)return!0;var m,v,C=d.c,x=d.e,k=d.s;e:if({}.toString.call(C)=="[object Array]"){if((k===1||k===-1)&&x>=-g&&x<=g&&x===o(x)){if(C[0]===0){if(x===0&&C.length===1)return!0;break e}if(m=(x+1)%l,m<1&&(m+=l),String(C[0]).length==m){for(m=0;m<C.length;m++)if(v=C[m],v<0||v>=s||v!==o(v))break e;if(v!==0)return!0}}}else if(C===null&&x===null&&(k===null||k===1||k===-1))return!0;throw Error(a+"Invalid BigNumber: "+d)},U.maximum=U.max=function(){return we(arguments,-1)},U.minimum=U.min=function(){return we(arguments,1)},U.random=function(){var d=9007199254740992,m=Math.random()*d&2097151?function(){return o(Math.random()*d)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(v){var C,x,k,D,T,A=0,P=[],I=new U(Q);if(v==null?v=X:_(v,0,g),D=n(v/l),j)if(crypto.getRandomValues){for(C=crypto.getRandomValues(new Uint32Array(D*=2));A<D;)T=C[A]*131072+(C[A+1]>>>11),T>=9e15?(x=crypto.getRandomValues(new Uint32Array(2)),C[A]=x[0],C[A+1]=x[1]):(P.push(T%1e14),A+=2);A=D/2}else if(crypto.randomBytes){for(C=crypto.randomBytes(D*=7);A<D;)T=(C[A]&31)*281474976710656+C[A+1]*1099511627776+C[A+2]*4294967296+C[A+3]*16777216+(C[A+4]<<16)+(C[A+5]<<8)+C[A+6],T>=9e15?crypto.randomBytes(7).copy(C,A):(P.push(T%1e14),A+=7);A=D/7}else throw j=!1,Error(a+"crypto unavailable");if(!j)for(;A<D;)T=m(),T<9e15&&(P[A++]=T%1e14);for(D=P[--A],v%=l,D&&v&&(T=p[l-v],P[A]=o(D/T)*T);P[A]===0;P.pop(),A--);if(A<0)P=[k=0];else{for(k=-1;P[0]===0;P.splice(0,1),k-=l);for(A=1,T=P[0];T>=10;T/=10,A++);A<l&&(k-=l-A)}return I.e=k,I.c=P,I}}(),U.sum=function(){for(var d=1,m=arguments,v=new U(m[0]);d<m.length;)v=v.plus(m[d++]);return v},O=function(){var d="0123456789";function m(v,C,x,k){for(var D,T=[0],A,P=0,I=v.length;P<I;){for(A=T.length;A--;T[A]*=C);for(T[0]+=k.indexOf(v.charAt(P++)),D=0;D<T.length;D++)T[D]>x-1&&(T[D+1]==null&&(T[D+1]=0),T[D+1]+=T[D]/x|0,T[D]%=x)}return T.reverse()}return function(v,C,x,k,D){var T,A,P,I,F,se,ie,Ce,ge=v.indexOf("."),Be=X,Ie=W;for(ge>=0&&(I=Se,Se=0,v=v.replace(".",""),Ce=new U(C),se=Ce.pow(v.length-ge),Se=I,Ce.c=m(Z(f(se.c),se.e,"0"),10,x,d),Ce.e=Ce.c.length),ie=m(v,C,x,D?(T=Fe,d):(T=d,Fe)),P=I=ie.length;ie[--I]==0;ie.pop());if(!ie[0])return T.charAt(0);if(ge<0?--P:(se.c=ie,se.e=P,se.s=k,se=R(se,Ce,Be,Ie,x),ie=se.c,F=se.r,P=se.e),A=P+Be+1,ge=ie[A],I=x/2,F=F||A<0||ie[A+1]!=null,F=Ie<4?(ge!=null||F)&&(Ie==0||Ie==(se.s<0?3:2)):ge>I||ge==I&&(Ie==4||F||Ie==6&&ie[A-1]&1||Ie==(se.s<0?8:7)),A<1||!ie[0])v=F?Z(T.charAt(1),-Be,T.charAt(0)):T.charAt(0);else{if(ie.length=A,F)for(--x;++ie[--A]>x;)ie[A]=0,A||(++P,ie=[1].concat(ie));for(I=ie.length;!ie[--I];);for(ge=0,v="";ge<=I;v+=T.charAt(ie[ge++]));v=Z(v,P,T.charAt(0))}return v}}(),R=function(){function d(C,x,k){var D,T,A,P,I=0,F=C.length,se=x%h,ie=x/h|0;for(C=C.slice();F--;)A=C[F]%h,P=C[F]/h|0,D=ie*A+P*se,T=se*A+D%h*h+I,I=(T/k|0)+(D/h|0)+ie*P,C[F]=T%k;return I&&(C=[I].concat(C)),C}function m(C,x,k,D){var T,A;if(k!=D)A=k>D?1:-1;else for(T=A=0;T<k;T++)if(C[T]!=x[T]){A=C[T]>x[T]?1:-1;break}return A}function v(C,x,k,D){for(var T=0;k--;)C[k]-=T,T=C[k]<x[k]?1:0,C[k]=T*D+C[k]-x[k];for(;!C[0]&&C.length>1;C.splice(0,1));}return function(C,x,k,D,T){var A,P,I,F,se,ie,Ce,ge,Be,Ie,ye,Oe,xe,at,zr,dt,sr,Xe=C.s==x.s?1:-1,Ye=C.c,He=x.c;if(!Ye||!Ye[0]||!He||!He[0])return new U(!C.s||!x.s||(Ye?He&&Ye[0]==He[0]:!He)?NaN:Ye&&Ye[0]==0||!He?Xe*0:Xe/0);for(ge=new U(Xe),Be=ge.c=[],P=C.e-x.e,Xe=k+P+1,T||(T=s,P=S(C.e/l)-S(x.e/l),Xe=Xe/l|0),I=0;He[I]==(Ye[I]||0);I++);if(He[I]>(Ye[I]||0)&&P--,Xe<0)Be.push(1),F=!0;else{for(at=Ye.length,dt=He.length,I=0,Xe+=2,se=o(T/(He[0]+1)),se>1&&(He=d(He,se,T),Ye=d(Ye,se,T),dt=He.length,at=Ye.length),xe=dt,Ie=Ye.slice(0,dt),ye=Ie.length;ye<dt;Ie[ye++]=0);sr=He.slice(),sr=[0].concat(sr),zr=He[0],He[1]>=T/2&&zr++;do{if(se=0,A=m(He,Ie,dt,ye),A<0){if(Oe=Ie[0],dt!=ye&&(Oe=Oe*T+(Ie[1]||0)),se=o(Oe/zr),se>1)for(se>=T&&(se=T-1),ie=d(He,se,T),Ce=ie.length,ye=Ie.length;m(ie,Ie,Ce,ye)==1;)se--,v(ie,dt<Ce?sr:He,Ce,T),Ce=ie.length,A=1;else se==0&&(A=se=1),ie=He.slice(),Ce=ie.length;if(Ce<ye&&(ie=[0].concat(ie)),v(Ie,ie,ye,T),ye=Ie.length,A==-1)for(;m(He,Ie,dt,ye)<1;)se++,v(Ie,dt<ye?sr:He,ye,T),ye=Ie.length}else A===0&&(se++,Ie=[0]);Be[I++]=se,Ie[0]?Ie[ye++]=Ye[xe]||0:(Ie=[Ye[xe]],ye=1)}while((xe++<at||Ie[0]!=null)&&Xe--);F=Ie[0]!=null,Be[0]||Be.splice(0,1)}if(T==s){for(I=1,Xe=Be[0];Xe>=10;Xe/=10,I++);ae(ge,k+(ge.e=I+P*l-1)+1,D,F)}else ge.e=P,ge.r=+F;return ge}}();function be(d,m,v,C){var x,k,D,T,A;if(v==null?v=W:_(v,0,8),!d.c)return d.toString();if(x=d.c[0],D=d.e,m==null)A=f(d.c),A=C==1||C==2&&(D<=ue||D>=V)?B(A,D):Z(A,D,"0");else if(d=ae(new U(d),m,v),k=d.e,A=f(d.c),T=A.length,C==1||C==2&&(m<=k||k<=ue)){for(;T<m;A+="0",T++);A=B(A,k)}else if(m-=D+(C===2&&k>D),A=Z(A,k,"0"),k+1>T){if(--m>0)for(A+=".";m--;A+="0");}else if(m+=k-T,m>0)for(k+1==T&&(A+=".");m--;A+="0");return d.s<0&&x?"-"+A:A}function we(d,m){for(var v,C,x=1,k=new U(d[0]);x<d.length;x++)C=new U(d[x]),(!C.s||(v=b(k,C))===m||v===0&&k.s===m)&&(k=C);return k}function de(d,m,v){for(var C=1,x=m.length;!m[--x];m.pop());for(x=m[0];x>=10;x/=10,C++);return(v=C+v*l-1)>me?d.c=d.e=null:v<K?d.c=[d.e=0]:(d.e=v,d.c=m),d}ee=function(){var d=/^(-?)0([xbo])(?=\w[\w.]*$)/i,m=/^([^.]+)\.$/,v=/^\.([^.]+)$/,C=/^-?(Infinity|NaN)$/,x=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(k,D,T,A){var P,I=T?D:D.replace(x,"");if(C.test(I))k.s=isNaN(I)?null:I<0?-1:1;else{if(!T&&(I=I.replace(d,function(F,se,ie){return P=(ie=ie.toLowerCase())=="x"?16:ie=="b"?2:8,!A||A==P?se:F}),A&&(P=A,I=I.replace(m,"$1").replace(v,"0.$1")),D!=I))return new U(I,P);if(U.DEBUG)throw Error(a+"Not a"+(A?" base "+A:"")+" number: "+D);k.s=null}k.c=k.e=null}}();function ae(d,m,v,C){var x,k,D,T,A,P,I,F=d.c,se=p;if(F){e:{for(x=1,T=F[0];T>=10;T/=10,x++);if(k=m-x,k<0)k+=l,D=m,A=F[P=0],I=o(A/se[x-D-1]%10);else if(P=n((k+1)/l),P>=F.length)if(C){for(;F.length<=P;F.push(0));A=I=0,x=1,k%=l,D=k-l+1}else break e;else{for(A=T=F[P],x=1;T>=10;T/=10,x++);k%=l,D=k-l+x,I=D<0?0:o(A/se[x-D-1]%10)}if(C=C||m<0||F[P+1]!=null||(D<0?A:A%se[x-D-1]),C=v<4?(I||C)&&(v==0||v==(d.s<0?3:2)):I>5||I==5&&(v==4||C||v==6&&(k>0?D>0?A/se[x-D]:0:F[P-1])%10&1||v==(d.s<0?8:7)),m<1||!F[0])return F.length=0,C?(m-=d.e+1,F[0]=se[(l-m%l)%l],d.e=-m||0):F[0]=d.e=0,d;if(k==0?(F.length=P,T=1,P--):(F.length=P+1,T=se[l-k],F[P]=D>0?o(A/se[x-D]%se[D])*T:0),C)for(;;)if(P==0){for(k=1,D=F[0];D>=10;D/=10,k++);for(D=F[0]+=T,T=1;D>=10;D/=10,T++);k!=T&&(d.e++,F[0]==s&&(F[0]=1));break}else{if(F[P]+=T,F[P]!=s)break;F[P--]=0,T=1}for(k=F.length;F[--k]===0;F.pop());}d.e>me?d.c=d.e=null:d.e<K&&(d.c=[d.e=0])}return d}function Y(d){var m,v=d.e;return v===null?d.toString():(m=f(d.c),m=v<=ue||v>=V?B(m,v):Z(m,v,"0"),d.s<0?"-"+m:m)}return E.absoluteValue=E.abs=function(){var d=new U(this);return d.s<0&&(d.s=1),d},E.comparedTo=function(d,m){return b(this,new U(d,m))},E.decimalPlaces=E.dp=function(d,m){var v,C,x,k=this;if(d!=null)return _(d,0,g),m==null?m=W:_(m,0,8),ae(new U(k),d+k.e+1,m);if(!(v=k.c))return null;if(C=((x=v.length-1)-S(this.e/l))*l,x=v[x])for(;x%10==0;x/=10,C--);return C<0&&(C=0),C},E.dividedBy=E.div=function(d,m){return R(this,new U(d,m),X,W)},E.dividedToIntegerBy=E.idiv=function(d,m){return R(this,new U(d,m),0,1)},E.exponentiatedBy=E.pow=function(d,m){var v,C,x,k,D,T,A,P,I,F=this;if(d=new U(d),d.c&&!d.isInteger())throw Error(a+"Exponent not an integer: "+Y(d));if(m!=null&&(m=new U(m)),T=d.e>14,!F.c||!F.c[0]||F.c[0]==1&&!F.e&&F.c.length==1||!d.c||!d.c[0])return I=new U(Math.pow(+Y(F),T?d.s*(2-M(d)):+Y(d))),m?I.mod(m):I;if(A=d.s<0,m){if(m.c?!m.c[0]:!m.s)return new U(NaN);C=!A&&F.isInteger()&&m.isInteger(),C&&(F=F.mod(m))}else{if(d.e>9&&(F.e>0||F.e<-1||(F.e==0?F.c[0]>1||T&&F.c[1]>=24e7:F.c[0]<8e13||T&&F.c[0]<=9999975e7)))return k=F.s<0&&M(d)?-0:0,F.e>-1&&(k=1/k),new U(A?1/k:k);Se&&(k=n(Se/l+2))}for(T?(v=new U(.5),A&&(d.s=1),P=M(d)):(x=Math.abs(+Y(d)),P=x%2),I=new U(Q);;){if(P){if(I=I.times(F),!I.c)break;k?I.c.length>k&&(I.c.length=k):C&&(I=I.mod(m))}if(x){if(x=o(x/2),x===0)break;P=x%2}else if(d=d.times(v),ae(d,d.e+1,1),d.e>14)P=M(d);else{if(x=+Y(d),x===0)break;P=x%2}F=F.times(F),k?F.c&&F.c.length>k&&(F.c.length=k):C&&(F=F.mod(m))}return C?I:(A&&(I=Q.div(I)),m?I.mod(m):k?ae(I,Se,W,D):I)},E.integerValue=function(d){var m=new U(this);return d==null?d=W:_(d,0,8),ae(m,m.e+1,d)},E.isEqualTo=E.eq=function(d,m){return b(this,new U(d,m))===0},E.isFinite=function(){return!!this.c},E.isGreaterThan=E.gt=function(d,m){return b(this,new U(d,m))>0},E.isGreaterThanOrEqualTo=E.gte=function(d,m){return(m=b(this,new U(d,m)))===1||m===0},E.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},E.isLessThan=E.lt=function(d,m){return b(this,new U(d,m))<0},E.isLessThanOrEqualTo=E.lte=function(d,m){return(m=b(this,new U(d,m)))===-1||m===0},E.isNaN=function(){return!this.s},E.isNegative=function(){return this.s<0},E.isPositive=function(){return this.s>0},E.isZero=function(){return!!this.c&&this.c[0]==0},E.minus=function(d,m){var v,C,x,k,D=this,T=D.s;if(d=new U(d,m),m=d.s,!T||!m)return new U(NaN);if(T!=m)return d.s=-m,D.plus(d);var A=D.e/l,P=d.e/l,I=D.c,F=d.c;if(!A||!P){if(!I||!F)return I?(d.s=-m,d):new U(F?D:NaN);if(!I[0]||!F[0])return F[0]?(d.s=-m,d):new U(I[0]?D:W==3?-0:0)}if(A=S(A),P=S(P),I=I.slice(),T=A-P){for((k=T<0)?(T=-T,x=I):(P=A,x=F),x.reverse(),m=T;m--;x.push(0));x.reverse()}else for(C=(k=(T=I.length)<(m=F.length))?T:m,T=m=0;m<C;m++)if(I[m]!=F[m]){k=I[m]<F[m];break}if(k&&(x=I,I=F,F=x,d.s=-d.s),m=(C=F.length)-(v=I.length),m>0)for(;m--;I[v++]=0);for(m=s-1;C>T;){if(I[--C]<F[C]){for(v=C;v&&!I[--v];I[v]=m);--I[v],I[C]+=s}I[C]-=F[C]}for(;I[0]==0;I.splice(0,1),--P);return I[0]?de(d,I,P):(d.s=W==3?-1:1,d.c=[d.e=0],d)},E.modulo=E.mod=function(d,m){var v,C,x=this;return d=new U(d,m),!x.c||!d.s||d.c&&!d.c[0]?new U(NaN):!d.c||x.c&&!x.c[0]?new U(x):(ve==9?(C=d.s,d.s=1,v=R(x,d,0,3),d.s=C,v.s*=C):v=R(x,d,0,ve),d=x.minus(v.times(d)),!d.c[0]&&ve==1&&(d.s=x.s),d)},E.multipliedBy=E.times=function(d,m){var v,C,x,k,D,T,A,P,I,F,se,ie,Ce,ge,Be,Ie=this,ye=Ie.c,Oe=(d=new U(d,m)).c;if(!ye||!Oe||!ye[0]||!Oe[0])return!Ie.s||!d.s||ye&&!ye[0]&&!Oe||Oe&&!Oe[0]&&!ye?d.c=d.e=d.s=null:(d.s*=Ie.s,!ye||!Oe?d.c=d.e=null:(d.c=[0],d.e=0)),d;for(C=S(Ie.e/l)+S(d.e/l),d.s*=Ie.s,A=ye.length,F=Oe.length,A<F&&(Ce=ye,ye=Oe,Oe=Ce,x=A,A=F,F=x),x=A+F,Ce=[];x--;Ce.push(0));for(ge=s,Be=h,x=F;--x>=0;){for(v=0,se=Oe[x]%Be,ie=Oe[x]/Be|0,D=A,k=x+D;k>x;)P=ye[--D]%Be,I=ye[D]/Be|0,T=ie*P+I*se,P=se*P+T%Be*Be+Ce[k]+v,v=(P/ge|0)+(T/Be|0)+ie*I,Ce[k--]=P%ge;Ce[k]=v}return v?++C:Ce.splice(0,1),de(d,Ce,C)},E.negated=function(){var d=new U(this);return d.s=-d.s||null,d},E.plus=function(d,m){var v,C=this,x=C.s;if(d=new U(d,m),m=d.s,!x||!m)return new U(NaN);if(x!=m)return d.s=-m,C.minus(d);var k=C.e/l,D=d.e/l,T=C.c,A=d.c;if(!k||!D){if(!T||!A)return new U(x/0);if(!T[0]||!A[0])return A[0]?d:new U(T[0]?C:x*0)}if(k=S(k),D=S(D),T=T.slice(),x=k-D){for(x>0?(D=k,v=A):(x=-x,v=T),v.reverse();x--;v.push(0));v.reverse()}for(x=T.length,m=A.length,x-m<0&&(v=A,A=T,T=v,m=x),x=0;m;)x=(T[--m]=T[m]+A[m]+x)/s|0,T[m]=s===T[m]?0:T[m]%s;return x&&(T=[x].concat(T),++D),de(d,T,D)},E.precision=E.sd=function(d,m){var v,C,x,k=this;if(d!=null&&d!==!!d)return _(d,1,g),m==null?m=W:_(m,0,8),ae(new U(k),d,m);if(!(v=k.c))return null;if(x=v.length-1,C=x*l+1,x=v[x]){for(;x%10==0;x/=10,C--);for(x=v[0];x>=10;x/=10,C++);}return d&&k.e+1>C&&(C=k.e+1),C},E.shiftedBy=function(d){return _(d,-c,c),this.times("1e"+d)},E.squareRoot=E.sqrt=function(){var d,m,v,C,x,k=this,D=k.c,T=k.s,A=k.e,P=X+4,I=new U("0.5");if(T!==1||!D||!D[0])return new U(!T||T<0&&(!D||D[0])?NaN:D?k:1/0);if(T=Math.sqrt(+Y(k)),T==0||T==1/0?(m=f(D),(m.length+A)%2==0&&(m+="0"),T=Math.sqrt(+m),A=S((A+1)/2)-(A<0||A%2),T==1/0?m="5e"+A:(m=T.toExponential(),m=m.slice(0,m.indexOf("e")+1)+A),v=new U(m)):v=new U(T+""),v.c[0]){for(A=v.e,T=A+P,T<3&&(T=0);;)if(x=v,v=I.times(x.plus(R(k,x,P,1))),f(x.c).slice(0,T)===(m=f(v.c)).slice(0,T))if(v.e<A&&--T,m=m.slice(T-3,T+1),m=="9999"||!C&&m=="4999"){if(!C&&(ae(x,x.e+X+2,0),x.times(x).eq(k))){v=x;break}P+=4,T+=4,C=1}else{(!+m||!+m.slice(1)&&m.charAt(0)=="5")&&(ae(v,v.e+X+2,1),d=!v.times(v).eq(k));break}}return ae(v,v.e+X+1,W,d)},E.toExponential=function(d,m){return d!=null&&(_(d,0,g),d++),be(this,d,m,1)},E.toFixed=function(d,m){return d!=null&&(_(d,0,g),d=d+this.e+1),be(this,d,m)},E.toFormat=function(d,m,v){var C,x=this;if(v==null)d!=null&&m&&typeof m=="object"?(v=m,m=null):d&&typeof d=="object"?(v=d,d=m=null):v=fe;else if(typeof v!="object")throw Error(a+"Argument not an object: "+v);if(C=x.toFixed(d,m),x.c){var k,D=C.split("."),T=+v.groupSize,A=+v.secondaryGroupSize,P=v.groupSeparator||"",I=D[0],F=D[1],se=x.s<0,ie=se?I.slice(1):I,Ce=ie.length;if(A&&(k=T,T=A,A=k,Ce-=k),T>0&&Ce>0){for(k=Ce%T||T,I=ie.substr(0,k);k<Ce;k+=T)I+=P+ie.substr(k,T);A>0&&(I+=P+ie.slice(k)),se&&(I="-"+I)}C=F?I+(v.decimalSeparator||"")+((A=+v.fractionGroupSize)?F.replace(new RegExp("\\d{"+A+"}\\B","g"),"$&"+(v.fractionGroupSeparator||"")):F):I}return(v.prefix||"")+C+(v.suffix||"")},E.toFraction=function(d){var m,v,C,x,k,D,T,A,P,I,F,se,ie=this,Ce=ie.c;if(d!=null&&(T=new U(d),!T.isInteger()&&(T.c||T.s!==1)||T.lt(Q)))throw Error(a+"Argument "+(T.isInteger()?"out of range: ":"not an integer: ")+Y(T));if(!Ce)return new U(ie);for(m=new U(Q),P=v=new U(Q),C=A=new U(Q),se=f(Ce),k=m.e=se.length-ie.e-1,m.c[0]=p[(D=k%l)<0?l+D:D],d=!d||T.comparedTo(m)>0?k>0?m:P:T,D=me,me=1/0,T=new U(se),A.c[0]=0;I=R(T,m,0,1),x=v.plus(I.times(C)),x.comparedTo(d)!=1;)v=C,C=x,P=A.plus(I.times(x=P)),A=x,m=T.minus(I.times(x=m)),T=x;return x=R(d.minus(v),C,0,1),A=A.plus(x.times(P)),v=v.plus(x.times(C)),A.s=P.s=ie.s,k=k*2,F=R(P,C,k,W).minus(ie).abs().comparedTo(R(A,v,k,W).minus(ie).abs())<1?[P,C]:[A,v],me=D,F},E.toNumber=function(){return+Y(this)},E.toPrecision=function(d,m){return d!=null&&_(d,1,g),be(this,d,m,2)},E.toString=function(d){var m,v=this,C=v.s,x=v.e;return x===null?C?(m="Infinity",C<0&&(m="-"+m)):m="NaN":(d==null?m=x<=ue||x>=V?B(f(v.c),x):Z(f(v.c),x,"0"):d===10&&z?(v=ae(new U(v),X+x+1,W),m=Z(f(v.c),v.e,"0")):(_(d,2,Fe.length,"Base"),m=O(Z(f(v.c),x,"0"),10,d,C,!0)),C<0&&v.c[0]&&(m="-"+m)),m},E.valueOf=E.toJSON=function(){return Y(this)},E._isBigNumber=!0,N!=null&&U.set(N),U}function S(N){var R=N|0;return N>0||N===R?R:R-1}function f(N){for(var R,O,ee=1,E=N.length,Q=N[0]+"";ee<E;){for(R=N[ee++]+"",O=l-R.length;O--;R="0"+R);Q+=R}for(E=Q.length;Q.charCodeAt(--E)===48;);return Q.slice(0,E+1||1)}function b(N,R){var O,ee,E=N.c,Q=R.c,X=N.s,W=R.s,ue=N.e,V=R.e;if(!X||!W)return null;if(O=E&&!E[0],ee=Q&&!Q[0],O||ee)return O?ee?0:-W:X;if(X!=W)return X;if(O=X<0,ee=ue==V,!E||!Q)return ee?0:!E^O?1:-1;if(!ee)return ue>V^O?1:-1;for(W=(ue=E.length)<(V=Q.length)?ue:V,X=0;X<W;X++)if(E[X]!=Q[X])return E[X]>Q[X]^O?1:-1;return ue==V?0:ue>V^O?1:-1}function _(N,R,O,ee){if(N<R||N>O||N!==o(N))throw Error(a+(ee||"Argument")+(typeof N=="number"?N<R||N>O?" out of range: ":" not an integer: ":" not a primitive number: ")+String(N))}function M(N){var R=N.c.length-1;return S(N.e/l)==R&&N.c[R]%2!=0}function B(N,R){return(N.length>1?N.charAt(0)+"."+N.slice(1):N)+(R<0?"e":"e+")+R}function Z(N,R,O){var ee,E;if(R<0){for(E=O+".";++R;E+=O);N=E+N}else if(ee=N.length,++R>ee){for(E=O,R-=ee;--R;E+=O);N+=E}else R<ee&&(N=N.slice(0,R)+"."+N.slice(R));return N}e=y(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Ao<"u"&&Ao.exports?Ao.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Qu)});var nd=te((YA,rd)=>{"use strict";var ed=hi(),td=rd.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,a={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function s(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(p){var h=a[p];return typeof h=="string"?h:"\\u"+("0000"+p.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function l(c,p){var h,g,y,S,f=n,b,_=p[c],M=_!=null&&(_ instanceof ed||ed.isBigNumber(_));switch(_&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(c)),typeof i=="function"&&(_=i.call(p,c,_)),typeof _){case"string":return M?_:s(_);case"number":return isFinite(_)?String(_):"null";case"boolean":case"null":case"bigint":return String(_);case"object":if(!_)return"null";if(n+=o,b=[],Object.prototype.toString.apply(_)==="[object Array]"){for(S=_.length,h=0;h<S;h+=1)b[h]=l(h,_)||"null";return y=b.length===0?"[]":n?`[
|
|
9
9
|
`+n+b.join(`,
|
|
10
10
|
`+n)+`
|
|
11
|
-
`+
|
|
11
|
+
`+f+"]":"["+b.join(",")+"]",n=f,y}if(i&&typeof i=="object")for(S=i.length,h=0;h<S;h+=1)typeof i[h]=="string"&&(g=i[h],y=l(g,_),y&&b.push(s(g)+(n?": ":":")+y));else Object.keys(_).forEach(function(B){var Z=l(B,_);Z&&b.push(s(B)+(n?": ":":")+Z)});return y=b.length===0?"{}":n?`{
|
|
12
12
|
`+n+b.join(`,
|
|
13
13
|
`+n)+`
|
|
14
|
-
`+
|
|
15
|
-
`,r:"\r",t:" "},a,i=function(y){throw{name:"SyntaxError",message:y,at:r,text:a}},s=function(y){return y&&y!==n&&i("Expected '"+y+"' instead of '"+n+"'"),n=a.charAt(r),r+=1,n},l=function(){var y,b="";for(n==="-"&&(b="-",s("-"));n>="0"&&n<="9";)b+=n,s();if(n===".")for(b+=".";s()&&n>="0"&&n<="9";)b+=n;if(n==="e"||n==="E")for(b+=n,s(),(n==="-"||n==="+")&&(b+=n,s());n>="0"&&n<="9";)b+=n,s();if(y=+b,!isFinite(y))i("Bad number");else return ko==null&&(ko=hi()),b.length>15?e.storeAsString?b:e.useNativeBigInt?BigInt(b):new ko(b):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new ko(y):y},c=function(){var y,b,_="",D;if(n==='"')for(var V=r;s();){if(n==='"')return r-1>V&&(_+=a.substring(V,r-1)),s(),_;if(n==="\\"){if(r-1>V&&(_+=a.substring(V,r-1)),s(),n==="u"){for(D=0,b=0;b<4&&(y=parseInt(s(),16),!!isFinite(y));b+=1)D=D*16+y;_+=String.fromCharCode(D)}else if(typeof o[n]=="string")_+=o[n];else break;V=r}}i("Bad string")},p=function(){for(;n&&n<=" ";)s()},h=function(){switch(n){case"t":return s("t"),s("r"),s("u"),s("e"),!0;case"f":return s("f"),s("a"),s("l"),s("s"),s("e"),!1;case"n":return s("n"),s("u"),s("l"),s("l"),null}i("Unexpected '"+n+"'")},m,g=function(){var y=[];if(n==="["){if(s("["),p(),n==="]")return s("]"),y;for(;n;){if(y.push(m()),p(),n==="]")return s("]"),y;s(","),p()}}i("Bad array")},T=function(){var y,b=Object.create(null);if(n==="{"){if(s("{"),p(),n==="}")return s("}"),b;for(;n;){if(y=c(),p(),s(":"),e.strict===!0&&Object.hasOwnProperty.call(b,y)&&i('Duplicate key "'+y+'"'),Sb.test(y)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():b[y]=m():Cb.test(y)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():b[y]=m():b[y]=m(),p(),n==="}")return s("}"),b;s(","),p()}}i("Bad object")};return m=function(){switch(p(),n){case"{":return T();case"[":return g();case'"':return c();case"-":return l();default:return n>="0"&&n<="9"?l():h()}},function(y,b){var _;return a=y+"",r=0,n=" ",_=m(),p(),n&&i("Syntax error"),typeof b=="function"?function D(V,X){var P,N,R=V[X];return R&&typeof R=="object"&&Object.keys(R).forEach(function(Q){N=D(R,Q),N!==void 0?R[Q]=N:delete R[Q]}),b.call(V,X,R)}({"":_},""):_}};od.exports=Ib});var ld=ee((ZA,Ro)=>{"use strict";var id=nd().stringify,sd=ad();Ro.exports=function(t){return{parse:sd(t),stringify:id}};Ro.exports.parse=sd();Ro.exports.stringify=id});var fi=ee(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GCE_LINUX_BIOS_PATHS=void 0;Ht.isGoogleCloudServerless=dd;Ht.isGoogleComputeEngineLinux=pd;Ht.isGoogleComputeEngineMACAddress=hd;Ht.isGoogleComputeEngine=fd;Ht.detectGCPResidency=kb;var cd=be("fs"),ud=be("os");Ht.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Ab=/^42:01/;function dd(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function pd(){if((0,ud.platform)()!=="linux")return!1;try{(0,cd.statSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,cd.readFileSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function hd(){let t=(0,ud.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(Ab.test(r))return!0}return!1}function fd(){return pd()||hd()}function kb(){return dd()||fd()}});var md=ee(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.Colours=void 0;var ot=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Oo.Colours=ot;ot.enabled=!1;ot.reset="";ot.bright="";ot.dim="";ot.red="";ot.green="";ot.yellow="";ot.blue="";ot.magenta="";ot.cyan="";ot.white="";ot.grey="";ot.refresh()});var bd=ee(De=>{"use strict";var Rb=De&&De.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ob=De&&De.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gd=De&&De.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Rb(r,e,n[o]);return Ob(r,e),r}}();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=gi;De.getDebugBackend=Mb;De.getStructuredBackend=Pb;De.setBackend=Db;De.log=vd;var Nb=be("events"),Dn=gd(be("process")),yd=gd(be("util")),gt=md(),qt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(qt||(De.LogSeverity=qt={}));var jn=class extends Nb.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>vd(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};De.AdhocDebugLogger=jn;De.placeholder=new jn("",()=>{}).func;var Zr=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Dn.env[De.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(r,...n)}catch(o){console.error(o)}}};De.DebugLogBackendBase=Zr;var mi=class extends Zr{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let a=`${gt.Colours.green}${e}${gt.Colours.reset}`,i=`${gt.Colours.yellow}${Dn.pid}${gt.Colours.reset}`,s;switch(r.severity){case qt.ERROR:s=`${gt.Colours.red}${r.severity}${gt.Colours.reset}`;break;case qt.INFO:s=`${gt.Colours.magenta}${r.severity}${gt.Colours.reset}`;break;case qt.WARNING:s=`${gt.Colours.yellow}${r.severity}${gt.Colours.reset}`;break;default:s=(o=r.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let l=yd.formatWithOptions({colors:gt.Colours.enabled},...n),c=Object.assign({},r);delete c.severity;let p=Object.getOwnPropertyNames(c).length?JSON.stringify(c):"",h=p?`${gt.Colours.grey}${p}${gt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",i,a,s,l,p?` ${h}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function gi(){return new mi}var yi=class extends Zr{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=Dn.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Dn.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Mb(t){return new yi(t)}var vi=class extends Zr{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(o,...a)=>{var i;let s=(i=o.severity)!==null&&i!==void 0?i:qt.INFO,l=Object.assign({severity:s,message:yd.format(...a)},o),c=JSON.stringify(l);n?n(o,c):console.log("%s",c)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Pb(t){return new vi(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var bi=new Map,yt;function Db(t){yt=t,bi.clear()}function vd(t,e){if(!yt&&!Dn.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=bi.get(t);if(r)return r.func;if(yt===null)return De.placeholder;yt===void 0&&(yt=gi());let n=(()=>{let o;return new jn(t,(i,...s)=>{if(o!==yt){if(yt===null)return;yt===void 0&&(yt=gi()),o=yt}yt?.log(t,i,...s)})})();return bi.set(t,n),n.func}});var _i=ee(qr=>{"use strict";var jb=qr&&qr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Lb=qr&&qr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&jb(e,t,r)};Object.defineProperty(qr,"__esModule",{value:!0});Lb(bd(),qr)});var Un=ee(de=>{"use strict";var wd=de&&de.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ub=de&&de.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fb=de&&de.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&wd(r,e,n[o]);return Ub(r,e),r}}(),Hb=de&&de.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wd(e,t,r)};Object.defineProperty(de,"__esModule",{value:!0});de.gcpResidencyCache=de.METADATA_SERVER_DETECTION=de.HEADERS=de.HEADER_VALUE=de.HEADER_NAME=de.SECONDARY_HOST_ADDRESS=de.HOST_ADDRESS=de.BASE_PATH=void 0;de.instance=zb;de.project=Wb;de.universe=Jb;de.bulk=Kb;de.isAvailable=Xb;de.resetIsAvailableCache=Zb;de.getGCPResidency=Ti;de.setGCPResidency=Ed;de.requestTimeout=Td;var wi=rt(),qb=ld(),Gb=fi(),$b=Fb(_i());de.BASE_PATH="/computeMetadata/v1";de.HOST_ADDRESS="http://169.254.169.254";de.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";de.HEADER_NAME="Metadata-Flavor";de.HEADER_VALUE="Google";de.HEADERS=Object.freeze({[de.HEADER_NAME]:de.HEADER_VALUE});var _d=$b.log("gcp-metadata");de.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 Ei(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||de.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(de.BASE_PATH,t).href}function Bb(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Ln(t,e={},r=3,n=!1){let o=new Headers(de.HEADERS),a="",i={};if(typeof t=="object"){let h=t;new Headers(h.headers).forEach((m,g)=>o.set(g,m)),a=h.metadataKey,i=h.params||i,r=h.noResponseRetries||r,n=h.fastFail||n}else a=t;typeof e=="string"?a+=`/${e}`:(Bb(e),e.property&&(a+=`/${e.property}`),new Headers(e.headers).forEach((h,m)=>o.set(m,h)),i=e.params||i);let s=n?Vb:wi.request,l={url:`${Ei()}/${a}`,headers:o,retryConfig:{noResponseRetries:r},params:i,responseType:"text",timeout:Td()};_d.info("instance request %j",l);let c=await s(l);_d.info("instance metadata is %s",c.data);let p=c.headers.get(de.HEADER_NAME);if(p!==de.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${de.HEADER_NAME} header. Expected '${de.HEADER_VALUE}', got ${p?`'${p}'`:"no header"}`);if(typeof c.data=="string")try{return qb.parse(c.data)}catch{}return c.data}async function Vb(t){let e={...t,url:t.url?.toString().replace(Ei(),Ei(de.SECONDARY_HOST_ADDRESS))},r=(0,wi.request)(t),n=(0,wi.request)(e);return Promise.any([r,n])}function zb(t){return Ln("instance",t)}function Wb(t){return Ln("project",t)}function Jb(t){return Ln("universe",t)}async function Kb(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Ln(r),o=r.metadataKey;e[o]=n})())),e}function Yb(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var No;async function Xb(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in de.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(de.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Ti();case"ping-only":}}try{return No===void 0&&(No=Ln("instance",void 0,Yb(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await No,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function Zb(){No=void 0}de.gcpResidencyCache=null;function Ti(){return de.gcpResidencyCache===null&&Ed(),de.gcpResidencyCache}function Ed(t=null){de.gcpResidencyCache=t!==null?t:(0,Gb.detectGCPResidency)()}function Td(){return Ti()?0:3e3}Hb(fi(),de)});var Cd=ee(Mo=>{"use strict";Mo.byteLength=e_;Mo.toByteArray=r_;Mo.fromByteArray=a_;var Yt=[],At=[],Qb=typeof Uint8Array<"u"?Uint8Array:Array,xi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Gr=0,xd=xi.length;Gr<xd;++Gr)Yt[Gr]=xi[Gr],At[xi.charCodeAt(Gr)]=Gr;var Gr,xd;At[45]=62;At[95]=63;function Sd(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function e_(t){var e=Sd(t),r=e[0],n=e[1];return(r+n)*3/4-n}function t_(t,e,r){return(e+r)*3/4-r}function r_(t){var e,r=Sd(t),n=r[0],o=r[1],a=new Qb(t_(t,n,o)),i=0,s=o>0?n-4:n,l;for(l=0;l<s;l+=4)e=At[t.charCodeAt(l)]<<18|At[t.charCodeAt(l+1)]<<12|At[t.charCodeAt(l+2)]<<6|At[t.charCodeAt(l+3)],a[i++]=e>>16&255,a[i++]=e>>8&255,a[i++]=e&255;return o===2&&(e=At[t.charCodeAt(l)]<<2|At[t.charCodeAt(l+1)]>>4,a[i++]=e&255),o===1&&(e=At[t.charCodeAt(l)]<<10|At[t.charCodeAt(l+1)]<<4|At[t.charCodeAt(l+2)]>>2,a[i++]=e>>8&255,a[i++]=e&255),a}function n_(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function o_(t,e,r){for(var n,o=[],a=e;a<r;a+=3)n=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),o.push(n_(n));return o.join("")}function a_(t){for(var e,r=t.length,n=r%3,o=[],a=16383,i=0,s=r-n;i<s;i+=a)o.push(o_(t,i,i+a>s?s:i+a));return n===1?(e=t[r-1],o.push(Yt[e>>2]+Yt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(Yt[e>>10]+Yt[e>>4&63]+Yt[e<<2&63]+"=")),o.join("")}});var Ci=ee(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.fromArrayBufferToHex=i_;function i_(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var Id=ee(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.BrowserCrypto=void 0;var Qr=Cd(),s_=Ci(),Ii=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return Qr.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Qr.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},a=new TextEncoder().encode(r),i=Qr.toByteArray(t.padBase64(n)),s=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,s,i,a)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),a=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),i=await window.crypto.subtle.sign(n,a,o);return Qr.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let r=Qr.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Qr.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,s_.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,a=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",a,o.encode(r))}};Po.BrowserCrypto=Ii});var Ad=ee(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.NodeCrypto=void 0;var en=be("crypto"),Ai=class{async sha256DigestBase64(e){return en.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return en.randomBytes(e).toString("base64")}async verify(e,r,n){let o=en.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=en.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return en.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:c_(e);return l_(en.createHmac("sha256",n).update(r).digest())}};Do.NodeCrypto=Ai;function l_(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function c_(t){return Buffer.from(t)}});var Fn=ee(gr=>{"use strict";var u_=gr&&gr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),d_=gr&&gr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&u_(e,t,r)};Object.defineProperty(gr,"__esModule",{value:!0});gr.createCrypto=f_;gr.hasBrowserCrypto=kd;var p_=Id(),h_=Ad();d_(Ci(),gr);function f_(){return kd()?new p_.BrowserCrypto:new h_.NodeCrypto}function kd(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var tn=ee((ki,Od)=>{"use strict";var jo=be("buffer"),Xt=jo.Buffer;function Rd(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?Od.exports=jo:(Rd(jo,ki),ki.Buffer=$r);function $r(t,e,r){return Xt(t,e,r)}$r.prototype=Object.create(Xt.prototype);Rd(Xt,$r);$r.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};$r.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};$r.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};$r.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return jo.SlowBuffer(t)}});var Md=ee((ck,Nd)=>{"use strict";function Ri(t){var e=(t/8|0)+(t%8===0?0:1);return e}var m_={ES256:Ri(256),ES384:Ri(384),ES512:Ri(521)};function g_(t){var e=m_[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Nd.exports=g_});var Oi=ee((uk,Fd)=>{"use strict";var Lo=tn().Buffer,Dd=Md(),Uo=128,jd=0,y_=32,v_=16,b_=2,Ld=v_|y_|jd<<6,Fo=b_|jd<<6;function __(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ud(t){if(Lo.isBuffer(t))return t;if(typeof t=="string")return Lo.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function w_(t,e){t=Ud(t);var r=Dd(e),n=r+1,o=t.length,a=0;if(t[a++]!==Ld)throw new Error('Could not find expected "seq"');var i=t[a++];if(i===(Uo|1)&&(i=t[a++]),o-a<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-a)+'" remaining');if(t[a++]!==Fo)throw new Error('Could not find expected "int" for "r"');var s=t[a++];if(o-a-2<s)throw new Error('"r" specified length of "'+s+'", only "'+(o-a-2)+'" available');if(n<s)throw new Error('"r" specified length of "'+s+'", max of "'+n+'" is acceptable');var l=a;if(a+=s,t[a++]!==Fo)throw new Error('Could not find expected "int" for "s"');var c=t[a++];if(o-a!==c)throw new Error('"s" specified length of "'+c+'", expected "'+(o-a)+'"');if(n<c)throw new Error('"s" specified length of "'+c+'", max of "'+n+'" is acceptable');var p=a;if(a+=c,a!==o)throw new Error('Expected to consume entire buffer, but "'+(o-a)+'" bytes remain');var h=r-s,m=r-c,g=Lo.allocUnsafe(h+s+m+c);for(a=0;a<h;++a)g[a]=0;t.copy(g,a,l+Math.max(-h,0),l+s),a=r;for(var T=a;a<T+m;++a)g[a]=0;return t.copy(g,a,p+Math.max(-m,0),p+c),g=g.toString("base64"),g=__(g),g}function Pd(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=Uo;return o&&--n,n}function E_(t,e){t=Ud(t);var r=Dd(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=Pd(t,0,r),a=Pd(t,r,t.length),i=r-o,s=r-a,l=2+i+1+1+s,c=l<Uo,p=Lo.allocUnsafe((c?2:3)+l),h=0;return p[h++]=Ld,c?p[h++]=l:(p[h++]=Uo|1,p[h++]=l&255),p[h++]=Fo,p[h++]=i,o<0?(p[h++]=0,h+=t.copy(p,h,0,r)):h+=t.copy(p,h,o,r),p[h++]=Fo,p[h++]=s,a<0?(p[h++]=0,t.copy(p,h,r)):t.copy(p,h,r+a),p}Fd.exports={derToJose:w_,joseToDer:E_}});var Gt=ee(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.LRUCache=void 0;yr.snakeToCamel=qd;yr.originalOrCamelOptions=C_;yr.removeUndefinedValuesInObject=I_;yr.isValidFile=A_;yr.getWellKnownCertificateConfigFileLocation=k_;var T_=be("fs"),x_=be("os"),Ni=be("path"),S_="certificate_config.json",Hd="gcloud";function qd(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function C_(t){function e(r){let n=t||{};return n[r]??n[qd(r)]}return{get:e}}var Mi=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};yr.LRUCache=Mi;function I_(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function A_(t){try{return(await T_.promises.lstat(t)).isFile()}catch{return!1}}function k_(){let t=process.env.CLOUDSDK_CONFIG||(R_()?Ni.join(process.env.APPDATA||"",Hd):Ni.join(process.env.HOME||"",".config",Hd));return Ni.join(t,S_)}function R_(){return x_.platform().startsWith("win")}});var Gd=ee((pk,O_)=>{O_.exports={name:"google-auth-library",version:"10.5.0",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:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^8.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",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.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-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.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},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"}});var Pi=ee(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.USER_AGENT=Cr.PRODUCT_NAME=Cr.pkg=void 0;var $d=Gd();Cr.pkg=$d;var Bd="google-api-nodejs-client";Cr.PRODUCT_NAME=Bd;var N_=`${Bd}/${$d.version}`;Cr.USER_AGENT=N_});var vt=ee($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.AuthClient=$t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=$t.DEFAULT_UNIVERSE=void 0;var M_=be("events"),Di=rt(),P_=Gt(),D_=_i(),ji=Pi();$t.DEFAULT_UNIVERSE="googleapis.com";$t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Li=class t extends M_.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=$t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=$t.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,P_.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??$t.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Di.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],o,a=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Di.Gaxios.mergeHeaders(a,r.headers),n&&Di.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:a,url:o}):this.request({...n,headers:a,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,D_.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${ji.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${ji.USER_AGENT}`):e.headers.set("User-Agent",ji.USER_AGENT);try{let n=e,o=n[t.RequestMethodNameSymbol],a=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=a;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,a,i):t.log.info("[%s] request %j",a,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};$t.AuthClient=Li});var Fi=ee(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.LoginTicket=void 0;var Ui=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Ho.LoginTicket=Ui});var Br=ee(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.OAuth2Client=Zt.ClientAuthentication=Zt.CertificateFormat=Zt.CodeChallengeMethod=void 0;var Vd=rt(),j_=be("querystring"),L_=be("stream"),U_=Oi(),zd=Gt(),Hi=Fn(),rn=vt(),F_=Fi(),Wd;(function(t){t.Plain="plain",t.S256="S256"})(Wd||(Zt.CodeChallengeMethod=Wd={}));var vr;(function(t){t.PEM="PEM",t.JWK="JWK"})(vr||(Zt.CertificateFormat=vr={}));var Hn;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Hn||(Zt.ClientAuthentication=Hn={}));var qi=class t extends rn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=vr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Hn.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+j_.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Hi.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),a=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:a}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Hn.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Hn.ClientSecretPost&&(o.client_secret=this._clientSecret);let a={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,zd.removeUndefinedValuesInObject)(o)),headers:n};rn.AuthClient.setMethodName(a,"getTokenAsync");let i=await this.transporter.request(a),s=i.data;return i.data&&i.data.expires_in&&(s.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:i}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,zd.removeUndefinedValuesInObject)(n))};rn.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof Vd.GaxiosError&&i.message==="invalid_grant"&&i.response?.data&&/ReAuth/i.test(i.response.data.error_description)&&(i.message=JSON.stringify(i.response.data)),i}let a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{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(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let s=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(s)}}if(this.refreshHandler){let s=await this.processAndValidateRefreshHandler();if(s?.access_token){this.setCredentials(s);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(r.refresh_token),o=n.tokens}catch(s){let l=s;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let a=this.credentials;a.token_type=a.token_type||"Bearer",o.refresh_token=a.refresh_token,this.credentials=o;let i=new Headers({authorization:a.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(i),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(rn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Vd.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.response;if(o){let a=o.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),s=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof L_.Readable,c=a===401||a===403;if(!r&&c&&!l&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&c&&!l&&s){let p=await this.processAndValidateRefreshHandler();return p?.access_token&&this.setCredentials(p),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,Hi.hasBrowserCrypto)()?vr.JWK:vr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case vr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case vr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let c={...t.RETRY_CONFIG,url:o};rn.AuthClient.setMethodName(c,"getFederatedSignonCertsAsync"),n=await this.transporter.request(c)}catch(c){throw c instanceof Error&&(c.message=`Failed to retrieve verification certificates: ${c.message}`),c}let a=n?.headers.get("cache-control"),i=-1;if(a){let c=/max-age=(?<maxAge>[0-9]+)/.exec(a)?.groups?.maxAge;c&&(i=Number(c)*1e3)}let s={};switch(r){case vr.PEM:s=n.data;break;case vr.JWK:for(let c of n.data.keys)s[c.kid]=c;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=i===-1?null:new Date(l.getTime()+i),this.certificateCache=s,this.certificateCacheFormat=r,{certs:s,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};rn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,o,a){let i=(0,Hi.createCrypto)();a||(a=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let s=e.split(".");if(s.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=s[0]+"."+s[1],c=s[2],p,h;try{p=JSON.parse(i.decodeBase64StringUtf8(s[0]))}catch(V){throw V instanceof Error&&(V.message=`Can't parse token envelope: ${s[0]}': ${V.message}`),V}if(!p)throw new Error("Can't parse token envelope: "+s[0]);try{h=JSON.parse(i.decodeBase64StringUtf8(s[1]))}catch(V){throw V instanceof Error&&(V.message=`Can't parse token payload '${s[0]}`),V}if(!h)throw new Error("Can't parse token payload: "+s[1]);if(!Object.prototype.hasOwnProperty.call(r,p.kid))throw new Error("No pem found for envelope: "+JSON.stringify(p));let m=r[p.kid];if(p.alg==="ES256"&&(c=U_.joseToDer(c,"ES256").toString("base64")),!await i.verify(m,l,c))throw new Error("Invalid token signature: "+e);if(!h.iat)throw new Error("No issue time in token: "+JSON.stringify(h));if(!h.exp)throw new Error("No expiration time in token: "+JSON.stringify(h));let T=Number(h.iat);if(isNaN(T))throw new Error("iat field using invalid format");let y=Number(h.exp);if(isNaN(y))throw new Error("exp field using invalid format");let b=new Date().getTime()/1e3;if(y>=b+a)throw new Error("Expiration time too far in future: "+JSON.stringify(h));let _=T-t.CLOCK_SKEW_SECS_,D=y+t.CLOCK_SKEW_SECS_;if(b<_)throw new Error("Token used too early, "+b+" < "+_+": "+JSON.stringify(h));if(b>D)throw new Error("Token used too late, "+b+" > "+D+": "+JSON.stringify(h));if(o&&o.indexOf(h.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+h.iss);if(typeof n<"u"&&n!==null){let V=h.aud,X=!1;if(n.constructor===Array?X=n.indexOf(V)>-1:X=V===n,!X)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new F_.LoginTicket(p,h)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Zt.OAuth2Client=qi});var $i=ee(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.Compute=void 0;var H_=rt(),Jd=Un(),q_=Br(),Gi=class extends q_.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await Jd.instance(o)}catch(o){throw o instanceof H_.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:r};n=await Jd.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.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:r.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))}};qo.Compute=Gi});var Vi=ee(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.IdTokenClient=void 0;var G_=Br(),Bi=class extends G_.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Go.IdTokenClient=Bi});var zi=ee(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.GCPEnv=void 0;nn.clear=$_;nn.getEnv=B_;var Kd=Un(),Qt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Qt||(nn.GCPEnv=Qt={}));var qn;function $_(){qn=void 0}async function B_(){return qn||(qn=V_(),qn)}async function V_(){let t=Qt.NONE;return z_()?t=Qt.APP_ENGINE:W_()?t=Qt.CLOUD_FUNCTIONS:await X_()?await Y_()?t=Qt.KUBERNETES_ENGINE:J_()?t=Qt.CLOUD_RUN:K_()?t=Qt.CLOUD_RUN_JOBS:t=Qt.COMPUTE_ENGINE:t=Qt.NONE,t}function z_(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function W_(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function J_(){return!!process.env.K_CONFIGURATION}function K_(){return!!process.env.CLOUD_RUN_JOB}async function Y_(){try{return await Kd.instance("attributes/cluster-name"),!0}catch{return!1}}async function X_(){return Kd.isAvailable()}});var Wi=ee((_k,Yd)=>{"use strict";var $o=tn().Buffer,Z_=be("stream"),Q_=be("util");function Bo(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=$o.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=$o.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}Q_.inherits(Bo,Z_);Bo.prototype.write=function(e){this.buffer=$o.concat([this.buffer,$o.from(e)]),this.emit("data",e)};Bo.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Yd.exports=Bo});var Zd=ee((wk,Xd)=>{"use strict";var Gn=be("buffer").Buffer,Ji=be("buffer").SlowBuffer;Xd.exports=Vo;function Vo(t,e){if(!Gn.isBuffer(t)||!Gn.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}Vo.install=function(){Gn.prototype.equal=Ji.prototype.equal=function(e){return Vo(this,e)}};var ew=Gn.prototype.equal,tw=Ji.prototype.equal;Vo.restore=function(){Gn.prototype.equal=ew,Ji.prototype.equal=tw}});var Zi=ee((Ek,sp)=>{"use strict";var an=tn().Buffer,kt=be("crypto"),ep=Oi(),Qd=be("util"),rw=`"%s" is not a valid algorithm.
|
|
14
|
+
`+f+"}":"{"+b.join(",")+"}",n=f,y}}typeof td.stringify!="function"&&(td.stringify=function(c,p,h){var g;if(n="",o="",typeof h=="number")for(g=0;g<h;g+=1)o+=" ";else typeof h=="string"&&(o=h);if(i=p,p&&typeof p!="function"&&(typeof p!="object"||typeof p.length!="number"))throw new Error("JSON.stringify");return l("",{"":c})})})()});var ad=te((XA,od)=>{"use strict";var ko=null,Sb=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Cb=/(?: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)/,Ib=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
15
|
+
`,r:"\r",t:" "},a,i=function(f){throw{name:"SyntaxError",message:f,at:r,text:a}},s=function(f){return f&&f!==n&&i("Expected '"+f+"' instead of '"+n+"'"),n=a.charAt(r),r+=1,n},l=function(){var f,b="";for(n==="-"&&(b="-",s("-"));n>="0"&&n<="9";)b+=n,s();if(n===".")for(b+=".";s()&&n>="0"&&n<="9";)b+=n;if(n==="e"||n==="E")for(b+=n,s(),(n==="-"||n==="+")&&(b+=n,s());n>="0"&&n<="9";)b+=n,s();if(f=+b,!isFinite(f))i("Bad number");else return ko==null&&(ko=hi()),b.length>15?e.storeAsString?b:e.useNativeBigInt?BigInt(b):new ko(b):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(f):new ko(f):f},c=function(){var f,b,_="",M;if(n==='"')for(var B=r;s();){if(n==='"')return r-1>B&&(_+=a.substring(B,r-1)),s(),_;if(n==="\\"){if(r-1>B&&(_+=a.substring(B,r-1)),s(),n==="u"){for(M=0,b=0;b<4&&(f=parseInt(s(),16),!!isFinite(f));b+=1)M=M*16+f;_+=String.fromCharCode(M)}else if(typeof o[n]=="string")_+=o[n];else break;B=r}}i("Bad string")},p=function(){for(;n&&n<=" ";)s()},h=function(){switch(n){case"t":return s("t"),s("r"),s("u"),s("e"),!0;case"f":return s("f"),s("a"),s("l"),s("s"),s("e"),!1;case"n":return s("n"),s("u"),s("l"),s("l"),null}i("Unexpected '"+n+"'")},g,y=function(){var f=[];if(n==="["){if(s("["),p(),n==="]")return s("]"),f;for(;n;){if(f.push(g()),p(),n==="]")return s("]"),f;s(","),p()}}i("Bad array")},S=function(){var f,b=Object.create(null);if(n==="{"){if(s("{"),p(),n==="}")return s("}"),b;for(;n;){if(f=c(),p(),s(":"),e.strict===!0&&Object.hasOwnProperty.call(b,f)&&i('Duplicate key "'+f+'"'),Sb.test(f)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?g():b[f]=g():Cb.test(f)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?g():b[f]=g():b[f]=g(),p(),n==="}")return s("}"),b;s(","),p()}}i("Bad object")};return g=function(){switch(p(),n){case"{":return S();case"[":return y();case'"':return c();case"-":return l();default:return n>="0"&&n<="9"?l():h()}},function(f,b){var _;return a=f+"",r=0,n=" ",_=g(),p(),n&&i("Syntax error"),typeof b=="function"?function M(B,Z){var N,R,O=B[Z];return O&&typeof O=="object"&&Object.keys(O).forEach(function(ee){R=M(O,ee),R!==void 0?O[ee]=R:delete O[ee]}),b.call(B,Z,O)}({"":_},""):_}};od.exports=Ib});var ld=te((ZA,Ro)=>{"use strict";var id=nd().stringify,sd=ad();Ro.exports=function(t){return{parse:sd(t),stringify:id}};Ro.exports.parse=sd();Ro.exports.stringify=id});var fi=te(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GCE_LINUX_BIOS_PATHS=void 0;Ht.isGoogleCloudServerless=dd;Ht.isGoogleComputeEngineLinux=pd;Ht.isGoogleComputeEngineMACAddress=hd;Ht.isGoogleComputeEngine=fd;Ht.detectGCPResidency=kb;var cd=_e("fs"),ud=_e("os");Ht.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Ab=/^42:01/;function dd(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function pd(){if((0,ud.platform)()!=="linux")return!1;try{(0,cd.statSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,cd.readFileSync)(Ht.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function hd(){let t=(0,ud.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(Ab.test(r))return!0}return!1}function fd(){return pd()||hd()}function kb(){return dd()||fd()}});var md=te(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.Colours=void 0;var ot=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Oo.Colours=ot;ot.enabled=!1;ot.reset="";ot.bright="";ot.dim="";ot.red="";ot.green="";ot.yellow="";ot.blue="";ot.magenta="";ot.cyan="";ot.white="";ot.grey="";ot.refresh()});var bd=te(De=>{"use strict";var Rb=De&&De.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ob=De&&De.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gd=De&&De.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Rb(r,e,n[o]);return Ob(r,e),r}}();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=gi;De.getDebugBackend=Mb;De.getStructuredBackend=Pb;De.setBackend=Db;De.log=vd;var Nb=_e("events"),Dn=gd(_e("process")),yd=gd(_e("util")),gt=md(),qt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(qt||(De.LogSeverity=qt={}));var jn=class extends Nb.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>vd(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};De.AdhocDebugLogger=jn;De.placeholder=new jn("",()=>{}).func;var Zr=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Dn.env[De.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(r,...n)}catch(o){console.error(o)}}};De.DebugLogBackendBase=Zr;var mi=class extends Zr{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let a=`${gt.Colours.green}${e}${gt.Colours.reset}`,i=`${gt.Colours.yellow}${Dn.pid}${gt.Colours.reset}`,s;switch(r.severity){case qt.ERROR:s=`${gt.Colours.red}${r.severity}${gt.Colours.reset}`;break;case qt.INFO:s=`${gt.Colours.magenta}${r.severity}${gt.Colours.reset}`;break;case qt.WARNING:s=`${gt.Colours.yellow}${r.severity}${gt.Colours.reset}`;break;default:s=(o=r.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let l=yd.formatWithOptions({colors:gt.Colours.enabled},...n),c=Object.assign({},r);delete c.severity;let p=Object.getOwnPropertyNames(c).length?JSON.stringify(c):"",h=p?`${gt.Colours.grey}${p}${gt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",i,a,s,l,p?` ${h}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function gi(){return new mi}var yi=class extends Zr{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=Dn.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Dn.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Mb(t){return new yi(t)}var vi=class extends Zr{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(o,...a)=>{var i;let s=(i=o.severity)!==null&&i!==void 0?i:qt.INFO,l=Object.assign({severity:s,message:yd.format(...a)},o),c=JSON.stringify(l);n?n(o,c):console.log("%s",c)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Pb(t){return new vi(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var bi=new Map,yt;function Db(t){yt=t,bi.clear()}function vd(t,e){if(!yt&&!Dn.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=bi.get(t);if(r)return r.func;if(yt===null)return De.placeholder;yt===void 0&&(yt=gi());let n=(()=>{let o;return new jn(t,(i,...s)=>{if(o!==yt){if(yt===null)return;yt===void 0&&(yt=gi()),o=yt}yt?.log(t,i,...s)})})();return bi.set(t,n),n.func}});var _i=te(qr=>{"use strict";var jb=qr&&qr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Lb=qr&&qr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&jb(e,t,r)};Object.defineProperty(qr,"__esModule",{value:!0});Lb(bd(),qr)});var Fn=te(pe=>{"use strict";var wd=pe&&pe.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Fb=pe&&pe.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ub=pe&&pe.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&wd(r,e,n[o]);return Fb(r,e),r}}(),Hb=pe&&pe.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wd(e,t,r)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=zb;pe.project=Wb;pe.universe=Jb;pe.bulk=Kb;pe.isAvailable=Xb;pe.resetIsAvailableCache=Zb;pe.getGCPResidency=Ti;pe.setGCPResidency=Ed;pe.requestTimeout=Td;var wi=rt(),qb=ld(),$b=fi(),Gb=Ub(_i());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var _d=Gb.log("gcp-metadata");pe.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 Ei(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function Bb(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Ln(t,e={},r=3,n=!1){let o=new Headers(pe.HEADERS),a="",i={};if(typeof t=="object"){let h=t;new Headers(h.headers).forEach((g,y)=>o.set(y,g)),a=h.metadataKey,i=h.params||i,r=h.noResponseRetries||r,n=h.fastFail||n}else a=t;typeof e=="string"?a+=`/${e}`:(Bb(e),e.property&&(a+=`/${e.property}`),new Headers(e.headers).forEach((h,g)=>o.set(g,h)),i=e.params||i);let s=n?Vb:wi.request,l={url:`${Ei()}/${a}`,headers:o,retryConfig:{noResponseRetries:r},params:i,responseType:"text",timeout:Td()};_d.info("instance request %j",l);let c=await s(l);_d.info("instance metadata is %s",c.data);let p=c.headers.get(pe.HEADER_NAME);if(p!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${p?`'${p}'`:"no header"}`);if(typeof c.data=="string")try{return qb.parse(c.data)}catch{}return c.data}async function Vb(t){let e={...t,url:t.url?.toString().replace(Ei(),Ei(pe.SECONDARY_HOST_ADDRESS))},r=(0,wi.request)(t),n=(0,wi.request)(e);return Promise.any([r,n])}function zb(t){return Ln("instance",t)}function Wb(t){return Ln("project",t)}function Jb(t){return Ln("universe",t)}async function Kb(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Ln(r),o=r.metadataKey;e[o]=n})())),e}function Yb(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var No;async function Xb(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Ti();case"ping-only":}}try{return No===void 0&&(No=Ln("instance",void 0,Yb(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await No,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function Zb(){No=void 0}pe.gcpResidencyCache=null;function Ti(){return pe.gcpResidencyCache===null&&Ed(),pe.gcpResidencyCache}function Ed(t=null){pe.gcpResidencyCache=t!==null?t:(0,$b.detectGCPResidency)()}function Td(){return Ti()?0:3e3}Hb(fi(),pe)});var Cd=te(Mo=>{"use strict";Mo.byteLength=e_;Mo.toByteArray=r_;Mo.fromByteArray=a_;var Yt=[],At=[],Qb=typeof Uint8Array<"u"?Uint8Array:Array,xi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for($r=0,xd=xi.length;$r<xd;++$r)Yt[$r]=xi[$r],At[xi.charCodeAt($r)]=$r;var $r,xd;At[45]=62;At[95]=63;function Sd(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function e_(t){var e=Sd(t),r=e[0],n=e[1];return(r+n)*3/4-n}function t_(t,e,r){return(e+r)*3/4-r}function r_(t){var e,r=Sd(t),n=r[0],o=r[1],a=new Qb(t_(t,n,o)),i=0,s=o>0?n-4:n,l;for(l=0;l<s;l+=4)e=At[t.charCodeAt(l)]<<18|At[t.charCodeAt(l+1)]<<12|At[t.charCodeAt(l+2)]<<6|At[t.charCodeAt(l+3)],a[i++]=e>>16&255,a[i++]=e>>8&255,a[i++]=e&255;return o===2&&(e=At[t.charCodeAt(l)]<<2|At[t.charCodeAt(l+1)]>>4,a[i++]=e&255),o===1&&(e=At[t.charCodeAt(l)]<<10|At[t.charCodeAt(l+1)]<<4|At[t.charCodeAt(l+2)]>>2,a[i++]=e>>8&255,a[i++]=e&255),a}function n_(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function o_(t,e,r){for(var n,o=[],a=e;a<r;a+=3)n=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),o.push(n_(n));return o.join("")}function a_(t){for(var e,r=t.length,n=r%3,o=[],a=16383,i=0,s=r-n;i<s;i+=a)o.push(o_(t,i,i+a>s?s:i+a));return n===1?(e=t[r-1],o.push(Yt[e>>2]+Yt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(Yt[e>>10]+Yt[e>>4&63]+Yt[e<<2&63]+"=")),o.join("")}});var Ci=te(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.fromArrayBufferToHex=i_;function i_(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var Id=te(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.BrowserCrypto=void 0;var Qr=Cd(),s_=Ci(),Ii=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return Qr.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Qr.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},a=new TextEncoder().encode(r),i=Qr.toByteArray(t.padBase64(n)),s=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,s,i,a)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),a=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),i=await window.crypto.subtle.sign(n,a,o);return Qr.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let r=Qr.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Qr.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,s_.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,a=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",a,o.encode(r))}};Po.BrowserCrypto=Ii});var Ad=te(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.NodeCrypto=void 0;var en=_e("crypto"),Ai=class{async sha256DigestBase64(e){return en.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return en.randomBytes(e).toString("base64")}async verify(e,r,n){let o=en.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=en.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return en.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:c_(e);return l_(en.createHmac("sha256",n).update(r).digest())}};Do.NodeCrypto=Ai;function l_(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function c_(t){return Buffer.from(t)}});var Un=te(gr=>{"use strict";var u_=gr&&gr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),d_=gr&&gr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&u_(e,t,r)};Object.defineProperty(gr,"__esModule",{value:!0});gr.createCrypto=f_;gr.hasBrowserCrypto=kd;var p_=Id(),h_=Ad();d_(Ci(),gr);function f_(){return kd()?new p_.BrowserCrypto:new h_.NodeCrypto}function kd(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var tn=te((ki,Od)=>{"use strict";var jo=_e("buffer"),Xt=jo.Buffer;function Rd(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?Od.exports=jo:(Rd(jo,ki),ki.Buffer=Gr);function Gr(t,e,r){return Xt(t,e,r)}Gr.prototype=Object.create(Xt.prototype);Rd(Xt,Gr);Gr.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};Gr.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Gr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};Gr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return jo.SlowBuffer(t)}});var Md=te((ck,Nd)=>{"use strict";function Ri(t){var e=(t/8|0)+(t%8===0?0:1);return e}var m_={ES256:Ri(256),ES384:Ri(384),ES512:Ri(521)};function g_(t){var e=m_[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Nd.exports=g_});var Oi=te((uk,Ud)=>{"use strict";var Lo=tn().Buffer,Dd=Md(),Fo=128,jd=0,y_=32,v_=16,b_=2,Ld=v_|y_|jd<<6,Uo=b_|jd<<6;function __(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Fd(t){if(Lo.isBuffer(t))return t;if(typeof t=="string")return Lo.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function w_(t,e){t=Fd(t);var r=Dd(e),n=r+1,o=t.length,a=0;if(t[a++]!==Ld)throw new Error('Could not find expected "seq"');var i=t[a++];if(i===(Fo|1)&&(i=t[a++]),o-a<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-a)+'" remaining');if(t[a++]!==Uo)throw new Error('Could not find expected "int" for "r"');var s=t[a++];if(o-a-2<s)throw new Error('"r" specified length of "'+s+'", only "'+(o-a-2)+'" available');if(n<s)throw new Error('"r" specified length of "'+s+'", max of "'+n+'" is acceptable');var l=a;if(a+=s,t[a++]!==Uo)throw new Error('Could not find expected "int" for "s"');var c=t[a++];if(o-a!==c)throw new Error('"s" specified length of "'+c+'", expected "'+(o-a)+'"');if(n<c)throw new Error('"s" specified length of "'+c+'", max of "'+n+'" is acceptable');var p=a;if(a+=c,a!==o)throw new Error('Expected to consume entire buffer, but "'+(o-a)+'" bytes remain');var h=r-s,g=r-c,y=Lo.allocUnsafe(h+s+g+c);for(a=0;a<h;++a)y[a]=0;t.copy(y,a,l+Math.max(-h,0),l+s),a=r;for(var S=a;a<S+g;++a)y[a]=0;return t.copy(y,a,p+Math.max(-g,0),p+c),y=y.toString("base64"),y=__(y),y}function Pd(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=Fo;return o&&--n,n}function E_(t,e){t=Fd(t);var r=Dd(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=Pd(t,0,r),a=Pd(t,r,t.length),i=r-o,s=r-a,l=2+i+1+1+s,c=l<Fo,p=Lo.allocUnsafe((c?2:3)+l),h=0;return p[h++]=Ld,c?p[h++]=l:(p[h++]=Fo|1,p[h++]=l&255),p[h++]=Uo,p[h++]=i,o<0?(p[h++]=0,h+=t.copy(p,h,0,r)):h+=t.copy(p,h,o,r),p[h++]=Uo,p[h++]=s,a<0?(p[h++]=0,t.copy(p,h,r)):t.copy(p,h,r+a),p}Ud.exports={derToJose:w_,joseToDer:E_}});var $t=te(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.LRUCache=void 0;yr.snakeToCamel=qd;yr.originalOrCamelOptions=C_;yr.removeUndefinedValuesInObject=I_;yr.isValidFile=A_;yr.getWellKnownCertificateConfigFileLocation=k_;var T_=_e("fs"),x_=_e("os"),Ni=_e("path"),S_="certificate_config.json",Hd="gcloud";function qd(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function C_(t){function e(r){let n=t||{};return n[r]??n[qd(r)]}return{get:e}}var Mi=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};yr.LRUCache=Mi;function I_(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function A_(t){try{return(await T_.promises.lstat(t)).isFile()}catch{return!1}}function k_(){let t=process.env.CLOUDSDK_CONFIG||(R_()?Ni.join(process.env.APPDATA||"",Hd):Ni.join(process.env.HOME||"",".config",Hd));return Ni.join(t,S_)}function R_(){return x_.platform().startsWith("win")}});var $d=te((pk,O_)=>{O_.exports={name:"google-auth-library",version:"10.5.0",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:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^8.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",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.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-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.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},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"}});var Pi=te(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.USER_AGENT=Cr.PRODUCT_NAME=Cr.pkg=void 0;var Gd=$d();Cr.pkg=Gd;var Bd="google-api-nodejs-client";Cr.PRODUCT_NAME=Bd;var N_=`${Bd}/${Gd.version}`;Cr.USER_AGENT=N_});var vt=te(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AuthClient=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Gt.DEFAULT_UNIVERSE=void 0;var M_=_e("events"),Di=rt(),P_=$t(),D_=_i(),ji=Pi();Gt.DEFAULT_UNIVERSE="googleapis.com";Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Li=class t extends M_.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Gt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Gt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,P_.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??Gt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Di.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],o,a=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Di.Gaxios.mergeHeaders(a,r.headers),n&&Di.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:a,url:o}):this.request({...n,headers:a,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,D_.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${ji.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${ji.USER_AGENT}`):e.headers.set("User-Agent",ji.USER_AGENT);try{let n=e,o=n[t.RequestMethodNameSymbol],a=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=a;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,a,i):t.log.info("[%s] request %j",a,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Gt.AuthClient=Li});var Ui=te(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.LoginTicket=void 0;var Fi=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Ho.LoginTicket=Fi});var Br=te(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.OAuth2Client=Zt.ClientAuthentication=Zt.CertificateFormat=Zt.CodeChallengeMethod=void 0;var Vd=rt(),j_=_e("querystring"),L_=_e("stream"),F_=Oi(),zd=$t(),Hi=Un(),rn=vt(),U_=Ui(),Wd;(function(t){t.Plain="plain",t.S256="S256"})(Wd||(Zt.CodeChallengeMethod=Wd={}));var vr;(function(t){t.PEM="PEM",t.JWK="JWK"})(vr||(Zt.CertificateFormat=vr={}));var Hn;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Hn||(Zt.ClientAuthentication=Hn={}));var qi=class t extends rn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=vr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Hn.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+j_.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Hi.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),a=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:a}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Hn.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Hn.ClientSecretPost&&(o.client_secret=this._clientSecret);let a={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,zd.removeUndefinedValuesInObject)(o)),headers:n};rn.AuthClient.setMethodName(a,"getTokenAsync");let i=await this.transporter.request(a),s=i.data;return i.data&&i.data.expires_in&&(s.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:i}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,zd.removeUndefinedValuesInObject)(n))};rn.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof Vd.GaxiosError&&i.message==="invalid_grant"&&i.response?.data&&/ReAuth/i.test(i.response.data.error_description)&&(i.message=JSON.stringify(i.response.data)),i}let a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{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(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let s=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(s)}}if(this.refreshHandler){let s=await this.processAndValidateRefreshHandler();if(s?.access_token){this.setCredentials(s);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(r.refresh_token),o=n.tokens}catch(s){let l=s;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let a=this.credentials;a.token_type=a.token_type||"Bearer",o.refresh_token=a.refresh_token,this.credentials=o;let i=new Headers({authorization:a.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(i),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(rn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Vd.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.response;if(o){let a=o.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),s=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof L_.Readable,c=a===401||a===403;if(!r&&c&&!l&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&c&&!l&&s){let p=await this.processAndValidateRefreshHandler();return p?.access_token&&this.setCredentials(p),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,Hi.hasBrowserCrypto)()?vr.JWK:vr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case vr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case vr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let c={...t.RETRY_CONFIG,url:o};rn.AuthClient.setMethodName(c,"getFederatedSignonCertsAsync"),n=await this.transporter.request(c)}catch(c){throw c instanceof Error&&(c.message=`Failed to retrieve verification certificates: ${c.message}`),c}let a=n?.headers.get("cache-control"),i=-1;if(a){let c=/max-age=(?<maxAge>[0-9]+)/.exec(a)?.groups?.maxAge;c&&(i=Number(c)*1e3)}let s={};switch(r){case vr.PEM:s=n.data;break;case vr.JWK:for(let c of n.data.keys)s[c.kid]=c;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=i===-1?null:new Date(l.getTime()+i),this.certificateCache=s,this.certificateCacheFormat=r,{certs:s,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};rn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,o,a){let i=(0,Hi.createCrypto)();a||(a=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let s=e.split(".");if(s.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=s[0]+"."+s[1],c=s[2],p,h;try{p=JSON.parse(i.decodeBase64StringUtf8(s[0]))}catch(B){throw B instanceof Error&&(B.message=`Can't parse token envelope: ${s[0]}': ${B.message}`),B}if(!p)throw new Error("Can't parse token envelope: "+s[0]);try{h=JSON.parse(i.decodeBase64StringUtf8(s[1]))}catch(B){throw B instanceof Error&&(B.message=`Can't parse token payload '${s[0]}`),B}if(!h)throw new Error("Can't parse token payload: "+s[1]);if(!Object.prototype.hasOwnProperty.call(r,p.kid))throw new Error("No pem found for envelope: "+JSON.stringify(p));let g=r[p.kid];if(p.alg==="ES256"&&(c=F_.joseToDer(c,"ES256").toString("base64")),!await i.verify(g,l,c))throw new Error("Invalid token signature: "+e);if(!h.iat)throw new Error("No issue time in token: "+JSON.stringify(h));if(!h.exp)throw new Error("No expiration time in token: "+JSON.stringify(h));let S=Number(h.iat);if(isNaN(S))throw new Error("iat field using invalid format");let f=Number(h.exp);if(isNaN(f))throw new Error("exp field using invalid format");let b=new Date().getTime()/1e3;if(f>=b+a)throw new Error("Expiration time too far in future: "+JSON.stringify(h));let _=S-t.CLOCK_SKEW_SECS_,M=f+t.CLOCK_SKEW_SECS_;if(b<_)throw new Error("Token used too early, "+b+" < "+_+": "+JSON.stringify(h));if(b>M)throw new Error("Token used too late, "+b+" > "+M+": "+JSON.stringify(h));if(o&&o.indexOf(h.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+h.iss);if(typeof n<"u"&&n!==null){let B=h.aud,Z=!1;if(n.constructor===Array?Z=n.indexOf(B)>-1:Z=B===n,!Z)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new U_.LoginTicket(p,h)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Zt.OAuth2Client=qi});var Gi=te(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.Compute=void 0;var H_=rt(),Jd=Fn(),q_=Br(),$i=class extends q_.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await Jd.instance(o)}catch(o){throw o instanceof H_.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:r};n=await Jd.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.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:r.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))}};qo.Compute=$i});var Vi=te($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.IdTokenClient=void 0;var $_=Br(),Bi=class extends $_.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};$o.IdTokenClient=Bi});var zi=te(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.GCPEnv=void 0;nn.clear=G_;nn.getEnv=B_;var Kd=Fn(),Qt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Qt||(nn.GCPEnv=Qt={}));var qn;function G_(){qn=void 0}async function B_(){return qn||(qn=V_(),qn)}async function V_(){let t=Qt.NONE;return z_()?t=Qt.APP_ENGINE:W_()?t=Qt.CLOUD_FUNCTIONS:await X_()?await Y_()?t=Qt.KUBERNETES_ENGINE:J_()?t=Qt.CLOUD_RUN:K_()?t=Qt.CLOUD_RUN_JOBS:t=Qt.COMPUTE_ENGINE:t=Qt.NONE,t}function z_(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function W_(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function J_(){return!!process.env.K_CONFIGURATION}function K_(){return!!process.env.CLOUD_RUN_JOB}async function Y_(){try{return await Kd.instance("attributes/cluster-name"),!0}catch{return!1}}async function X_(){return Kd.isAvailable()}});var Wi=te((_k,Yd)=>{"use strict";var Go=tn().Buffer,Z_=_e("stream"),Q_=_e("util");function Bo(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Go.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Go.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}Q_.inherits(Bo,Z_);Bo.prototype.write=function(e){this.buffer=Go.concat([this.buffer,Go.from(e)]),this.emit("data",e)};Bo.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Yd.exports=Bo});var Zd=te((wk,Xd)=>{"use strict";var $n=_e("buffer").Buffer,Ji=_e("buffer").SlowBuffer;Xd.exports=Vo;function Vo(t,e){if(!$n.isBuffer(t)||!$n.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}Vo.install=function(){$n.prototype.equal=Ji.prototype.equal=function(e){return Vo(this,e)}};var ew=$n.prototype.equal,tw=Ji.prototype.equal;Vo.restore=function(){$n.prototype.equal=ew,Ji.prototype.equal=tw}});var Zi=te((Ek,sp)=>{"use strict";var an=tn().Buffer,kt=_e("crypto"),ep=Oi(),Qd=_e("util"),rw=`"%s" is not a valid algorithm.
|
|
16
16
|
Supported algorithms are:
|
|
17
|
-
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,$n="secret must be a string or buffer",on="key must be a string or a buffer",nw="key must be a string, a buffer or an object",Yi=typeof kt.createPublicKey=="function";Yi&&(on+=" or a KeyObject",$n+="or a KeyObject");function tp(t){if(!an.isBuffer(t)&&typeof t!="string"&&(!Yi||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Bt(on)}function rp(t){if(!an.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Bt(nw)}function ow(t){if(!an.isBuffer(t)){if(typeof t=="string")return t;if(!Yi||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Bt($n)}}function Xi(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function np(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Bt(t){var e=[].slice.call(arguments,1),r=Qd.format.bind(Qd,t).apply(null,e);return new TypeError(r)}function aw(t){return an.isBuffer(t)||typeof t=="string"}function Bn(t){return aw(t)||(t=JSON.stringify(t)),t}function op(t){return function(r,n){ow(n),r=Bn(r);var o=kt.createHmac("sha"+t,n),a=(o.update(r),o.digest("base64"));return Xi(a)}}var Ki,iw="timingSafeEqual"in kt?function(e,r){return e.byteLength!==r.byteLength?!1:kt.timingSafeEqual(e,r)}:function(e,r){return Ki||(Ki=Zd()),Ki(e,r)};function sw(t){return function(r,n,o){var a=op(t)(r,o);return iw(an.from(n),an.from(a))}}function ap(t){return function(r,n){rp(n),r=Bn(r);var o=kt.createSign("RSA-SHA"+t),a=(o.update(r),o.sign(n,"base64"));return Xi(a)}}function ip(t){return function(r,n,o){tp(o),r=Bn(r),n=np(n);var a=kt.createVerify("RSA-SHA"+t);return a.update(r),a.verify(o,n,"base64")}}function lw(t){return function(r,n){rp(n),r=Bn(r);var o=kt.createSign("RSA-SHA"+t),a=(o.update(r),o.sign({key:n,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Xi(a)}}function cw(t){return function(r,n,o){tp(o),r=Bn(r),n=np(n);var a=kt.createVerify("RSA-SHA"+t);return a.update(r),a.verify({key:o,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function uw(t){var e=ap(t);return function(){var n=e.apply(null,arguments);return n=ep.derToJose(n,"ES"+t),n}}function dw(t){var e=ip(t);return function(n,o,a){o=ep.joseToDer(o,"ES"+t).toString("base64");var i=e(n,o,a);return i}}function pw(){return function(){return""}}function hw(){return function(e,r){return r===""}}sp.exports=function(e){var r={hs:op,rs:ap,ps:lw,es:uw,none:pw},n={hs:sw,rs:ip,ps:cw,es:dw,none:hw},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Bt(rw,e);var a=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:r[a](i),verify:n[a](i)}}});var Qi=ee((Tk,lp)=>{"use strict";var fw=be("buffer").Buffer;lp.exports=function(e){return typeof e=="string"?e:typeof e=="number"||fw.isBuffer(e)?e.toString():JSON.stringify(e)}});var fp=ee((xk,hp)=>{"use strict";var mw=tn().Buffer,cp=Wi(),gw=Zi(),yw=be("stream"),up=Qi(),es=be("util");function dp(t,e){return mw.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function vw(t,e,r){r=r||"utf8";var n=dp(up(t),"binary"),o=dp(up(e),r);return es.format("%s.%s",n,o)}function pp(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,a=gw(e.alg),i=vw(e,r,o),s=a.sign(i,n);return es.format("%s.%s",i,s)}function zo(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new cp(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new cp(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}es.inherits(zo,yw);zo.prototype.sign=function(){try{var e=pp({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};zo.sign=pp;hp.exports=zo});var xp=ee((Sk,Tp)=>{"use strict";var gp=tn().Buffer,mp=Wi(),bw=Zi(),_w=be("stream"),yp=Qi(),ww=be("util"),Ew=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Tw(t){return Object.prototype.toString.call(t)==="[object Object]"}function xw(t){if(Tw(t))return t;try{return JSON.parse(t)}catch{return}}function vp(t){var e=t.split(".",1)[0];return xw(gp.from(e,"base64").toString("binary"))}function Sw(t){return t.split(".",2).join(".")}function bp(t){return t.split(".")[2]}function Cw(t,e){e=e||"utf8";var r=t.split(".")[1];return gp.from(r,"base64").toString(e)}function _p(t){return Ew.test(t)&&!!vp(t)}function wp(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=yp(t);var o=bp(t),a=Sw(t),i=bw(e);return i.verify(a,o,r)}function Ep(t,e){if(e=e||{},t=yp(t),!_p(t))return null;var r=vp(t);if(!r)return null;var n=Cw(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:bp(t)}}function sn(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new mp(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new mp(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}ww.inherits(sn,_w);sn.prototype.verify=function(){try{var e=wp(this.signature.buffer,this.algorithm,this.key.buffer),r=Ep(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};sn.decode=Ep;sn.isValid=_p;sn.verify=wp;Tp.exports=sn});var ts=ee(Ir=>{"use strict";var Sp=fp(),Wo=xp(),Iw=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Ir.ALGORITHMS=Iw;Ir.sign=Sp.sign;Ir.verify=Wo.verify;Ir.decode=Wo.decode;Ir.isValid=Wo.isValid;Ir.createSign=function(e){return new Sp(e)};Ir.createVerify=function(e){return new Wo(e)}});var Hp=ee(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.GoogleToken=void 0;var Cp=Jo(be("fs")),Aw=rt(),kw=Jo(ts()),Rw=Jo(be("path")),Ow=be("util");function Jo(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Jo=function(a,i){if(!i&&a&&a.__esModule)return a;var s,l,c={__proto__:null,default:a};if(a===null||br(a)!="object"&&typeof a!="function")return c;if(s=i?n:r){if(s.has(a))return s.get(a);s.set(a,c)}for(var p in a)p!=="default"&&{}.hasOwnProperty.call(a,p)&&((l=(s=Object.defineProperty)&&Object.getOwnPropertyDescriptor(a,p))&&(l.get||l.set)?s(c,p,l):c[p]=a[p]);return c})(t,e)}function br(t){"@babel/helpers - typeof";return br=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},br(t)}function Nw(t,e){Dp(t,e),e.add(t)}function Mw(t,e,r){Dp(t,e),e.set(t,r)}function Dp(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Ip(t,e,r){return t.set(Vt(t,e),r),r}function Ap(t,e){return t.get(Vt(t,e))}function Vt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function kp(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Up(n.key),n)}}function jp(t,e,r){return e&&kp(t.prototype,e),r&&kp(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Lp(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Pw(t,e,r){return e=Jn(e),Dw(t,ss()?Reflect.construct(e,r||[],Jn(t).constructor):e.apply(t,r))}function Dw(t,e){if(e&&(br(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return jw(t)}function jw(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Lw(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Wn(t,e)}function rs(t){var e=typeof Map=="function"?new Map:void 0;return rs=function(n){if(n===null||!Fw(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,o)}function o(){return Uw(n,arguments,Jn(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Wn(o,n)},rs(t)}function Uw(t,e,r){if(ss())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&Wn(o,r.prototype),o}function ss(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ss=function(){return!!t})()}function Fw(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Wn(t,e){return Wn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Wn(t,e)}function Jn(t){return Jn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Jn(t)}function bt(t,e,r){return(e=Up(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Up(t){var e=Hw(t,"string");return br(e)=="symbol"?e:e+""}function Hw(t,e){if(br(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(br(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(g,T,y,b){var _=T&&T.prototype instanceof s?T:s,D=Object.create(_.prototype);return _t(D,"_invoke",function(V,X,P){var N,R,Q,E=0,re=P||[],Z=!1,Y={p:0,n:0,v:t,a:ce,f:ce.bind(t,4),d:function(J,fe){return N=J,R=0,Q=t,Y.n=fe,i}};function ce(B,J){for(R=B,Q=J,e=0;!Z&&E&&!fe&&e<re.length;e++){var fe,j=re[e],ye=Y.p,Se=j[2];B>3?(fe=Se===J)&&(Q=j[(R=j[4])?5:(R=3,3)],j[4]=j[5]=t):j[0]<=ye&&((fe=B<2&&ye<j[1])?(R=0,Y.v=J,Y.n=j[1]):ye<Se&&(fe=B<3||j[0]>J||J>Se)&&(j[4]=B,j[5]=J,Y.n=Se,R=0))}if(fe||B>1)return i;throw Z=!0,J}return function(B,J,fe){if(E>1)throw TypeError("Generator is already running");for(Z&&J===1&&ce(J,fe),R=J,Q=fe;(e=R<2?t:Q)||!Z;){N||(R?R<3?(R>1&&(Y.n=-1),ce(R,Q)):Y.n=Q:Y.v=Q);try{if(E=2,N){if(R||(B="next"),e=N[B]){if(!(e=e.call(N,Q)))throw TypeError("iterator result is not an object");if(!e.done)return e;Q=e.value,R<2&&(R=0)}else R===1&&(e=N.return)&&e.call(N),R<2&&(Q=TypeError("The iterator does not provide a '"+B+"' method"),R=1);N=t}else if((e=(Z=Y.n<0)?Q:V.call(X,Y))!==i)break}catch(j){N=t,R=1,Q=j}finally{E=1}}return{value:e,done:Z}}}(g,y,b),!0),D}var i={};function s(){}function l(){}function c(){}e=Object.getPrototypeOf;var p=[][n]?e(e([][n]())):(_t(e={},n,function(){return this}),e),h=c.prototype=s.prototype=Object.create(p);function m(g){return Object.setPrototypeOf?Object.setPrototypeOf(g,c):(g.__proto__=c,_t(g,o,"GeneratorFunction")),g.prototype=Object.create(h),g}return l.prototype=c,_t(h,"constructor",c),_t(c,"constructor",l),l.displayName="GeneratorFunction",_t(c,o,"GeneratorFunction"),_t(h),_t(h,o,"Generator"),_t(h,n,function(){return this}),_t(h,"toString",function(){return"[object Generator]"}),(wt=function(){return{w:a,m}})()}function _t(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}_t=function(i,s,l,c){if(s)o?o(i,s,{value:l,enumerable:!c,configurable:!c,writable:!c}):i[s]=l;else{var p=function(m,g){_t(i,m,function(T){return this._invoke(m,g,T)})};p("next",0),p("throw",1),p("return",2)}},_t(t,e,r,n)}function Rp(t,e,r,n,o,a,i){try{var s=t[a](i),l=s.value}catch(c){return void r(c)}s.done?e(l):Promise.resolve(l).then(n,o)}function ln(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var a=t.apply(e,r);function i(l){Rp(a,n,o,i,s,"next",l)}function s(l){Rp(a,n,o,i,s,"throw",l)}i(void 0)})}}var Op=Cp.readFile?(0,Ow.promisify)(Cp.readFile):ln(wt().m(function t(){return wt().w(function(e){for(;;)switch(e.n){case 0:throw new zn("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Np="https://oauth2.googleapis.com/token",qw="https://oauth2.googleapis.com/revoke?token=",zn=function(t){function e(r,n){var o;return Lp(this,e),o=Pw(this,e,[r]),bt(o,"code",void 0),o.code=n,o}return Lw(e,t),jp(e)}(rs(Error)),Vn=new WeakMap,er=new WeakSet,Ik=Ko.GoogleToken=function(){function t(e){Lp(this,t),Nw(this,er),bt(this,"expiresAt",void 0),bt(this,"key",void 0),bt(this,"keyFile",void 0),bt(this,"iss",void 0),bt(this,"sub",void 0),bt(this,"scope",void 0),bt(this,"rawToken",void 0),bt(this,"tokenExpires",void 0),bt(this,"email",void 0),bt(this,"additionalClaims",void 0),bt(this,"eagerRefreshThresholdMillis",void 0),bt(this,"transporter",{request:function(n){return(0,Aw.request)(n)}}),Mw(this,Vn,void 0),Vt(er,this,Fp).call(this,e)}return jp(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(br(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Vt(er,this,Mp).call(this,n).then(function(a){return o(null,a)},r);return}return Vt(er,this,Mp).call(this,n)}},{key:"getCredentials",value:function(){var e=ln(wt().m(function n(o){var a,i,s,l,c,p,h;return wt().w(function(m){for(;;)switch(m.n){case 0:a=Rw.extname(o),h=a,m.n=h===".json"?1:h===".der"||h===".crt"||h===".pem"?4:h===".p12"||h===".pfx"?6:7;break;case 1:return m.n=2,Op(o,"utf8");case 2:if(i=m.v,s=JSON.parse(i),l=s.private_key,c=s.client_email,!(!l||!c)){m.n=3;break}throw new zn("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:c});case 4:return m.n=5,Op(o,"utf8");case 5:return p=m.v,m.a(2,{privateKey:p});case 6:throw new zn("*.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");case 7:throw new zn("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r}()},{key:"revokeToken",value:function(r){if(r){Vt(er,this,Pp).call(this).then(function(){return r()},r);return}return Vt(er,this,Pp).call(this)}}])}();function Mp(t){return ns.apply(this,arguments)}function ns(){return ns=ln(wt().m(function t(e){return wt().w(function(r){for(;;)switch(r.n){case 0:if(!(Ap(Vn,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,Ap(Vn,this));case 1:return r.p=1,r.n=2,Ip(Vn,this,Vt(er,this,Gw).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,Ip(Vn,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),ns.apply(this,arguments)}function Gw(t){return os.apply(this,arguments)}function os(){return os=ln(wt().m(function t(e){var r;return wt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||Vt(er,this,$w).call(this);case 4:return n.a(2,Vt(er,this,Bw).call(this))}},t,this)})),os.apply(this,arguments)}function $w(){if(!this.iss)throw new zn("email is required.","MISSING_CREDENTIALS")}function Pp(){return as.apply(this,arguments)}function as(){return as=ln(wt().m(function t(){var e;return wt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=qw+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Vt(er,this,Fp).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),as.apply(this,arguments)}function Fp(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,br(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function Bw(){return is.apply(this,arguments)}function is(){return is=ln(wt().m(function t(){var e,r,n,o,a,i,s,l,c,p;return wt().w(function(h){for(;;)switch(h.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:Np,exp:e+3600,iat:e,sub:this.sub},r),o=kw.sign({header:{alg:"RS256"},payload:n,secret:this.key}),h.p=1,h.n=2,this.transporter.request({method:"POST",url:Np,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return a=h.v,this.rawToken=a.data,this.expiresAt=a.data.expires_in===null||a.data.expires_in===void 0?void 0:(e+a.data.expires_in)*1e3,h.a(2,this.rawToken);case 3:throw h.p=3,p=h.v,this.rawToken=void 0,this.tokenExpires=void 0,l=p.response&&(i=p.response)!==null&&i!==void 0&&i.data?(s=p.response)===null||s===void 0?void 0:s.data:{},l.error&&(c=l.error_description?": ".concat(l.error_description):"",p.message="".concat(l.error).concat(c)),p;case 4:return h.a(2)}},t,this,[[1,3]])})),is.apply(this,arguments)}});var cs=ee(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.JWTAccess=void 0;var Vw=ts(),zw=Gt(),qp={alg:"RS256",typ:"JWT"},ls=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new zw.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let o=this.getCachedKey(e,n),a=this.cache.get(o),i=Date.now();if(a&&a.expiration-i>this.eagerRefreshThresholdMillis)return new Headers(a.headers);let s=Math.floor(Date.now()/1e3),l=t.getExpirationTime(s),c;if(Array.isArray(n)&&(n=n.join(" ")),n?c={iss:this.email,sub:this.email,scope:n,exp:l,iat:s}:c={iss:this.email,sub:this.email,aud:e,exp:l,iat:s},r){for(let T in c)if(r[T])throw new Error(`The '${T}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let p=this.keyId?{...qp,kid:this.keyId}:qp,h=Object.assign(c,r),m=Vw.sign({header:p,payload:h,secret:this.key}),g=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:g}),g}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",a=>o+=a).on("error",n).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),r()}catch(a){n(a)}})})}};Yo.JWTAccess=ls});var ds=ee(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.JWT=void 0;var Gp=Hp(),Ww=cs(),Jw=Br(),Xo=vt(),us=class t extends Jw.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Xo.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Xo.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Xo.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new Ww.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Xo.DEFAULT_UNIVERSE,a=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(a)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new Gp.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new Gp.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),r()}catch(a){n(a)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Zo.JWT=us});var hs=ee(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.UserRefreshClient=cn.USER_REFRESH_ACCOUNT_TYPE=void 0;var Kw=Br(),Yw=vt();cn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ps=class t extends Kw.OAuth2Client{_refreshToken;constructor(e,r,n,o,a){let i=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:a};super(i),this._refreshToken=i.refreshToken,this.credentials.refresh_token=i.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return Yw.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);return this.fromJSON(a),r()}catch(a){return n(a)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};cn.UserRefreshClient=ps});var ms=ee(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.Impersonated=un.IMPERSONATED_ACCOUNT_TYPE=void 0;var $p=Br(),Xw=rt(),Zw=Gt();un.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var fs=class t extends $p.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new $p.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,Zw.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),a=o.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof Xw.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,a={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:a,method:"POST"})).data.token}};un.Impersonated=fs});var ys=ee(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.OAuthClientAuthHandler=void 0;Kn.getErrorFromOAuthErrorResponse=tE;var dn=rt(),Qw=Fn(),eE=["PUT","POST","PATCH"],gs=class{#e=(0,Qw.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new dn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new dn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=dn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=dn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=dn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",a=this.#e.encodeBase64StringUtf8(`${n}:${o}`);dn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${a}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!eE.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let a=new URLSearchParams(e.data??"");a.append("client_id",this.#t.clientId),a.append("client_secret",this.#t.clientSecret||""),e.data=a}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Kn.OAuthClientAuthHandler=gs;function tE(t,e){let r=t.error,n=t.error_description,o=t.error_uri,a=`Error code ${r}`;typeof n<"u"&&(a+=`: ${n}`),typeof o<"u"&&(a+=` - ${o}`);let i=new Error(a);if(e){let s=Object.keys(e);e.stack&&s.push("stack"),s.forEach(l=>{l!=="message"&&Object.defineProperty(i,l,{value:e[l],writable:!1,enumerable:!0})})}return i}});var ea=ee(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.StsCredentials=void 0;var rE=rt(),nE=vt(),Bp=ys(),oE=Gt(),vs=class t extends Bp.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},a={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,oE.removeUndefinedValuesInObject)(o))};nE.AuthClient.setMethodName(a,"exchangeToken"),this.applyClientAuthenticationOptions(a);try{let i=await this.transporter.request(a),s=i.data;return s.res=i,s}catch(i){throw i instanceof rE.GaxiosError&&i.response?(0,Bp.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};Qo.StsCredentials=vs});var Ar=ee(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.BaseExternalAccountClient=Rt.CLOUD_RESOURCE_MANAGER=Rt.EXTERNAL_ACCOUNT_TYPE=Rt.EXPIRATION_TIME_OFFSET=void 0;var aE=rt(),iE=be("stream"),bs=vt(),sE=ea(),Vp=Gt(),lE=Pi(),cE="urn:ietf:params:oauth:grant-type:token-exchange",uE="urn:ietf:params:oauth:token-type:access_token",_s="https://www.googleapis.com/auth/cloud-platform",dE=3600;Rt.EXPIRATION_TIME_OFFSET=300*1e3;Rt.EXTERNAL_ACCOUNT_TYPE="external_account";Rt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var pE="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",hE="https://sts.{universeDomain}/v1/token",ws=class t extends bs.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,Vp.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Rt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Rt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),a=r.get("client_secret");this.tokenUrl=r.get("token_url")??hE.replace("{universeDomain}",this.universeDomain);let i=r.get("subject_token_type"),s=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),c=r.get("service_account_impersonation"),p=(0,Vp.originalOrCamelOptions)(c).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:a}),this.stsCredential=new sE.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[_s],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=s;let h=new RegExp(pE);if(this.workforcePoolUserProject&&!this.audience.match(h))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=p,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=dE),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};bs.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=aE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof iE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:cE,audience:this.audience,requestedTokenType:uE,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[_s]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),a=await this.stsCredential.exchangeToken(r,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(a.access_token):a.expires_in?this.cachedAccessToken={access_token:a.access_token,expiry_date:new Date().getTime()+a.expires_in*1e3,res:a.res}:this.cachedAccessToken={access_token:a.access_token,res:a.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};bs.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[_s]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${lE.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Rt.BaseExternalAccountClient=ws});var zp=ee(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.FileSubjectTokenSupplier=void 0;var Ts=be("util"),xs=be("fs"),fE=(0,Ts.promisify)(xs.readFile??(()=>{})),mE=(0,Ts.promisify)(xs.realpath??(()=>{})),gE=(0,Ts.promisify)(xs.lstat??(()=>{})),Es=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await mE(e),!(await gE(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r,n=await fE(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};ta.FileSubjectTokenSupplier=Es});var Wp=ee(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.UrlSubjectTokenSupplier=void 0;var yE=vt(),Ss=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};yE.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};ra.UrlSubjectTokenSupplier=Ss});var Jp=ee(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.CertificateSubjectTokenSupplier=Et.InvalidConfigurationError=Et.CertificateSourceUnavailableError=Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var na=Gt(),oa=be("fs"),aa=be("crypto"),vE=be("https");Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Et.CertificateSourceUnavailableError=tr;var Ot=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Et.InvalidConfigurationError=Ot;var Cs=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new vE.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,na.isValidFile)(e))return e;throw new tr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,na.isValidFile)(r))return r;throw new tr(`Path from environment variable "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,na.getWellKnownCertificateConfigFileLocation)();if(await(0,na.isValidFile)(n))return n;throw new tr(`Could not find certificate configuration file. Searched override path, the "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await oa.promises.readFile(e,"utf8")}catch{throw new tr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,a=n?.cert_configs?.workload?.key_path;if(!o||!a)throw new Ot(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:a}}catch(n){throw n instanceof Ot?n:new Ot(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await oa.promises.readFile(e),new aa.X509Certificate(n)}catch(a){let i=a instanceof Error?a.message:String(a);throw new tr(`Failed to read certificate file at ${e}: ${i}`)}try{o=await oa.promises.readFile(r),(0,aa.createPrivateKey)(o)}catch(a){let i=a instanceof Error?a.message:String(a);throw new tr(`Failed to read private key file at ${r}: ${i}`)}return{cert:n,key:o}}async#n(e){let r=new aa.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let a=((await oa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,c)=>{try{return new aa.X509Certificate(l)}catch(p){let h=p instanceof Error?p.message:String(p);throw new Ot(`Failed to parse certificate at index ${c} in trust chain file ${this.trustChainPath}: ${h}`)}}),i=a.findIndex(l=>r.raw.equals(l.raw)),s;if(i===-1)s=[r,...a];else if(i===0)s=a;else throw new Ot(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(s.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof Ot)throw n;let o=n instanceof Error?n.message:String(n);throw new tr(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Et.CertificateSubjectTokenSupplier=Cs});var ks=ee(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.IdentityPoolClient=void 0;var bE=Ar(),Is=Gt(),_E=zp(),wE=Wp(),Kp=Jp(),EE=ea(),Yp=rt(),As=class t extends bE.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,Is.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let a=(0,Is.originalOrCamelOptions)(n),i=(0,Is.originalOrCamelOptions)(a.get("format")),s=i.get("type")||"text",l=i.get("subject_token_field_name");if(s!=="json"&&s!=="text")throw new Error(`Invalid credential_source format "${s}"`);if(s==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let c=a.get("file"),p=a.get("url"),h=a.get("certificate"),m=a.get("headers");if(c&&p||p&&h||c&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(c)this.credentialSourceType="file",this.subjectTokenSupplier=new _E.FileSubjectTokenSupplier({filePath:c,formatType:s,subjectTokenFieldName:l});else if(p)this.credentialSourceType="url",this.subjectTokenSupplier=new wE.UrlSubjectTokenSupplier({url:p,formatType:s,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(h){this.credentialSourceType="certificate";let g=new Kp.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=g}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Kp.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new EE.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Yp.Gaxios({agent:r})}),this.transporter=new Yp.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};ia.IdentityPoolClient=As});var Os=ee(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.AwsRequestSigner=void 0;var sa=rt(),Zp=Fn(),Xp="AWS4-HMAC-SHA256",TE="aws4_request",Rs=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Zp.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",a=e.body||r,i=e.headers,s=await this.getCredentials(),l=new URL(n);if(typeof a!="string"&&a!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let c=await SE({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:s,requestPayload:a,additionalAmzHeaders:i}),p=sa.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:l.host},i||{});s.token&&sa.Gaxios.mergeHeaders(p,{"x-amz-security-token":s.token});let h={url:n,method:o,headers:p};return a!==void 0&&(h.body=a),h}};la.AwsRequestSigner=Rs;async function Yn(t,e,r){return await t.signWithHmacSha256(e,r)}async function xE(t,e,r,n,o){let a=await Yn(t,`AWS4${e}`,r),i=await Yn(t,a,n),s=await Yn(t,i,o);return await Yn(t,s,"aws4_request")}async function SE(t){let e=sa.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],o=new Date,a=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),i=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let s=sa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":a},e),l="",c=[...s.keys()].sort();c.forEach(D=>{l+=`${D}:${s.get(D)}
|
|
18
|
-
`});let p=c.join(";"),h=await t.crypto.sha256DigestHex(r),
|
|
17
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Gn="secret must be a string or buffer",on="key must be a string or a buffer",nw="key must be a string, a buffer or an object",Yi=typeof kt.createPublicKey=="function";Yi&&(on+=" or a KeyObject",Gn+="or a KeyObject");function tp(t){if(!an.isBuffer(t)&&typeof t!="string"&&(!Yi||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Bt(on)}function rp(t){if(!an.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Bt(nw)}function ow(t){if(!an.isBuffer(t)){if(typeof t=="string")return t;if(!Yi||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Bt(Gn)}}function Xi(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function np(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Bt(t){var e=[].slice.call(arguments,1),r=Qd.format.bind(Qd,t).apply(null,e);return new TypeError(r)}function aw(t){return an.isBuffer(t)||typeof t=="string"}function Bn(t){return aw(t)||(t=JSON.stringify(t)),t}function op(t){return function(r,n){ow(n),r=Bn(r);var o=kt.createHmac("sha"+t,n),a=(o.update(r),o.digest("base64"));return Xi(a)}}var Ki,iw="timingSafeEqual"in kt?function(e,r){return e.byteLength!==r.byteLength?!1:kt.timingSafeEqual(e,r)}:function(e,r){return Ki||(Ki=Zd()),Ki(e,r)};function sw(t){return function(r,n,o){var a=op(t)(r,o);return iw(an.from(n),an.from(a))}}function ap(t){return function(r,n){rp(n),r=Bn(r);var o=kt.createSign("RSA-SHA"+t),a=(o.update(r),o.sign(n,"base64"));return Xi(a)}}function ip(t){return function(r,n,o){tp(o),r=Bn(r),n=np(n);var a=kt.createVerify("RSA-SHA"+t);return a.update(r),a.verify(o,n,"base64")}}function lw(t){return function(r,n){rp(n),r=Bn(r);var o=kt.createSign("RSA-SHA"+t),a=(o.update(r),o.sign({key:n,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Xi(a)}}function cw(t){return function(r,n,o){tp(o),r=Bn(r),n=np(n);var a=kt.createVerify("RSA-SHA"+t);return a.update(r),a.verify({key:o,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function uw(t){var e=ap(t);return function(){var n=e.apply(null,arguments);return n=ep.derToJose(n,"ES"+t),n}}function dw(t){var e=ip(t);return function(n,o,a){o=ep.joseToDer(o,"ES"+t).toString("base64");var i=e(n,o,a);return i}}function pw(){return function(){return""}}function hw(){return function(e,r){return r===""}}sp.exports=function(e){var r={hs:op,rs:ap,ps:lw,es:uw,none:pw},n={hs:sw,rs:ip,ps:cw,es:dw,none:hw},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Bt(rw,e);var a=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:r[a](i),verify:n[a](i)}}});var Qi=te((Tk,lp)=>{"use strict";var fw=_e("buffer").Buffer;lp.exports=function(e){return typeof e=="string"?e:typeof e=="number"||fw.isBuffer(e)?e.toString():JSON.stringify(e)}});var fp=te((xk,hp)=>{"use strict";var mw=tn().Buffer,cp=Wi(),gw=Zi(),yw=_e("stream"),up=Qi(),es=_e("util");function dp(t,e){return mw.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function vw(t,e,r){r=r||"utf8";var n=dp(up(t),"binary"),o=dp(up(e),r);return es.format("%s.%s",n,o)}function pp(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,a=gw(e.alg),i=vw(e,r,o),s=a.sign(i,n);return es.format("%s.%s",i,s)}function zo(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new cp(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new cp(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}es.inherits(zo,yw);zo.prototype.sign=function(){try{var e=pp({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};zo.sign=pp;hp.exports=zo});var xp=te((Sk,Tp)=>{"use strict";var gp=tn().Buffer,mp=Wi(),bw=Zi(),_w=_e("stream"),yp=Qi(),ww=_e("util"),Ew=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Tw(t){return Object.prototype.toString.call(t)==="[object Object]"}function xw(t){if(Tw(t))return t;try{return JSON.parse(t)}catch{return}}function vp(t){var e=t.split(".",1)[0];return xw(gp.from(e,"base64").toString("binary"))}function Sw(t){return t.split(".",2).join(".")}function bp(t){return t.split(".")[2]}function Cw(t,e){e=e||"utf8";var r=t.split(".")[1];return gp.from(r,"base64").toString(e)}function _p(t){return Ew.test(t)&&!!vp(t)}function wp(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=yp(t);var o=bp(t),a=Sw(t),i=bw(e);return i.verify(a,o,r)}function Ep(t,e){if(e=e||{},t=yp(t),!_p(t))return null;var r=vp(t);if(!r)return null;var n=Cw(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:bp(t)}}function sn(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new mp(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new mp(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}ww.inherits(sn,_w);sn.prototype.verify=function(){try{var e=wp(this.signature.buffer,this.algorithm,this.key.buffer),r=Ep(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};sn.decode=Ep;sn.isValid=_p;sn.verify=wp;Tp.exports=sn});var ts=te(Ir=>{"use strict";var Sp=fp(),Wo=xp(),Iw=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Ir.ALGORITHMS=Iw;Ir.sign=Sp.sign;Ir.verify=Wo.verify;Ir.decode=Wo.decode;Ir.isValid=Wo.isValid;Ir.createSign=function(e){return new Sp(e)};Ir.createVerify=function(e){return new Wo(e)}});var Hp=te(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.GoogleToken=void 0;var Cp=Jo(_e("fs")),Aw=rt(),kw=Jo(ts()),Rw=Jo(_e("path")),Ow=_e("util");function Jo(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Jo=function(a,i){if(!i&&a&&a.__esModule)return a;var s,l,c={__proto__:null,default:a};if(a===null||br(a)!="object"&&typeof a!="function")return c;if(s=i?n:r){if(s.has(a))return s.get(a);s.set(a,c)}for(var p in a)p!=="default"&&{}.hasOwnProperty.call(a,p)&&((l=(s=Object.defineProperty)&&Object.getOwnPropertyDescriptor(a,p))&&(l.get||l.set)?s(c,p,l):c[p]=a[p]);return c})(t,e)}function br(t){"@babel/helpers - typeof";return br=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},br(t)}function Nw(t,e){Dp(t,e),e.add(t)}function Mw(t,e,r){Dp(t,e),e.set(t,r)}function Dp(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Ip(t,e,r){return t.set(Vt(t,e),r),r}function Ap(t,e){return t.get(Vt(t,e))}function Vt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function kp(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Fp(n.key),n)}}function jp(t,e,r){return e&&kp(t.prototype,e),r&&kp(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Lp(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Pw(t,e,r){return e=Jn(e),Dw(t,ss()?Reflect.construct(e,r||[],Jn(t).constructor):e.apply(t,r))}function Dw(t,e){if(e&&(br(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return jw(t)}function jw(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Lw(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Wn(t,e)}function rs(t){var e=typeof Map=="function"?new Map:void 0;return rs=function(n){if(n===null||!Uw(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,o)}function o(){return Fw(n,arguments,Jn(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Wn(o,n)},rs(t)}function Fw(t,e,r){if(ss())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&Wn(o,r.prototype),o}function ss(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ss=function(){return!!t})()}function Uw(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Wn(t,e){return Wn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Wn(t,e)}function Jn(t){return Jn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Jn(t)}function bt(t,e,r){return(e=Fp(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Fp(t){var e=Hw(t,"string");return br(e)=="symbol"?e:e+""}function Hw(t,e){if(br(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(br(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(y,S,f,b){var _=S&&S.prototype instanceof s?S:s,M=Object.create(_.prototype);return _t(M,"_invoke",function(B,Z,N){var R,O,ee,E=0,Q=N||[],X=!1,W={p:0,n:0,v:t,a:ue,f:ue.bind(t,4),d:function(K,me){return R=K,O=0,ee=t,W.n=me,i}};function ue(V,K){for(O=V,ee=K,e=0;!X&&E&&!me&&e<Q.length;e++){var me,j=Q[e],ve=W.p,Se=j[2];V>3?(me=Se===K)&&(ee=j[(O=j[4])?5:(O=3,3)],j[4]=j[5]=t):j[0]<=ve&&((me=V<2&&ve<j[1])?(O=0,W.v=K,W.n=j[1]):ve<Se&&(me=V<3||j[0]>K||K>Se)&&(j[4]=V,j[5]=K,W.n=Se,O=0))}if(me||V>1)return i;throw X=!0,K}return function(V,K,me){if(E>1)throw TypeError("Generator is already running");for(X&&K===1&&ue(K,me),O=K,ee=me;(e=O<2?t:ee)||!X;){R||(O?O<3?(O>1&&(W.n=-1),ue(O,ee)):W.n=ee:W.v=ee);try{if(E=2,R){if(O||(V="next"),e=R[V]){if(!(e=e.call(R,ee)))throw TypeError("iterator result is not an object");if(!e.done)return e;ee=e.value,O<2&&(O=0)}else O===1&&(e=R.return)&&e.call(R),O<2&&(ee=TypeError("The iterator does not provide a '"+V+"' method"),O=1);R=t}else if((e=(X=W.n<0)?ee:B.call(Z,W))!==i)break}catch(j){R=t,O=1,ee=j}finally{E=1}}return{value:e,done:X}}}(y,f,b),!0),M}var i={};function s(){}function l(){}function c(){}e=Object.getPrototypeOf;var p=[][n]?e(e([][n]())):(_t(e={},n,function(){return this}),e),h=c.prototype=s.prototype=Object.create(p);function g(y){return Object.setPrototypeOf?Object.setPrototypeOf(y,c):(y.__proto__=c,_t(y,o,"GeneratorFunction")),y.prototype=Object.create(h),y}return l.prototype=c,_t(h,"constructor",c),_t(c,"constructor",l),l.displayName="GeneratorFunction",_t(c,o,"GeneratorFunction"),_t(h),_t(h,o,"Generator"),_t(h,n,function(){return this}),_t(h,"toString",function(){return"[object Generator]"}),(wt=function(){return{w:a,m:g}})()}function _t(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}_t=function(i,s,l,c){if(s)o?o(i,s,{value:l,enumerable:!c,configurable:!c,writable:!c}):i[s]=l;else{var p=function(g,y){_t(i,g,function(S){return this._invoke(g,y,S)})};p("next",0),p("throw",1),p("return",2)}},_t(t,e,r,n)}function Rp(t,e,r,n,o,a,i){try{var s=t[a](i),l=s.value}catch(c){return void r(c)}s.done?e(l):Promise.resolve(l).then(n,o)}function ln(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var a=t.apply(e,r);function i(l){Rp(a,n,o,i,s,"next",l)}function s(l){Rp(a,n,o,i,s,"throw",l)}i(void 0)})}}var Op=Cp.readFile?(0,Ow.promisify)(Cp.readFile):ln(wt().m(function t(){return wt().w(function(e){for(;;)switch(e.n){case 0:throw new zn("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Np="https://oauth2.googleapis.com/token",qw="https://oauth2.googleapis.com/revoke?token=",zn=function(t){function e(r,n){var o;return Lp(this,e),o=Pw(this,e,[r]),bt(o,"code",void 0),o.code=n,o}return Lw(e,t),jp(e)}(rs(Error)),Vn=new WeakMap,er=new WeakSet,Ik=Ko.GoogleToken=function(){function t(e){Lp(this,t),Nw(this,er),bt(this,"expiresAt",void 0),bt(this,"key",void 0),bt(this,"keyFile",void 0),bt(this,"iss",void 0),bt(this,"sub",void 0),bt(this,"scope",void 0),bt(this,"rawToken",void 0),bt(this,"tokenExpires",void 0),bt(this,"email",void 0),bt(this,"additionalClaims",void 0),bt(this,"eagerRefreshThresholdMillis",void 0),bt(this,"transporter",{request:function(n){return(0,Aw.request)(n)}}),Mw(this,Vn,void 0),Vt(er,this,Up).call(this,e)}return jp(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(br(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Vt(er,this,Mp).call(this,n).then(function(a){return o(null,a)},r);return}return Vt(er,this,Mp).call(this,n)}},{key:"getCredentials",value:function(){var e=ln(wt().m(function n(o){var a,i,s,l,c,p,h;return wt().w(function(g){for(;;)switch(g.n){case 0:a=Rw.extname(o),h=a,g.n=h===".json"?1:h===".der"||h===".crt"||h===".pem"?4:h===".p12"||h===".pfx"?6:7;break;case 1:return g.n=2,Op(o,"utf8");case 2:if(i=g.v,s=JSON.parse(i),l=s.private_key,c=s.client_email,!(!l||!c)){g.n=3;break}throw new zn("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return g.a(2,{privateKey:l,clientEmail:c});case 4:return g.n=5,Op(o,"utf8");case 5:return p=g.v,g.a(2,{privateKey:p});case 6:throw new zn("*.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");case 7:throw new zn("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return g.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r}()},{key:"revokeToken",value:function(r){if(r){Vt(er,this,Pp).call(this).then(function(){return r()},r);return}return Vt(er,this,Pp).call(this)}}])}();function Mp(t){return ns.apply(this,arguments)}function ns(){return ns=ln(wt().m(function t(e){return wt().w(function(r){for(;;)switch(r.n){case 0:if(!(Ap(Vn,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,Ap(Vn,this));case 1:return r.p=1,r.n=2,Ip(Vn,this,Vt(er,this,$w).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,Ip(Vn,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),ns.apply(this,arguments)}function $w(t){return os.apply(this,arguments)}function os(){return os=ln(wt().m(function t(e){var r;return wt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||Vt(er,this,Gw).call(this);case 4:return n.a(2,Vt(er,this,Bw).call(this))}},t,this)})),os.apply(this,arguments)}function Gw(){if(!this.iss)throw new zn("email is required.","MISSING_CREDENTIALS")}function Pp(){return as.apply(this,arguments)}function as(){return as=ln(wt().m(function t(){var e;return wt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=qw+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Vt(er,this,Up).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),as.apply(this,arguments)}function Up(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,br(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function Bw(){return is.apply(this,arguments)}function is(){return is=ln(wt().m(function t(){var e,r,n,o,a,i,s,l,c,p;return wt().w(function(h){for(;;)switch(h.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:Np,exp:e+3600,iat:e,sub:this.sub},r),o=kw.sign({header:{alg:"RS256"},payload:n,secret:this.key}),h.p=1,h.n=2,this.transporter.request({method:"POST",url:Np,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return a=h.v,this.rawToken=a.data,this.expiresAt=a.data.expires_in===null||a.data.expires_in===void 0?void 0:(e+a.data.expires_in)*1e3,h.a(2,this.rawToken);case 3:throw h.p=3,p=h.v,this.rawToken=void 0,this.tokenExpires=void 0,l=p.response&&(i=p.response)!==null&&i!==void 0&&i.data?(s=p.response)===null||s===void 0?void 0:s.data:{},l.error&&(c=l.error_description?": ".concat(l.error_description):"",p.message="".concat(l.error).concat(c)),p;case 4:return h.a(2)}},t,this,[[1,3]])})),is.apply(this,arguments)}});var cs=te(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.JWTAccess=void 0;var Vw=ts(),zw=$t(),qp={alg:"RS256",typ:"JWT"},ls=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new zw.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let o=this.getCachedKey(e,n),a=this.cache.get(o),i=Date.now();if(a&&a.expiration-i>this.eagerRefreshThresholdMillis)return new Headers(a.headers);let s=Math.floor(Date.now()/1e3),l=t.getExpirationTime(s),c;if(Array.isArray(n)&&(n=n.join(" ")),n?c={iss:this.email,sub:this.email,scope:n,exp:l,iat:s}:c={iss:this.email,sub:this.email,aud:e,exp:l,iat:s},r){for(let S in c)if(r[S])throw new Error(`The '${S}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let p=this.keyId?{...qp,kid:this.keyId}:qp,h=Object.assign(c,r),g=Vw.sign({header:p,payload:h,secret:this.key}),y=new Headers({authorization:`Bearer ${g}`});return this.cache.set(o,{expiration:l*1e3,headers:y}),y}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",a=>o+=a).on("error",n).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),r()}catch(a){n(a)}})})}};Yo.JWTAccess=ls});var ds=te(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.JWT=void 0;var $p=Hp(),Ww=cs(),Jw=Br(),Xo=vt(),us=class t extends Jw.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Xo.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Xo.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Xo.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new Ww.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Xo.DEFAULT_UNIVERSE,a=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(a)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new $p.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new $p.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),r()}catch(a){n(a)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Zo.JWT=us});var hs=te(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.UserRefreshClient=cn.USER_REFRESH_ACCOUNT_TYPE=void 0;var Kw=Br(),Yw=vt();cn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ps=class t extends Kw.OAuth2Client{_refreshToken;constructor(e,r,n,o,a){let i=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:a};super(i),this._refreshToken=i.refreshToken,this.credentials.refresh_token=i.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return Yw.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);return this.fromJSON(a),r()}catch(a){return n(a)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};cn.UserRefreshClient=ps});var ms=te(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.Impersonated=un.IMPERSONATED_ACCOUNT_TYPE=void 0;var Gp=Br(),Xw=rt(),Zw=$t();un.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var fs=class t extends Gp.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Gp.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,Zw.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),a=o.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof Xw.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,a={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:a,method:"POST"})).data.token}};un.Impersonated=fs});var ys=te(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.OAuthClientAuthHandler=void 0;Kn.getErrorFromOAuthErrorResponse=tE;var dn=rt(),Qw=Un(),eE=["PUT","POST","PATCH"],gs=class{#e=(0,Qw.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new dn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new dn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=dn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=dn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=dn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",a=this.#e.encodeBase64StringUtf8(`${n}:${o}`);dn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${a}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!eE.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let a=new URLSearchParams(e.data??"");a.append("client_id",this.#t.clientId),a.append("client_secret",this.#t.clientSecret||""),e.data=a}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Kn.OAuthClientAuthHandler=gs;function tE(t,e){let r=t.error,n=t.error_description,o=t.error_uri,a=`Error code ${r}`;typeof n<"u"&&(a+=`: ${n}`),typeof o<"u"&&(a+=` - ${o}`);let i=new Error(a);if(e){let s=Object.keys(e);e.stack&&s.push("stack"),s.forEach(l=>{l!=="message"&&Object.defineProperty(i,l,{value:e[l],writable:!1,enumerable:!0})})}return i}});var ea=te(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.StsCredentials=void 0;var rE=rt(),nE=vt(),Bp=ys(),oE=$t(),vs=class t extends Bp.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},a={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,oE.removeUndefinedValuesInObject)(o))};nE.AuthClient.setMethodName(a,"exchangeToken"),this.applyClientAuthenticationOptions(a);try{let i=await this.transporter.request(a),s=i.data;return s.res=i,s}catch(i){throw i instanceof rE.GaxiosError&&i.response?(0,Bp.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};Qo.StsCredentials=vs});var Ar=te(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.BaseExternalAccountClient=Rt.CLOUD_RESOURCE_MANAGER=Rt.EXTERNAL_ACCOUNT_TYPE=Rt.EXPIRATION_TIME_OFFSET=void 0;var aE=rt(),iE=_e("stream"),bs=vt(),sE=ea(),Vp=$t(),lE=Pi(),cE="urn:ietf:params:oauth:grant-type:token-exchange",uE="urn:ietf:params:oauth:token-type:access_token",_s="https://www.googleapis.com/auth/cloud-platform",dE=3600;Rt.EXPIRATION_TIME_OFFSET=300*1e3;Rt.EXTERNAL_ACCOUNT_TYPE="external_account";Rt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var pE="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",hE="https://sts.{universeDomain}/v1/token",ws=class t extends bs.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,Vp.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Rt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Rt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),a=r.get("client_secret");this.tokenUrl=r.get("token_url")??hE.replace("{universeDomain}",this.universeDomain);let i=r.get("subject_token_type"),s=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),c=r.get("service_account_impersonation"),p=(0,Vp.originalOrCamelOptions)(c).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:a}),this.stsCredential=new sE.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[_s],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=s;let h=new RegExp(pE);if(this.workforcePoolUserProject&&!this.audience.match(h))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=p,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=dE),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};bs.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=aE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof iE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:cE,audience:this.audience,requestedTokenType:uE,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[_s]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),a=await this.stsCredential.exchangeToken(r,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(a.access_token):a.expires_in?this.cachedAccessToken={access_token:a.access_token,expiry_date:new Date().getTime()+a.expires_in*1e3,res:a.res}:this.cachedAccessToken={access_token:a.access_token,res:a.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};bs.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[_s]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${lE.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Rt.BaseExternalAccountClient=ws});var zp=te(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.FileSubjectTokenSupplier=void 0;var Ts=_e("util"),xs=_e("fs"),fE=(0,Ts.promisify)(xs.readFile??(()=>{})),mE=(0,Ts.promisify)(xs.realpath??(()=>{})),gE=(0,Ts.promisify)(xs.lstat??(()=>{})),Es=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await mE(e),!(await gE(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r,n=await fE(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};ta.FileSubjectTokenSupplier=Es});var Wp=te(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.UrlSubjectTokenSupplier=void 0;var yE=vt(),Ss=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};yE.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};ra.UrlSubjectTokenSupplier=Ss});var Jp=te(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.CertificateSubjectTokenSupplier=Et.InvalidConfigurationError=Et.CertificateSourceUnavailableError=Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var na=$t(),oa=_e("fs"),aa=_e("crypto"),vE=_e("https");Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Et.CertificateSourceUnavailableError=tr;var Ot=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Et.InvalidConfigurationError=Ot;var Cs=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new vE.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,na.isValidFile)(e))return e;throw new tr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,na.isValidFile)(r))return r;throw new tr(`Path from environment variable "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,na.getWellKnownCertificateConfigFileLocation)();if(await(0,na.isValidFile)(n))return n;throw new tr(`Could not find certificate configuration file. Searched override path, the "${Et.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await oa.promises.readFile(e,"utf8")}catch{throw new tr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,a=n?.cert_configs?.workload?.key_path;if(!o||!a)throw new Ot(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:a}}catch(n){throw n instanceof Ot?n:new Ot(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await oa.promises.readFile(e),new aa.X509Certificate(n)}catch(a){let i=a instanceof Error?a.message:String(a);throw new tr(`Failed to read certificate file at ${e}: ${i}`)}try{o=await oa.promises.readFile(r),(0,aa.createPrivateKey)(o)}catch(a){let i=a instanceof Error?a.message:String(a);throw new tr(`Failed to read private key file at ${r}: ${i}`)}return{cert:n,key:o}}async#n(e){let r=new aa.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let a=((await oa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,c)=>{try{return new aa.X509Certificate(l)}catch(p){let h=p instanceof Error?p.message:String(p);throw new Ot(`Failed to parse certificate at index ${c} in trust chain file ${this.trustChainPath}: ${h}`)}}),i=a.findIndex(l=>r.raw.equals(l.raw)),s;if(i===-1)s=[r,...a];else if(i===0)s=a;else throw new Ot(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(s.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof Ot)throw n;let o=n instanceof Error?n.message:String(n);throw new tr(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Et.CertificateSubjectTokenSupplier=Cs});var ks=te(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.IdentityPoolClient=void 0;var bE=Ar(),Is=$t(),_E=zp(),wE=Wp(),Kp=Jp(),EE=ea(),Yp=rt(),As=class t extends bE.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,Is.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let a=(0,Is.originalOrCamelOptions)(n),i=(0,Is.originalOrCamelOptions)(a.get("format")),s=i.get("type")||"text",l=i.get("subject_token_field_name");if(s!=="json"&&s!=="text")throw new Error(`Invalid credential_source format "${s}"`);if(s==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let c=a.get("file"),p=a.get("url"),h=a.get("certificate"),g=a.get("headers");if(c&&p||p&&h||c&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(c)this.credentialSourceType="file",this.subjectTokenSupplier=new _E.FileSubjectTokenSupplier({filePath:c,formatType:s,subjectTokenFieldName:l});else if(p)this.credentialSourceType="url",this.subjectTokenSupplier=new wE.UrlSubjectTokenSupplier({url:p,formatType:s,subjectTokenFieldName:l,headers:g,additionalGaxiosOptions:t.RETRY_CONFIG});else if(h){this.credentialSourceType="certificate";let y=new Kp.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=y}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Kp.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new EE.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Yp.Gaxios({agent:r})}),this.transporter=new Yp.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};ia.IdentityPoolClient=As});var Os=te(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.AwsRequestSigner=void 0;var sa=rt(),Zp=Un(),Xp="AWS4-HMAC-SHA256",TE="aws4_request",Rs=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Zp.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",a=e.body||r,i=e.headers,s=await this.getCredentials(),l=new URL(n);if(typeof a!="string"&&a!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let c=await SE({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:s,requestPayload:a,additionalAmzHeaders:i}),p=sa.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:l.host},i||{});s.token&&sa.Gaxios.mergeHeaders(p,{"x-amz-security-token":s.token});let h={url:n,method:o,headers:p};return a!==void 0&&(h.body=a),h}};la.AwsRequestSigner=Rs;async function Yn(t,e,r){return await t.signWithHmacSha256(e,r)}async function xE(t,e,r,n,o){let a=await Yn(t,`AWS4${e}`,r),i=await Yn(t,a,n),s=await Yn(t,i,o);return await Yn(t,s,"aws4_request")}async function SE(t){let e=sa.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],o=new Date,a=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),i=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let s=sa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":a},e),l="",c=[...s.keys()].sort();c.forEach(M=>{l+=`${M}:${s.get(M)}
|
|
18
|
+
`});let p=c.join(";"),h=await t.crypto.sha256DigestHex(r),g=`${t.method.toUpperCase()}
|
|
19
19
|
${t.canonicalUri}
|
|
20
20
|
${t.canonicalQuerystring}
|
|
21
21
|
${l}
|
|
22
22
|
${p}
|
|
23
|
-
${h}`,
|
|
23
|
+
${h}`,y=`${i}/${t.region}/${n}/${TE}`,S=`${Xp}
|
|
24
24
|
${a}
|
|
25
|
-
${
|
|
26
|
-
`+await t.crypto.sha256DigestHex(m),y=await xE(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,n),b=await Yn(t.crypto,y,T),_=`${Xp} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${p}, Signature=${(0,Zp.fromArrayBufferToHex)(b)}`;return{amzDate:e.has("date")?void 0:a,authorizationHeader:_,canonicalQuerystring:t.canonicalQuerystring}}});var Qp=ee(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.DefaultAwsSecurityCredentialsSupplier=void 0;var ca=vt(),Ns=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};ca.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ca.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return ca.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return ca.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};ua.DefaultAwsSecurityCredentialsSupplier=Ns});var Ps=ee(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.AwsClient=void 0;var CE=Os(),IE=Ar(),AE=Qp(),eh=Gt(),kE=rt(),Ms=class t extends IE.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,eh.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let a=(0,eh.originalOrCamelOptions)(n);this.environmentId=a.get("environment_id");let i=a.get("region_url"),s=a.get("url"),l=a.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new AE.DefaultAwsSecurityCredentialsSupplier({regionUrl:i,securityCredentialsUrl:s,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=a.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new CE.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return kE.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,a)=>r.push({key:a,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};da.AwsClient=Ms});var Fs=ee(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.InvalidSubjectTokenError=Je.InvalidMessageFieldError=Je.InvalidCodeFieldError=Je.InvalidTokenTypeFieldError=Je.InvalidExpirationTimeFieldError=Je.InvalidSuccessFieldError=Je.InvalidVersionFieldError=Je.ExecutableResponseError=Je.ExecutableResponse=void 0;var pa="urn:ietf:params:oauth:token-type:saml2",Ds="urn:ietf:params:oauth:token-type:id_token",js="urn:ietf:params:oauth:token-type:jwt",Ls=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ha("Executable response must contain a 'version' field.");if(e.success===void 0)throw new fa("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==pa&&this.tokenType!==Ds&&this.tokenType!==js)throw new ma(`Executable response must contain a 'token_type' field when successful and it must be one of ${Ds}, ${js}, or ${pa}.`);if(this.tokenType===pa){if(!e.saml_response)throw new Xn(`Executable response must contain a 'saml_response' field when token_type=${pa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Xn(`Executable response must contain a 'id_token' field when token_type=${Ds} or ${js}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ga("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ya("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Je.ExecutableResponse=Ls;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Je.ExecutableResponseError=rr;var ha=class extends rr{};Je.InvalidVersionFieldError=ha;var fa=class extends rr{};Je.InvalidSuccessFieldError=fa;var Us=class extends rr{};Je.InvalidExpirationTimeFieldError=Us;var ma=class extends rr{};Je.InvalidTokenTypeFieldError=ma;var ga=class extends rr{};Je.InvalidCodeFieldError=ga;var ya=class extends rr{};Je.InvalidMessageFieldError=ya;var Xn=class extends rr{};Je.InvalidSubjectTokenError=Xn});var Gs=ee(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.PluggableAuthHandler=pn.ExecutableError=void 0;var Vr=Fs(),RE=be("child_process"),Hs=be("fs"),va=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};pn.ExecutableError=va;var qs=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let o=RE.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",s=>{a+=s}),o.stderr.on("data",s=>{a+=s});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",s=>{if(clearTimeout(i),s===0)try{let l=JSON.parse(a),c=new Vr.ExecutableResponse(l);return r(c)}catch(l){return l instanceof Vr.ExecutableResponseError?n(l):n(new Vr.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}else return n(new va(a,s.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Hs.promises.realpath(this.outputFile)}catch{return}if(!(await Hs.promises.lstat(e)).isFile())return;let r=await Hs.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new Vr.ExecutableResponse(n).isValid()?new Vr.ExecutableResponse(n):void 0}catch(n){throw n instanceof Vr.ExecutableResponseError?n:new Vr.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};pn.PluggableAuthHandler=qs});var Bs=ee(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.PluggableAuthClient=hn.ExecutableError=void 0;var OE=Ar(),NE=Fs(),th=Gs(),ME=Gs();Object.defineProperty(hn,"ExecutableError",{enumerable:!0,get:function(){return ME.ExecutableError}});var PE=30*1e3,rh=5*1e3,nh=120*1e3,DE="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",oh=1,$s=class extends OE.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=PE;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<rh||this.timeoutMillis>nh)throw new Error(`Timeout must be between ${rh} and ${nh} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new th.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[DE]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>oh)throw new Error(`Version of executable is not currently supported, maximum supported version is ${oh}.`);if(!e.success)throw new th.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new NE.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};hn.PluggableAuthClient=$s});var zs=ee(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ExternalAccountClient=void 0;var jE=Ar(),LE=ks(),UE=Ps(),FE=Bs(),Vs=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===jE.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new UE.AwsClient(e):e.credential_source?.executable?new FE.PluggableAuthClient(e):new LE.IdentityPoolClient(e):null}};ba.ExternalAccountClient=Vs});var Ks=ee(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.ExternalAccountAuthorizedUserClient=fn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var ih=vt(),ah=ys(),sh=rt(),HE=be("stream"),qE=Ar();fn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var GE="https://sts.{universeDomain}/v1/oauthtoken",Ws=class t extends ah.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};ih.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),a=o.data;return a.res=o,a}catch(o){throw o instanceof sh.GaxiosError&&o.response?(0,ah.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Js=class extends ih.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ws({tokenRefreshEndpoint:e.token_url??GE.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=qE.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=sh.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof HE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};fn.ExternalAccountAuthorizedUserClient=Js});var dh=ee(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GoogleAuth=zt.GoogleAuthExceptionMessages=void 0;var $E=be("child_process"),Zn=be("fs"),BE=rt(),Qn=Un(),VE=be("os"),Ys=be("path"),zE=Fn(),WE=$i(),JE=Vi(),KE=zi(),mn=ds(),lh=hs(),gn=ms(),YE=zs(),eo=Ar(),Xs=vt(),ch=Ks(),uh=Gt();zt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
25
|
+
${y}
|
|
26
|
+
`+await t.crypto.sha256DigestHex(g),f=await xE(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,n),b=await Yn(t.crypto,f,S),_=`${Xp} Credential=${t.securityCredentials.accessKeyId}/${y}, SignedHeaders=${p}, Signature=${(0,Zp.fromArrayBufferToHex)(b)}`;return{amzDate:e.has("date")?void 0:a,authorizationHeader:_,canonicalQuerystring:t.canonicalQuerystring}}});var Qp=te(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.DefaultAwsSecurityCredentialsSupplier=void 0;var ca=vt(),Ns=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};ca.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ca.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return ca.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return ca.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};ua.DefaultAwsSecurityCredentialsSupplier=Ns});var Ps=te(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.AwsClient=void 0;var CE=Os(),IE=Ar(),AE=Qp(),eh=$t(),kE=rt(),Ms=class t extends IE.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,eh.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let a=(0,eh.originalOrCamelOptions)(n);this.environmentId=a.get("environment_id");let i=a.get("region_url"),s=a.get("url"),l=a.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new AE.DefaultAwsSecurityCredentialsSupplier({regionUrl:i,securityCredentialsUrl:s,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=a.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new CE.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return kE.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,a)=>r.push({key:a,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};da.AwsClient=Ms});var Us=te(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.InvalidSubjectTokenError=Je.InvalidMessageFieldError=Je.InvalidCodeFieldError=Je.InvalidTokenTypeFieldError=Je.InvalidExpirationTimeFieldError=Je.InvalidSuccessFieldError=Je.InvalidVersionFieldError=Je.ExecutableResponseError=Je.ExecutableResponse=void 0;var pa="urn:ietf:params:oauth:token-type:saml2",Ds="urn:ietf:params:oauth:token-type:id_token",js="urn:ietf:params:oauth:token-type:jwt",Ls=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ha("Executable response must contain a 'version' field.");if(e.success===void 0)throw new fa("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==pa&&this.tokenType!==Ds&&this.tokenType!==js)throw new ma(`Executable response must contain a 'token_type' field when successful and it must be one of ${Ds}, ${js}, or ${pa}.`);if(this.tokenType===pa){if(!e.saml_response)throw new Xn(`Executable response must contain a 'saml_response' field when token_type=${pa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Xn(`Executable response must contain a 'id_token' field when token_type=${Ds} or ${js}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ga("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ya("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Je.ExecutableResponse=Ls;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Je.ExecutableResponseError=rr;var ha=class extends rr{};Je.InvalidVersionFieldError=ha;var fa=class extends rr{};Je.InvalidSuccessFieldError=fa;var Fs=class extends rr{};Je.InvalidExpirationTimeFieldError=Fs;var ma=class extends rr{};Je.InvalidTokenTypeFieldError=ma;var ga=class extends rr{};Je.InvalidCodeFieldError=ga;var ya=class extends rr{};Je.InvalidMessageFieldError=ya;var Xn=class extends rr{};Je.InvalidSubjectTokenError=Xn});var $s=te(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.PluggableAuthHandler=pn.ExecutableError=void 0;var Vr=Us(),RE=_e("child_process"),Hs=_e("fs"),va=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};pn.ExecutableError=va;var qs=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let o=RE.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",s=>{a+=s}),o.stderr.on("data",s=>{a+=s});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",s=>{if(clearTimeout(i),s===0)try{let l=JSON.parse(a),c=new Vr.ExecutableResponse(l);return r(c)}catch(l){return l instanceof Vr.ExecutableResponseError?n(l):n(new Vr.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}else return n(new va(a,s.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Hs.promises.realpath(this.outputFile)}catch{return}if(!(await Hs.promises.lstat(e)).isFile())return;let r=await Hs.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new Vr.ExecutableResponse(n).isValid()?new Vr.ExecutableResponse(n):void 0}catch(n){throw n instanceof Vr.ExecutableResponseError?n:new Vr.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};pn.PluggableAuthHandler=qs});var Bs=te(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.PluggableAuthClient=hn.ExecutableError=void 0;var OE=Ar(),NE=Us(),th=$s(),ME=$s();Object.defineProperty(hn,"ExecutableError",{enumerable:!0,get:function(){return ME.ExecutableError}});var PE=30*1e3,rh=5*1e3,nh=120*1e3,DE="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",oh=1,Gs=class extends OE.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=PE;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<rh||this.timeoutMillis>nh)throw new Error(`Timeout must be between ${rh} and ${nh} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new th.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[DE]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>oh)throw new Error(`Version of executable is not currently supported, maximum supported version is ${oh}.`);if(!e.success)throw new th.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new NE.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};hn.PluggableAuthClient=Gs});var zs=te(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ExternalAccountClient=void 0;var jE=Ar(),LE=ks(),FE=Ps(),UE=Bs(),Vs=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===jE.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new FE.AwsClient(e):e.credential_source?.executable?new UE.PluggableAuthClient(e):new LE.IdentityPoolClient(e):null}};ba.ExternalAccountClient=Vs});var Ks=te(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.ExternalAccountAuthorizedUserClient=fn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var ih=vt(),ah=ys(),sh=rt(),HE=_e("stream"),qE=Ar();fn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var $E="https://sts.{universeDomain}/v1/oauthtoken",Ws=class t extends ah.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};ih.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),a=o.data;return a.res=o,a}catch(o){throw o instanceof sh.GaxiosError&&o.response?(0,ah.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Js=class extends ih.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ws({tokenRefreshEndpoint:e.token_url??$E.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=qE.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=sh.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof HE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};fn.ExternalAccountAuthorizedUserClient=Js});var dh=te(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GoogleAuth=zt.GoogleAuthExceptionMessages=void 0;var GE=_e("child_process"),Zn=_e("fs"),BE=rt(),Qn=Fn(),VE=_e("os"),Ys=_e("path"),zE=Un(),WE=Gi(),JE=Vi(),KE=zi(),mn=ds(),lh=hs(),gn=ms(),YE=zs(),eo=Ar(),Xs=vt(),ch=Ks(),uh=$t();zt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
27
27
|
To learn more about authentication and Google APIs, visit:
|
|
28
28
|
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
29
29
|
To learn more about authentication and Google APIs, visit:
|
|
30
30
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
31
31
|
To learn more about Universe Domain retrieval, visit:
|
|
32
|
-
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Zs=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(zt.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===zt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(zt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Qn.universe("universe-domain"),e||=Xs.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Xs.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,uh.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Xs.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(o=>r(null,o.credential,o.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof mn.JWT?r.scopes=this.scopes:r instanceof eo.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof mn.JWT?r.scopes=this.scopes:r instanceof eo.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new WE.Compute(e));throw new Error(zt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Qn.getGCPResidency()||await Qn.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let o=process.env.HOME;o&&(r=Ys.join(o,".config"))}return r&&(r=Ys.join(r,"gcloud","application_default_credentials.json"),Zn.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Zn.realpathSync(e),!Zn.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=Zn.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==gn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${gn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new gn.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,r={}){let n,o=(0,uh.originalOrCamelOptions)(r).get("universe_domain");return e.type===lh.USER_REFRESH_ACCOUNT_TYPE?(n=new lh.UserRefreshClient(r),n.fromJSON(e)):e.type===gn.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===eo.EXTERNAL_ACCOUNT_TYPE?(n=YE.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===ch.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new ch.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new mn.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){let o={};if(typeof r=="function"?n=r:o=r,n)this.fromStreamAsync(e,o).then(a=>n(null,a),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,r){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let a=[];e.setEncoding("utf8").on("error",o).on("data",i=>a.push(i)).on("end",()=>{try{try{let i=JSON.parse(a.join("")),s=this._cacheClientFromJSON(i,r);return n(s)}catch(i){if(!this.keyFilename)throw i;let s=new mn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=s,this.setGapicJWTValues(s),n(s)}}catch(i){return o(i)}})})}fromAPIKey(e,r={}){return new mn.JWT({...r,apiKey:e})}_isWindows(){let e=VE.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,$E.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==eo.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Qn.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof gn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof eo.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[r,n]=await Promise.all([Qn.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(zt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Ys.resolve(this.keyFilename),r=Zn.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))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 JE.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,o=await(await this.getClient()).getRequestHeaders(r);return e.headers=BE.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,KE.getEnv)()}async sign(e,r){let n=await this.getClient(),o=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof gn.Impersonated)return(await n.sign(e)).signedBlob;let a=(0,zE.createCrypto)();if(n instanceof mn.JWT&&n.key)return await a.sign(n.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(a,i.client_email,e,r)}async signBlob(e,r,n,o){let a=new URL(o+`${r}:signBlob`);return(await this.request({method:"POST",url:a.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};zt.GoogleAuth=Zs});var ph=ee(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.IAMAuth=void 0;var Qs=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};_a.IAMAuth=Qs});var hh=ee(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var XE=rt(),ZE=be("stream"),el=vt(),QE=ea(),eT="urn:ietf:params:oauth:grant-type:token-exchange",tT="urn:ietf:params:oauth:token-type:access_token",rT="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var tl=class extends el.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof el.AuthClient?{}:e),e instanceof el.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>nr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${nr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new QE.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=XE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof ZE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:eT,requestedTokenType:tT,subjectToken:e,subjectTokenType:rT},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,a=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:a,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};nr.DownscopedClient=tl});var fh=ee(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.PassThroughClient=void 0;var nT=vt(),rl=class extends nT.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};wa.PassThroughClient=rl});var bh=ee(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GoogleAuth=le.auth=le.PassThroughClient=le.ExternalAccountAuthorizedUserClient=le.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=le.ExecutableError=le.PluggableAuthClient=le.DownscopedClient=le.BaseExternalAccountClient=le.ExternalAccountClient=le.IdentityPoolClient=le.AwsRequestSigner=le.AwsClient=le.UserRefreshClient=le.LoginTicket=le.ClientAuthentication=le.OAuth2Client=le.CodeChallengeMethod=le.Impersonated=le.JWT=le.JWTAccess=le.IdTokenClient=le.IAMAuth=le.GCPEnv=le.Compute=le.DEFAULT_UNIVERSE=le.AuthClient=le.gaxios=le.gcpMetadata=void 0;var mh=dh();Object.defineProperty(le,"GoogleAuth",{enumerable:!0,get:function(){return mh.GoogleAuth}});le.gcpMetadata=Un();le.gaxios=rt();var gh=vt();Object.defineProperty(le,"AuthClient",{enumerable:!0,get:function(){return gh.AuthClient}});Object.defineProperty(le,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return gh.DEFAULT_UNIVERSE}});var oT=$i();Object.defineProperty(le,"Compute",{enumerable:!0,get:function(){return oT.Compute}});var aT=zi();Object.defineProperty(le,"GCPEnv",{enumerable:!0,get:function(){return aT.GCPEnv}});var iT=ph();Object.defineProperty(le,"IAMAuth",{enumerable:!0,get:function(){return iT.IAMAuth}});var sT=Vi();Object.defineProperty(le,"IdTokenClient",{enumerable:!0,get:function(){return sT.IdTokenClient}});var lT=cs();Object.defineProperty(le,"JWTAccess",{enumerable:!0,get:function(){return lT.JWTAccess}});var cT=ds();Object.defineProperty(le,"JWT",{enumerable:!0,get:function(){return cT.JWT}});var uT=ms();Object.defineProperty(le,"Impersonated",{enumerable:!0,get:function(){return uT.Impersonated}});var nl=Br();Object.defineProperty(le,"CodeChallengeMethod",{enumerable:!0,get:function(){return nl.CodeChallengeMethod}});Object.defineProperty(le,"OAuth2Client",{enumerable:!0,get:function(){return nl.OAuth2Client}});Object.defineProperty(le,"ClientAuthentication",{enumerable:!0,get:function(){return nl.ClientAuthentication}});var dT=Fi();Object.defineProperty(le,"LoginTicket",{enumerable:!0,get:function(){return dT.LoginTicket}});var pT=hs();Object.defineProperty(le,"UserRefreshClient",{enumerable:!0,get:function(){return pT.UserRefreshClient}});var hT=Ps();Object.defineProperty(le,"AwsClient",{enumerable:!0,get:function(){return hT.AwsClient}});var fT=Os();Object.defineProperty(le,"AwsRequestSigner",{enumerable:!0,get:function(){return fT.AwsRequestSigner}});var mT=ks();Object.defineProperty(le,"IdentityPoolClient",{enumerable:!0,get:function(){return mT.IdentityPoolClient}});var gT=zs();Object.defineProperty(le,"ExternalAccountClient",{enumerable:!0,get:function(){return gT.ExternalAccountClient}});var yT=Ar();Object.defineProperty(le,"BaseExternalAccountClient",{enumerable:!0,get:function(){return yT.BaseExternalAccountClient}});var vT=hh();Object.defineProperty(le,"DownscopedClient",{enumerable:!0,get:function(){return vT.DownscopedClient}});var yh=Bs();Object.defineProperty(le,"PluggableAuthClient",{enumerable:!0,get:function(){return yh.PluggableAuthClient}});Object.defineProperty(le,"ExecutableError",{enumerable:!0,get:function(){return yh.ExecutableError}});var vh=Ks();Object.defineProperty(le,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return vh.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(le,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return vh.ExternalAccountAuthorizedUserClient}});var bT=fh();Object.defineProperty(le,"PassThroughClient",{enumerable:!0,get:function(){return bT.PassThroughClient}});var _T=new mh.GoogleAuth;le.auth=_T});var pl=ee((_O,Zh)=>{"use strict";var dl=Object.defineProperty,t0=Object.getOwnPropertyDescriptor,r0=Object.getOwnPropertyNames,n0=Object.prototype.hasOwnProperty,o0=(t,e)=>{for(var r in e)dl(t,r,{get:e[r],enumerable:!0})},a0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of r0(e))!n0.call(t,o)&&o!==r&&dl(t,o,{get:()=>e[o],enumerable:!(n=t0(e,o))||n.enumerable});return t},i0=t=>a0(dl({},"__esModule",{value:!0}),t),Yh={};o0(Yh,{SYMBOL_FOR_REQ_CONTEXT:()=>Xh,getContext:()=>s0});Zh.exports=i0(Yh);var Xh=Symbol.for("@vercel/request-context");function s0(){return globalThis[Xh]?.get?.()??{}}});var tf=ee((wO,ef)=>{"use strict";var fl=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,c0=Object.getOwnPropertyNames,u0=Object.prototype.hasOwnProperty,d0=(t,e)=>{for(var r in e)fl(t,r,{get:e[r],enumerable:!0})},p0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of c0(e))!u0.call(t,o)&&o!==r&&fl(t,o,{get:()=>e[o],enumerable:!(n=l0(e,o))||n.enumerable});return t},h0=t=>p0(fl({},"__esModule",{value:!0}),t),Qh={};d0(Qh,{getVercelOidcToken:()=>g0,getVercelOidcTokenSync:()=>hl});ef.exports=h0(Qh);var f0=pl(),m0=lg();async function g0(){let t="",e;try{t=hl()}catch(r){e=r}try{let[{getTokenPayload:r,isExpired:n},{refreshToken:o}]=await Promise.all([await import("./token-util-7HVAYCG2.js"),await import("./token-HZZUEE35.js")]);(!t||n(r(t)))&&(await o(),t=hl())}catch(r){let n=e instanceof Error?e.message:"";throw r instanceof Error&&(n=`${n}
|
|
33
|
-
${r.message}`),n?new m0.VercelOidcTokenError(n):r}return t}function hl(){let t=(0,f0.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!t)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return t}});var gl=
|
|
34
|
-
Error message: ${Tr(e)}`,cause:e}),this[Ql]=!0,this.text=t}static isInstance(t){return oe.hasMarker(t,kc)}},Rc="AI_LoadAPIKeyError",Oc=`vercel.ai.error.${Rc}`,yg=Symbol.for(Oc),tc,rc,In=class extends(rc=oe,tc=yg,rc){constructor({message:t}){super({name:Rc,message:t}),this[tc]=!0}static isInstance(t){return oe.hasMarker(t,Oc)}},Nc="AI_LoadSettingError",Mc=`vercel.ai.error.${Nc}`,vg=Symbol.for(Mc),nc,oc,An=class extends(oc=oe,nc=vg,oc){constructor({message:t}){super({name:Nc,message:t}),this[nc]=!0}static isInstance(t){return oe.hasMarker(t,Mc)}},Pc="AI_NoContentGeneratedError",Dc=`vercel.ai.error.${Pc}`,bg=Symbol.for(Dc),ac,ic,CC=class extends(ic=oe,ac=bg,ic){constructor({message:t="No content generated."}={}){super({name:Pc,message:t}),this[ac]=!0}static isInstance(t){return oe.hasMarker(t,Dc)}},jc="AI_NoSuchModelError",Lc=`vercel.ai.error.${jc}`,_g=Symbol.for(Lc),sc,lc,Ha=class extends(lc=oe,sc=_g,lc){constructor({errorName:t=jc,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[sc]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return oe.hasMarker(t,Lc)}},
|
|
35
|
-
Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e){return oe.hasMarker(e,qc)}static wrap({value:e,cause:r}){return
|
|
36
|
-
`;break;case"id":s=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?n(parseInt(b,10)):r(new mo(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:_}));break;default:r(new mo(`Unknown field "${
|
|
37
|
-
`)?l.slice(0,-1):l}),s=void 0,l="",c=""}function
|
|
32
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Zs=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(zt.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===zt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(zt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Qn.universe("universe-domain"),e||=Xs.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Xs.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,uh.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Xs.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(o=>r(null,o.credential,o.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof mn.JWT?r.scopes=this.scopes:r instanceof eo.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof mn.JWT?r.scopes=this.scopes:r instanceof eo.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new WE.Compute(e));throw new Error(zt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Qn.getGCPResidency()||await Qn.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let o=process.env.HOME;o&&(r=Ys.join(o,".config"))}return r&&(r=Ys.join(r,"gcloud","application_default_credentials.json"),Zn.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Zn.realpathSync(e),!Zn.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=Zn.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==gn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${gn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new gn.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,r={}){let n,o=(0,uh.originalOrCamelOptions)(r).get("universe_domain");return e.type===lh.USER_REFRESH_ACCOUNT_TYPE?(n=new lh.UserRefreshClient(r),n.fromJSON(e)):e.type===gn.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===eo.EXTERNAL_ACCOUNT_TYPE?(n=YE.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===ch.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new ch.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new mn.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){let o={};if(typeof r=="function"?n=r:o=r,n)this.fromStreamAsync(e,o).then(a=>n(null,a),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,r){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let a=[];e.setEncoding("utf8").on("error",o).on("data",i=>a.push(i)).on("end",()=>{try{try{let i=JSON.parse(a.join("")),s=this._cacheClientFromJSON(i,r);return n(s)}catch(i){if(!this.keyFilename)throw i;let s=new mn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=s,this.setGapicJWTValues(s),n(s)}}catch(i){return o(i)}})})}fromAPIKey(e,r={}){return new mn.JWT({...r,apiKey:e})}_isWindows(){let e=VE.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,GE.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==eo.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Qn.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof gn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof eo.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[r,n]=await Promise.all([Qn.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(zt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Ys.resolve(this.keyFilename),r=Zn.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))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 JE.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,o=await(await this.getClient()).getRequestHeaders(r);return e.headers=BE.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,KE.getEnv)()}async sign(e,r){let n=await this.getClient(),o=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof gn.Impersonated)return(await n.sign(e)).signedBlob;let a=(0,zE.createCrypto)();if(n instanceof mn.JWT&&n.key)return await a.sign(n.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(a,i.client_email,e,r)}async signBlob(e,r,n,o){let a=new URL(o+`${r}:signBlob`);return(await this.request({method:"POST",url:a.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};zt.GoogleAuth=Zs});var ph=te(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.IAMAuth=void 0;var Qs=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};_a.IAMAuth=Qs});var hh=te(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var XE=rt(),ZE=_e("stream"),el=vt(),QE=ea(),eT="urn:ietf:params:oauth:grant-type:token-exchange",tT="urn:ietf:params:oauth:token-type:access_token",rT="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var tl=class extends el.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof el.AuthClient?{}:e),e instanceof el.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>nr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${nr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new QE.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=XE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let i=a.status,s=a.config.data instanceof ZE.Readable;if(!r&&(i===401||i===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:eT,requestedTokenType:tT,subjectToken:e,subjectTokenType:rT},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,a=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:a,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};nr.DownscopedClient=tl});var fh=te(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.PassThroughClient=void 0;var nT=vt(),rl=class extends nT.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};wa.PassThroughClient=rl});var bh=te(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GoogleAuth=le.auth=le.PassThroughClient=le.ExternalAccountAuthorizedUserClient=le.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=le.ExecutableError=le.PluggableAuthClient=le.DownscopedClient=le.BaseExternalAccountClient=le.ExternalAccountClient=le.IdentityPoolClient=le.AwsRequestSigner=le.AwsClient=le.UserRefreshClient=le.LoginTicket=le.ClientAuthentication=le.OAuth2Client=le.CodeChallengeMethod=le.Impersonated=le.JWT=le.JWTAccess=le.IdTokenClient=le.IAMAuth=le.GCPEnv=le.Compute=le.DEFAULT_UNIVERSE=le.AuthClient=le.gaxios=le.gcpMetadata=void 0;var mh=dh();Object.defineProperty(le,"GoogleAuth",{enumerable:!0,get:function(){return mh.GoogleAuth}});le.gcpMetadata=Fn();le.gaxios=rt();var gh=vt();Object.defineProperty(le,"AuthClient",{enumerable:!0,get:function(){return gh.AuthClient}});Object.defineProperty(le,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return gh.DEFAULT_UNIVERSE}});var oT=Gi();Object.defineProperty(le,"Compute",{enumerable:!0,get:function(){return oT.Compute}});var aT=zi();Object.defineProperty(le,"GCPEnv",{enumerable:!0,get:function(){return aT.GCPEnv}});var iT=ph();Object.defineProperty(le,"IAMAuth",{enumerable:!0,get:function(){return iT.IAMAuth}});var sT=Vi();Object.defineProperty(le,"IdTokenClient",{enumerable:!0,get:function(){return sT.IdTokenClient}});var lT=cs();Object.defineProperty(le,"JWTAccess",{enumerable:!0,get:function(){return lT.JWTAccess}});var cT=ds();Object.defineProperty(le,"JWT",{enumerable:!0,get:function(){return cT.JWT}});var uT=ms();Object.defineProperty(le,"Impersonated",{enumerable:!0,get:function(){return uT.Impersonated}});var nl=Br();Object.defineProperty(le,"CodeChallengeMethod",{enumerable:!0,get:function(){return nl.CodeChallengeMethod}});Object.defineProperty(le,"OAuth2Client",{enumerable:!0,get:function(){return nl.OAuth2Client}});Object.defineProperty(le,"ClientAuthentication",{enumerable:!0,get:function(){return nl.ClientAuthentication}});var dT=Ui();Object.defineProperty(le,"LoginTicket",{enumerable:!0,get:function(){return dT.LoginTicket}});var pT=hs();Object.defineProperty(le,"UserRefreshClient",{enumerable:!0,get:function(){return pT.UserRefreshClient}});var hT=Ps();Object.defineProperty(le,"AwsClient",{enumerable:!0,get:function(){return hT.AwsClient}});var fT=Os();Object.defineProperty(le,"AwsRequestSigner",{enumerable:!0,get:function(){return fT.AwsRequestSigner}});var mT=ks();Object.defineProperty(le,"IdentityPoolClient",{enumerable:!0,get:function(){return mT.IdentityPoolClient}});var gT=zs();Object.defineProperty(le,"ExternalAccountClient",{enumerable:!0,get:function(){return gT.ExternalAccountClient}});var yT=Ar();Object.defineProperty(le,"BaseExternalAccountClient",{enumerable:!0,get:function(){return yT.BaseExternalAccountClient}});var vT=hh();Object.defineProperty(le,"DownscopedClient",{enumerable:!0,get:function(){return vT.DownscopedClient}});var yh=Bs();Object.defineProperty(le,"PluggableAuthClient",{enumerable:!0,get:function(){return yh.PluggableAuthClient}});Object.defineProperty(le,"ExecutableError",{enumerable:!0,get:function(){return yh.ExecutableError}});var vh=Ks();Object.defineProperty(le,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return vh.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(le,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return vh.ExternalAccountAuthorizedUserClient}});var bT=fh();Object.defineProperty(le,"PassThroughClient",{enumerable:!0,get:function(){return bT.PassThroughClient}});var _T=new mh.GoogleAuth;le.auth=_T});var pl=te((_O,Zh)=>{"use strict";var dl=Object.defineProperty,t0=Object.getOwnPropertyDescriptor,r0=Object.getOwnPropertyNames,n0=Object.prototype.hasOwnProperty,o0=(t,e)=>{for(var r in e)dl(t,r,{get:e[r],enumerable:!0})},a0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of r0(e))!n0.call(t,o)&&o!==r&&dl(t,o,{get:()=>e[o],enumerable:!(n=t0(e,o))||n.enumerable});return t},i0=t=>a0(dl({},"__esModule",{value:!0}),t),Yh={};o0(Yh,{SYMBOL_FOR_REQ_CONTEXT:()=>Xh,getContext:()=>s0});Zh.exports=i0(Yh);var Xh=Symbol.for("@vercel/request-context");function s0(){return globalThis[Xh]?.get?.()??{}}});var tf=te((wO,ef)=>{"use strict";var fl=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,c0=Object.getOwnPropertyNames,u0=Object.prototype.hasOwnProperty,d0=(t,e)=>{for(var r in e)fl(t,r,{get:e[r],enumerable:!0})},p0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of c0(e))!u0.call(t,o)&&o!==r&&fl(t,o,{get:()=>e[o],enumerable:!(n=l0(e,o))||n.enumerable});return t},h0=t=>p0(fl({},"__esModule",{value:!0}),t),Qh={};d0(Qh,{getVercelOidcToken:()=>g0,getVercelOidcTokenSync:()=>hl});ef.exports=h0(Qh);var f0=pl(),m0=lg();async function g0(){let t="",e;try{t=hl()}catch(r){e=r}try{let[{getTokenPayload:r,isExpired:n},{refreshToken:o}]=await Promise.all([await import("./token-util-7HVAYCG2.js"),await import("./token-HZZUEE35.js")]);(!t||n(r(t)))&&(await o(),t=hl())}catch(r){let n=e instanceof Error?e.message:"";throw r instanceof Error&&(n=`${n}
|
|
33
|
+
${r.message}`),n?new m0.VercelOidcTokenError(n):r}return t}function hl(){let t=(0,f0.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!t)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return t}});var gl=te((EO,of)=>{"use strict";var ml=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,v0=Object.getOwnPropertyNames,b0=Object.prototype.hasOwnProperty,_0=(t,e)=>{for(var r in e)ml(t,r,{get:e[r],enumerable:!0})},w0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of v0(e))!b0.call(t,o)&&o!==r&&ml(t,o,{get:()=>e[o],enumerable:!(n=y0(e,o))||n.enumerable});return t},E0=t=>w0(ml({},"__esModule",{value:!0}),t),nf={};_0(nf,{getContext:()=>T0.getContext,getVercelOidcToken:()=>rf.getVercelOidcToken,getVercelOidcTokenSync:()=>rf.getVercelOidcTokenSync});of.exports=E0(nf);var rf=tf(),T0=pl()});import{z as Mt}from"zod";var cg=class{constructor(){this.tools=new Map}register(t){if(this.tools.has(t.name))throw new Error(`Tool '${t.name}' is already registered`);let e={name:t.name,description:t.description,schema:t.schema,execute:t.execute,usesElementIndex:t.usesElementIndex??!1,availability:{openai:t.availability?.openai??!0,mcp:t.availability?.mcp??!0}};this.tools.set(t.name,e)}get(t){return this.tools.get(t)}has(t){return this.tools.has(t)}getToolNames(){return Array.from(this.tools.keys())}getTools(){return Array.from(this.tools.values())}async execute(t,e,r){let n=this.tools.get(t);if(!n)throw new Error(`Tool not found: ${t}`);try{let o=e?.description,a={...e};delete a.description;let i=n.schema.parse(a),s={...r,actionDescription:o};return await n.execute(i,s)}catch(o){if(o instanceof Mt.ZodError){let a=o.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ");return{success:!1,error:`Invalid arguments for tool '${t}': ${a}`,actionEntity:{action_description:e?.description||`${t} (validation failed)`,action_data:{action_name:t,kwargs:e},feedback:`Validation error: ${a}`}}}throw o}}clear(){this.tools.clear()}size(){return this.tools.size}buildActionUnionSchema(){let t=this.getTools().filter(e=>e.availability.openai);return this.buildUnionSchemaFromTools(t)}buildActionUnionSchemaForTools(t,e=!1){let r=new Set(t),n=this.getTools().filter(o=>r.has(o.name));return this.buildUnionSchemaFromTools(n,e)}buildUnionSchemaFromTools(t,e=!1){if(t.length===0)return Mt.object({done:Mt.any()});let r=t.map(i=>{let s=i.schema;if(e&&s instanceof Mt.ZodObject){let l=s._def.shape();s=Mt.object({...l,description:Mt.string().describe("Semantic, human-readable description of the action")})}if(s instanceof Mt.ZodObject){let l=s._def.shape();Object.keys(l).length===0&&(s=Mt.object({_empty:Mt.boolean().optional()}))}return Mt.object({[i.name]:s})});if(r.length===1)return r[0];let[n,o,...a]=r;return Mt.union([n,o,...a])}},EC=new cg;var mc="vercel.ai.error",ug=Symbol.for(mc),ql,$l,oe=class gc extends($l=Error,ql=ug,$l){constructor({name:e,message:r,cause:n}){super(r),this[ql]=!0,this.name=e,this.cause=n}static isInstance(e){return gc.hasMarker(e,mc)}static hasMarker(e,r){let n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},yc="AI_APICallError",vc=`vercel.ai.error.${yc}`,dg=Symbol.for(vc),Gl,Bl,$e=class extends(Bl=oe,Gl=dg,Bl){constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:a,cause:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:yc,message:t,cause:i}),this[Gl]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=a,this.isRetryable=s,this.data=l}static isInstance(t){return oe.hasMarker(t,vc)}},bc="AI_EmptyResponseBodyError",_c=`vercel.ai.error.${bc}`,pg=Symbol.for(_c),Vl,zl,wc=class extends(zl=oe,Vl=pg,zl){constructor({message:t="Empty response body"}={}){super({name:bc,message:t}),this[Vl]=!0}static isInstance(t){return oe.hasMarker(t,_c)}};function Tr(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Ec="AI_InvalidArgumentError",Tc=`vercel.ai.error.${Ec}`,hg=Symbol.for(Tc),Wl,Jl,ho=class extends(Jl=oe,Wl=hg,Jl){constructor({message:t,cause:e,argument:r}){super({name:Ec,message:t,cause:e}),this[Wl]=!0,this.argument=r}static isInstance(t){return oe.hasMarker(t,Tc)}},xc="AI_InvalidPromptError",Sc=`vercel.ai.error.${xc}`,fg=Symbol.for(Sc),Kl,Yl,Dr=class extends(Yl=oe,Kl=fg,Yl){constructor({prompt:t,message:e,cause:r}){super({name:xc,message:`Invalid prompt: ${e}`,cause:r}),this[Kl]=!0,this.prompt=t}static isInstance(t){return oe.hasMarker(t,Sc)}},Cc="AI_InvalidResponseDataError",Ic=`vercel.ai.error.${Cc}`,mg=Symbol.for(Ic),Xl,Zl,SC=class extends(Zl=oe,Xl=mg,Zl){constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Cc,message:e}),this[Xl]=!0,this.data=t}static isInstance(t){return oe.hasMarker(t,Ic)}},Ac="AI_JSONParseError",kc=`vercel.ai.error.${Ac}`,gg=Symbol.for(kc),Ql,ec,Cn=class extends(ec=oe,Ql=gg,ec){constructor({text:t,cause:e}){super({name:Ac,message:`JSON parsing failed: Text: ${t}.
|
|
34
|
+
Error message: ${Tr(e)}`,cause:e}),this[Ql]=!0,this.text=t}static isInstance(t){return oe.hasMarker(t,kc)}},Rc="AI_LoadAPIKeyError",Oc=`vercel.ai.error.${Rc}`,yg=Symbol.for(Oc),tc,rc,In=class extends(rc=oe,tc=yg,rc){constructor({message:t}){super({name:Rc,message:t}),this[tc]=!0}static isInstance(t){return oe.hasMarker(t,Oc)}},Nc="AI_LoadSettingError",Mc=`vercel.ai.error.${Nc}`,vg=Symbol.for(Mc),nc,oc,An=class extends(oc=oe,nc=vg,oc){constructor({message:t}){super({name:Nc,message:t}),this[nc]=!0}static isInstance(t){return oe.hasMarker(t,Mc)}},Pc="AI_NoContentGeneratedError",Dc=`vercel.ai.error.${Pc}`,bg=Symbol.for(Dc),ac,ic,CC=class extends(ic=oe,ac=bg,ic){constructor({message:t="No content generated."}={}){super({name:Pc,message:t}),this[ac]=!0}static isInstance(t){return oe.hasMarker(t,Dc)}},jc="AI_NoSuchModelError",Lc=`vercel.ai.error.${jc}`,_g=Symbol.for(Lc),sc,lc,Ha=class extends(lc=oe,sc=_g,lc){constructor({errorName:t=jc,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[sc]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return oe.hasMarker(t,Lc)}},Fc="AI_TooManyEmbeddingValuesForCallError",Uc=`vercel.ai.error.${Fc}`,wg=Symbol.for(Uc),cc,uc,fo=class extends(uc=oe,cc=wg,uc){constructor(t){super({name:Fc,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[cc]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return oe.hasMarker(t,Uc)}},Hc="AI_TypeValidationError",qc=`vercel.ai.error.${Hc}`,Eg=Symbol.for(qc),dc,pc,Pt=class Ua extends(pc=oe,dc=Eg,pc){constructor({value:e,cause:r}){super({name:Hc,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
35
|
+
Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e){return oe.hasMarker(e,qc)}static wrap({value:e,cause:r}){return Ua.isInstance(r)&&r.value===e?r:new Ua({value:e,cause:r})}},$c="AI_UnsupportedFunctionalityError",Gc=`vercel.ai.error.${$c}`,Tg=Symbol.for(Gc),hc,fc,tt=class extends(fc=oe,hc=Tg,fc){constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:$c,message:e}),this[hc]=!0,this.functionality=t}static isInstance(t){return oe.hasMarker(t,Gc)}};import*as Eo from"zod/v4";import{ZodFirstPartyTypeKind as ke}from"zod/v3";import{ZodFirstPartyTypeKind as jg}from"zod/v3";import{ZodFirstPartyTypeKind as yo}from"zod/v3";var mo=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function qa(t){}function Bc(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=qa,onError:r=qa,onRetry:n=qa,onComment:o}=t,a="",i=!0,s,l="",c="";function p(f){let b=i?f.replace(/^\xEF\xBB\xBF/,""):f,[_,M]=xg(`${a}${b}`);for(let B of _)h(B);a=M,i=!1}function h(f){if(f===""){y();return}if(f.startsWith(":")){o&&o(f.slice(f.startsWith(": ")?2:1));return}let b=f.indexOf(":");if(b!==-1){let _=f.slice(0,b),M=f[b+1]===" "?2:1,B=f.slice(b+M);g(_,B,f);return}g(f,"",f)}function g(f,b,_){switch(f){case"event":c=b;break;case"data":l=`${l}${b}
|
|
36
|
+
`;break;case"id":s=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?n(parseInt(b,10)):r(new mo(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:_}));break;default:r(new mo(`Unknown field "${f.length>20?`${f.slice(0,20)}\u2026`:f}"`,{type:"unknown-field",field:f,value:b,line:_}));break}}function y(){l.length>0&&e({id:s,event:c||void 0,data:l.endsWith(`
|
|
37
|
+
`)?l.slice(0,-1):l}),s=void 0,l="",c=""}function S(f={}){a&&f.consume&&h(a),i=!0,s=void 0,l="",c="",a=""}return{feed:p,reset:S}}function xg(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),a=t.indexOf(`
|
|
38
38
|
`,n),i=-1;if(o!==-1&&a!==-1?i=Math.min(o,a):o!==-1?o===t.length-1?i=-1:i=o:a!==-1&&(i=a),i===-1){r=t.slice(n);break}else{let s=t.slice(n,i);e.push(s),n=i+1,t[n-1]==="\r"&&t[n]===`
|
|
39
|
-
`&&n++}}return[e,r]}var go=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(a){o=Bc({onEvent:i=>{a.enqueue(i)},onError(i){e==="terminate"?a.error(i):typeof e=="function"&&e(i)},onRetry:r,onComment:n})},transform(a){o.feed(a)}})}};function $e(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function Xc({tools:t=[],providerToolNames:e}){let r={},n={};for(let o of t)if(o.type==="provider"&&o.id in e){let a=e[o.id];r[o.name]=a,n[a]=o.name}return{toProviderToolName:o=>{var a;return(a=r[o])!=null?a:o},toCustomToolName:o=>{var a;return(a=n[o])!=null?a:o}}}async function Zc(t,e){if(t==null)return Promise.resolve();let r=e?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Vc());return}let a=setTimeout(()=>{i(),n()},t),i=()=>{clearTimeout(a),r?.removeEventListener("abort",s)},s=()=>{i(),o(Vc())};r?.addEventListener("abort",s)})}function Vc(){return new DOMException("Delay was aborted","AbortError")}function kn(t){return Object.fromEntries([...t.headers])}var{btoa:Sg,atob:Cg}=globalThis;function Jr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Cg(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Jt(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Sg(e)}function lr(t){return t instanceof Uint8Array?Jt(t):t}var Qc="AI_DownloadError",eu=`vercel.ai.error.${Qc}`,Ig=Symbol.for(eu),zc,Wc,vo=class extends(Wc=oe,zc=Ig,Wc){constructor({url:t,statusCode:e,statusText:r,cause:n,message:o=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Qc,message:o,cause:n}),this[zc]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return oe.hasMarker(t,eu)}};var cr=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=()=>{let a=r.length,i=new Array(e);for(let s=0;s<e;s++)i[s]=r[Math.random()*a|0];return i.join("")};if(t==null)return o;if(r.includes(n))throw new ho({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${o()}`},xt=cr();function bo(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function xr(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Ag=["fetch failed","failed to fetch"];function tu({error:t,url:e,requestBodyValues:r}){if(xr(t))return t;if(t instanceof TypeError&&Ag.includes(t.message.toLowerCase())){let n=t.cause;if(n!=null)return new Ge({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function _o(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function kg(t){if(t==null)return{};let e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(let[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function lt(t,...e){let r=new Headers(kg(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var ru="4.0.6",Rg=()=>globalThis.fetch,za=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:a=Rg()})=>{try{let i=await a(t,{method:"GET",headers:lt(e,`ai-sdk/provider-utils/${ru}`,_o()),signal:o}),s=kn(i);if(!i.ok){let l;try{l=await n({response:i,url:t,requestBodyValues:{}})}catch(c){throw xr(c)||Ge.isInstance(c)?c:new Ge({message:"Failed to process error response",cause:c,statusCode:i.status,url:t,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(xr(l)||Ge.isInstance(l))?l:new Ge({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:s,requestBodyValues:{}})}}catch(i){throw tu({error:i,url:t,requestBodyValues:{}})}};function nu(t){return t!=null}function ou({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,o])=>{let a=n.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:a.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function wo({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new In({message:`${n} API key must be a string.`});if(typeof process>"u")throw new In({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new In({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new In({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function Lt({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function Wa({settingValue:t,environmentVariableName:e,settingName:r,description:n}){if(typeof t=="string")return t;if(t!=null)throw new An({message:`${n} setting must be a string.`});if(typeof process>"u")throw new An({message:`${n} setting is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new An({message:`${n} setting is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new An({message:`${n} setting must be a string. The value of the ${e} environment variable is not a string.`});return t}var Og=/"__proto__"\s*:/,Ng=/"constructor"\s*:/;function Jc(t){let e=JSON.parse(t);return e===null||typeof e!="object"||Og.test(t)===!1&&Ng.test(t)===!1?e:Mg(e)}function Mg(t){let e=[t];for(;e.length;){let r=e;e=[];for(let n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let a=n[o];a&&typeof a=="object"&&e.push(a)}}}return t}function au(t){let{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Jc(t)}try{return Jc(t)}finally{Error.stackTraceLimit=e}}function Ja(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;let{properties:r}=t;if(r!=null)for(let n of Object.keys(r))r[n]=jr(r[n])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(jr):jr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(jr)),t.allOf!=null&&(t.allOf=t.allOf.map(jr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(jr));let{definitions:e}=t;if(e!=null)for(let r of Object.keys(e))e[r]=jr(e[r]);return t}function jr(t){return typeof t=="boolean"?t:Ja(t)}var Pg=Symbol("Let zodToJsonSchema decide on which parser to use"),Kc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Dg=t=>typeof t=="string"?{...Kc,name:t}:{...Kc,...t};function mt(){return{}}function Lg(t,e){var r,n,o;let a={type:"array"};return(r=t.type)!=null&&r._def&&((o=(n=t.type)==null?void 0:n._def)==null?void 0:o.typeName)!==jg.ZodAny&&(a.items=Ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(a.minItems=t.minLength.value),t.maxLength&&(a.maxItems=t.maxLength.value),t.exactLength&&(a.minItems=t.exactLength.value,a.maxItems=t.exactLength.value),a}function Ug(t){let e={type:"integer",format:"int64"};if(!t.checks)return e;for(let r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Fg(){return{type:"boolean"}}function iu(t,e){return Ne(t.type._def,e)}var Hg=(t,e)=>Ne(t.innerType._def,e);function su(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>su(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return qg(t)}}var qg=t=>{let e={type:"integer",format:"unix-time"};for(let r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function Gg(t,e){return{...Ne(t.innerType._def,e),default:t.defaultValue()}}function $g(t,e){return e.effectStrategy==="input"?Ne(t.schema._def,e):mt()}function Bg(t){return{type:"string",enum:Array.from(t.values)}}var Vg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function zg(t,e){let r=[Ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ne(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(Vg(o))n.push(...o.allOf);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:i,...s}=o;a=s}n.push(a)}}),n.length?{allOf:n}:void 0}function Wg(t){let e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Ga=void 0,Dt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ga===void 0&&(Ga=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ga),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function lu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":jt(r,"email",n.message,e);break;case"format:idn-email":jt(r,"idn-email",n.message,e);break;case"pattern:zod":st(r,Dt.email,n.message,e);break}break;case"url":jt(r,"uri",n.message,e);break;case"uuid":jt(r,"uuid",n.message,e);break;case"regex":st(r,n.regex,n.message,e);break;case"cuid":st(r,Dt.cuid,n.message,e);break;case"cuid2":st(r,Dt.cuid2,n.message,e);break;case"startsWith":st(r,RegExp(`^${$a(n.value,e)}`),n.message,e);break;case"endsWith":st(r,RegExp(`${$a(n.value,e)}$`),n.message,e);break;case"datetime":jt(r,"date-time",n.message,e);break;case"date":jt(r,"date",n.message,e);break;case"time":jt(r,"time",n.message,e);break;case"duration":jt(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{st(r,RegExp($a(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&jt(r,"ipv4",n.message,e),n.version!=="v4"&&jt(r,"ipv6",n.message,e);break}case"base64url":st(r,Dt.base64url,n.message,e);break;case"jwt":st(r,Dt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&st(r,Dt.ipv4Cidr,n.message,e),n.version!=="v4"&&st(r,Dt.ipv6Cidr,n.message,e);break}case"emoji":st(r,Dt.emoji(),n.message,e);break;case"ulid":{st(r,Dt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{st(r,Dt.base64,n.message,e);break}}break}case"nanoid":st(r,Dt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function $a(t,e){return e.patternStrategy==="escape"?Kg(t):t}var Jg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kg(t){let e="";for(let r=0;r<t.length;r++)Jg.has(t[r])||(e+="\\"),e+=t[r];return e}function jt(t,e,r,n){var o;t.format||(o=t.anyOf)!=null&&o.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function st(t,e,r,n){var o;t.pattern||(o=t.allOf)!=null&&o.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Yc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Yc(e,n)}function Yc(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=n.i?t.source.toLowerCase():t.source,a="",i=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(i){a+=o[c],i=!1;continue}if(n.i){if(s){if(o[c].match(/[a-z]/)){l?(a+=o[c],a+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(a+=o[c],l=!0):a+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){a+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){a+=`(^|(?<=[\r
|
|
39
|
+
`&&n++}}return[e,r]}var go=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(a){o=Bc({onEvent:i=>{a.enqueue(i)},onError(i){e==="terminate"?a.error(i):typeof e=="function"&&e(i)},onRetry:r,onComment:n})},transform(a){o.feed(a)}})}};function Ge(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function Xc({tools:t=[],providerToolNames:e}){let r={},n={};for(let o of t)if(o.type==="provider"&&o.id in e){let a=e[o.id];r[o.name]=a,n[a]=o.name}return{toProviderToolName:o=>{var a;return(a=r[o])!=null?a:o},toCustomToolName:o=>{var a;return(a=n[o])!=null?a:o}}}async function Zc(t,e){if(t==null)return Promise.resolve();let r=e?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Vc());return}let a=setTimeout(()=>{i(),n()},t),i=()=>{clearTimeout(a),r?.removeEventListener("abort",s)},s=()=>{i(),o(Vc())};r?.addEventListener("abort",s)})}function Vc(){return new DOMException("Delay was aborted","AbortError")}function kn(t){return Object.fromEntries([...t.headers])}var{btoa:Sg,atob:Cg}=globalThis;function Jr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Cg(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Jt(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Sg(e)}function lr(t){return t instanceof Uint8Array?Jt(t):t}var Qc="AI_DownloadError",eu=`vercel.ai.error.${Qc}`,Ig=Symbol.for(eu),zc,Wc,vo=class extends(Wc=oe,zc=Ig,Wc){constructor({url:t,statusCode:e,statusText:r,cause:n,message:o=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Qc,message:o,cause:n}),this[zc]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return oe.hasMarker(t,eu)}};var cr=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=()=>{let a=r.length,i=new Array(e);for(let s=0;s<e;s++)i[s]=r[Math.random()*a|0];return i.join("")};if(t==null)return o;if(r.includes(n))throw new ho({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${o()}`},xt=cr();function bo(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function xr(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Ag=["fetch failed","failed to fetch"];function tu({error:t,url:e,requestBodyValues:r}){if(xr(t))return t;if(t instanceof TypeError&&Ag.includes(t.message.toLowerCase())){let n=t.cause;if(n!=null)return new $e({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function _o(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function kg(t){if(t==null)return{};let e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(let[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function lt(t,...e){let r=new Headers(kg(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var ru="4.0.6",Rg=()=>globalThis.fetch,za=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:a=Rg()})=>{try{let i=await a(t,{method:"GET",headers:lt(e,`ai-sdk/provider-utils/${ru}`,_o()),signal:o}),s=kn(i);if(!i.ok){let l;try{l=await n({response:i,url:t,requestBodyValues:{}})}catch(c){throw xr(c)||$e.isInstance(c)?c:new $e({message:"Failed to process error response",cause:c,statusCode:i.status,url:t,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(xr(l)||$e.isInstance(l))?l:new $e({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:s,requestBodyValues:{}})}}catch(i){throw tu({error:i,url:t,requestBodyValues:{}})}};function nu(t){return t!=null}function ou({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,o])=>{let a=n.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:a.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function wo({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new In({message:`${n} API key must be a string.`});if(typeof process>"u")throw new In({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new In({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new In({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function Lt({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function Wa({settingValue:t,environmentVariableName:e,settingName:r,description:n}){if(typeof t=="string")return t;if(t!=null)throw new An({message:`${n} setting must be a string.`});if(typeof process>"u")throw new An({message:`${n} setting is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new An({message:`${n} setting is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new An({message:`${n} setting must be a string. The value of the ${e} environment variable is not a string.`});return t}var Og=/"__proto__"\s*:/,Ng=/"constructor"\s*:/;function Jc(t){let e=JSON.parse(t);return e===null||typeof e!="object"||Og.test(t)===!1&&Ng.test(t)===!1?e:Mg(e)}function Mg(t){let e=[t];for(;e.length;){let r=e;e=[];for(let n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let a=n[o];a&&typeof a=="object"&&e.push(a)}}}return t}function au(t){let{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Jc(t)}try{return Jc(t)}finally{Error.stackTraceLimit=e}}function Ja(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;let{properties:r}=t;if(r!=null)for(let n of Object.keys(r))r[n]=jr(r[n])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(jr):jr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(jr)),t.allOf!=null&&(t.allOf=t.allOf.map(jr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(jr));let{definitions:e}=t;if(e!=null)for(let r of Object.keys(e))e[r]=jr(e[r]);return t}function jr(t){return typeof t=="boolean"?t:Ja(t)}var Pg=Symbol("Let zodToJsonSchema decide on which parser to use"),Kc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Dg=t=>typeof t=="string"?{...Kc,name:t}:{...Kc,...t};function mt(){return{}}function Lg(t,e){var r,n,o;let a={type:"array"};return(r=t.type)!=null&&r._def&&((o=(n=t.type)==null?void 0:n._def)==null?void 0:o.typeName)!==jg.ZodAny&&(a.items=Ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(a.minItems=t.minLength.value),t.maxLength&&(a.maxItems=t.maxLength.value),t.exactLength&&(a.minItems=t.exactLength.value,a.maxItems=t.exactLength.value),a}function Fg(t){let e={type:"integer",format:"int64"};if(!t.checks)return e;for(let r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Ug(){return{type:"boolean"}}function iu(t,e){return Ne(t.type._def,e)}var Hg=(t,e)=>Ne(t.innerType._def,e);function su(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>su(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return qg(t)}}var qg=t=>{let e={type:"integer",format:"unix-time"};for(let r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function $g(t,e){return{...Ne(t.innerType._def,e),default:t.defaultValue()}}function Gg(t,e){return e.effectStrategy==="input"?Ne(t.schema._def,e):mt()}function Bg(t){return{type:"string",enum:Array.from(t.values)}}var Vg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function zg(t,e){let r=[Ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ne(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(Vg(o))n.push(...o.allOf);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:i,...s}=o;a=s}n.push(a)}}),n.length?{allOf:n}:void 0}function Wg(t){let e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var $a=void 0,Dt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>($a===void 0&&($a=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$a),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function lu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":jt(r,"email",n.message,e);break;case"format:idn-email":jt(r,"idn-email",n.message,e);break;case"pattern:zod":st(r,Dt.email,n.message,e);break}break;case"url":jt(r,"uri",n.message,e);break;case"uuid":jt(r,"uuid",n.message,e);break;case"regex":st(r,n.regex,n.message,e);break;case"cuid":st(r,Dt.cuid,n.message,e);break;case"cuid2":st(r,Dt.cuid2,n.message,e);break;case"startsWith":st(r,RegExp(`^${Ga(n.value,e)}`),n.message,e);break;case"endsWith":st(r,RegExp(`${Ga(n.value,e)}$`),n.message,e);break;case"datetime":jt(r,"date-time",n.message,e);break;case"date":jt(r,"date",n.message,e);break;case"time":jt(r,"time",n.message,e);break;case"duration":jt(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{st(r,RegExp(Ga(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&jt(r,"ipv4",n.message,e),n.version!=="v4"&&jt(r,"ipv6",n.message,e);break}case"base64url":st(r,Dt.base64url,n.message,e);break;case"jwt":st(r,Dt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&st(r,Dt.ipv4Cidr,n.message,e),n.version!=="v4"&&st(r,Dt.ipv6Cidr,n.message,e);break}case"emoji":st(r,Dt.emoji(),n.message,e);break;case"ulid":{st(r,Dt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{st(r,Dt.base64,n.message,e);break}}break}case"nanoid":st(r,Dt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ga(t,e){return e.patternStrategy==="escape"?Kg(t):t}var Jg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kg(t){let e="";for(let r=0;r<t.length;r++)Jg.has(t[r])||(e+="\\"),e+=t[r];return e}function jt(t,e,r,n){var o;t.format||(o=t.anyOf)!=null&&o.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function st(t,e,r,n){var o;t.pattern||(o=t.allOf)!=null&&o.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Yc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Yc(e,n)}function Yc(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=n.i?t.source.toLowerCase():t.source,a="",i=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(i){a+=o[c],i=!1;continue}if(n.i){if(s){if(o[c].match(/[a-z]/)){l?(a+=o[c],a+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(a+=o[c],l=!0):a+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){a+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){a+=`(^|(?<=[\r
|
|
40
40
|
]))`;continue}else if(o[c]==="$"){a+=`($|(?=[\r
|
|
41
41
|
]))`;continue}}if(n.s&&o[c]==="."){a+=s?`${o[c]}\r
|
|
42
42
|
`:`[${o[c]}\r
|
|
43
|
-
]`;continue}a+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function cu(t,e){var r,n,o,a,i,s;let l={type:"object",additionalProperties:(r=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===yo.ZodString&&((o=t.keyType._def.checks)!=null&&o.length)){let{type:c,...p}=lu(t.keyType._def,e);return{...l,propertyNames:p}}else{if(((a=t.keyType)==null?void 0:a._def.typeName)===yo.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((i=t.keyType)==null?void 0:i._def.typeName)===yo.ZodBranded&&t.keyType._def.type._def.typeName===yo.ZodString&&((s=t.keyType._def.type._def.checks)!=null&&s.length)){let{type:c,...p}=iu(t.keyType._def,e);return{...l,propertyNames:p}}}return l}function Yg(t,e){if(e.mapStrategy==="record")return cu(t,e);let r=Ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||mt(),n=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||mt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Xg(t){let e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),o=Array.from(new Set(n.map(a=>typeof a)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Zg(){return{not:mt()}}function Qg(){return{type:"null"}}var Ba={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ey(t,e){let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ba&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,a)=>{let i=Ba[a._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(a._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((a,i,s)=>s.indexOf(a)===i);return{type:o.length>1?o:o[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(a=>!n.includes(a))],[])};return ty(t,e)}var ty=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Ne(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ry(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ba[t.innerType._def.typeName],"null"]};let r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ny(t){let e={type:"number"};if(!t.checks)return e;for(let r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function oy(t,e){let r={type:"object",properties:{}},n=[],o=t.shape();for(let i in o){let s=o[i];if(s===void 0||s._def===void 0)continue;let l=iy(s),c=Ne(s._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);let a=ay(t,e);return a!==void 0&&(r.additionalProperties=a),r}function ay(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ne(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function iy(t){try{return t.isOptional()}catch{return!0}}var sy=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ne(t.innerType._def,e);let n=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:mt()},n]}:mt()},ly=(t,e)=>{if(e.pipeStrategy==="input")return Ne(t.in._def,e);if(e.pipeStrategy==="output")return Ne(t.out._def,e);let r=Ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function cy(t,e){return Ne(t.type._def,e)}function uy(t,e){let n={type:"array",uniqueItems:!0,items:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function dy(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function py(){return{not:mt()}}function hy(){return mt()}var fy=(t,e)=>Ne(t.innerType._def,e),my=(t,e,r)=>{switch(e){case ke.ZodString:return lu(t,r);case ke.ZodNumber:return ny(t);case ke.ZodObject:return oy(t,r);case ke.ZodBigInt:return Ug(t);case ke.ZodBoolean:return Fg();case ke.ZodDate:return su(t,r);case ke.ZodUndefined:return py();case ke.ZodNull:return Qg();case ke.ZodArray:return Lg(t,r);case ke.ZodUnion:case ke.ZodDiscriminatedUnion:return ey(t,r);case ke.ZodIntersection:return zg(t,r);case ke.ZodTuple:return dy(t,r);case ke.ZodRecord:return cu(t,r);case ke.ZodLiteral:return Wg(t);case ke.ZodEnum:return Bg(t);case ke.ZodNativeEnum:return Xg(t);case ke.ZodNullable:return ry(t,r);case ke.ZodOptional:return sy(t,r);case ke.ZodMap:return Yg(t,r);case ke.ZodSet:return uy(t,r);case ke.ZodLazy:return()=>t.getter()._def;case ke.ZodPromise:return cy(t,r);case ke.ZodNaN:case ke.ZodNever:return Zg();case ke.ZodEffects:return $g(t,r);case ke.ZodAny:return mt();case ke.ZodUnknown:return hy();case ke.ZodDefault:return Gg(t,r);case ke.ZodBranded:return iu(t,r);case ke.ZodReadonly:return fy(t,r);case ke.ZodCatch:return Hg(t,r);case ke.ZodPipeline:return ly(t,r);case ke.ZodFunction:case ke.ZodVoid:case ke.ZodSymbol:return;default:return(n=>{})(e)}},gy=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ne(t,e,r=!1){var n;let o=e.seen.get(t);if(e.override){let l=(n=e.override)==null?void 0:n.call(e,t,e,o,r);if(l!==Pg)return l}if(o&&!r){let l=yy(o,e);if(l!==void 0)return l}let a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);let i=my(t,t.typeName,e),s=typeof i=="function"?Ne(i(),e):i;if(s&&vy(t,e,s),e.postProcess){let l=e.postProcess(s,t,e);return a.jsonSchema=s,l}return a.jsonSchema=s,s}var yy=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gy(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),mt()):e.$refStrategy==="seen"?mt():void 0}},vy=(t,e,r)=>(t.description&&(r.description=t.description),r),by=t=>{let e=Dg(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},_y=(t,e)=>{var r;let n=by(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[p,h])=>{var m;return{...c,[p]:(m=Ne(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0))!=null?m:mt()}},{}):void 0,a=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=(r=Ne(t._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1))!=null?r:mt(),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s);let l=a===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...o,[a]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Va=Symbol.for("vercel.ai.schema");function q(t){let e;return()=>(e==null&&(e=t()),e)}function To(t,{validate:e}={}){return{[Va]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function wy(t){return typeof t=="object"&&t!==null&&Va in t&&t[Va]===!0&&"jsonSchema"in t&&"validate"in t}function ur(t){return t==null?To({properties:{},additionalProperties:!1}):wy(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?H(t):Ey(t):t()}function Ey(t){return To(()=>Ja(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async e=>{let r=await t["~standard"].validate(e);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new Pt({value:e,cause:r.issues})}}})}function Ty(t,e){var r;let n=(r=e?.useReferences)!=null?r:!1;return To(()=>_y(t,{$refStrategy:n?"root":"none"}),{validate:async o=>{let a=await t.safeParseAsync(o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function xy(t,e){var r;let n=(r=e?.useReferences)!=null?r:!1;return To(()=>Ja(Eo.toJSONSchema(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{let a=await Eo.safeParseAsync(t,o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function Sy(t){return"_zod"in t}function H(t,e){return Sy(t)?xy(t,e):Ty(t,e)}async function St({value:t,schema:e}){let r=await nt({value:t,schema:e});if(!r.success)throw Pt.wrap({value:t,cause:r.error});return r.value}async function nt({value:t,schema:e}){let r=ur(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};let n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:Pt.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:Pt.wrap({value:t,cause:n}),rawValue:t}}}async function Cy({text:t,schema:e}){try{let r=au(t);return e==null?r:St({value:r,schema:e})}catch(r){throw Cn.isInstance(r)||Pt.isInstance(r)?r:new Cn({text:t,cause:r})}}async function pt({text:t,schema:e}){try{let r=au(t);return e==null?{success:!0,value:r,rawValue:r}:await nt({value:r,schema:e})}catch(r){return{success:!1,error:Cn.isInstance(r)?r:new Cn({text:t,cause:r}),rawValue:void 0}}}function Iy({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new go).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await pt({text:r,schema:e}))}}))}async function Ve({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;let n=await nt({value:e[t],schema:r});if(!n.success)throw new ho({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var Ay=()=>globalThis.fetch,Fe=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>ky({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i});var ky=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=Ay()})=>{try{let s=await i(t,{method:"POST",headers:lt(e,`ai-sdk/provider-utils/${ru}`,_o()),body:r.content,signal:a}),l=kn(s);if(!s.ok){let c;try{c=await o({response:s,url:t,requestBodyValues:r.values})}catch(p){throw xr(p)||Ge.isInstance(p)?p:new Ge({message:"Failed to process error response",cause:p,statusCode:s.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(xr(c)||Ge.isInstance(c))?c:new Ge({message:"Failed to process successful response",cause:c,statusCode:s.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw tu({error:s,url:t,requestBodyValues:r.values})}};function we({id:t,inputSchema:e}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider",id:t,args:c,inputSchema:e,outputSchema:n,execute:r,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l})}function Ze({id:t,inputSchema:e,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,...p})=>({type:"provider",id:t,args:p,inputSchema:e,outputSchema:r,execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Te(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var Qe=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{let i=await n.text(),s=kn(n);if(i.trim()==="")return{responseHeaders:s,value:new Ge({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{let l=await Cy({text:i,schema:t});return{responseHeaders:s,value:new Ge({message:e(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new Ge({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},Sr=t=>async({response:e})=>{let r=kn(e);if(e.body==null)throw new wc({});return{responseHeaders:r,value:Iy({stream:e.body,schema:t})}},qe=t=>async({response:e,url:r,requestBodyValues:n})=>{let o=await e.text(),a=await pt({text:o,schema:t}),i=kn(e);if(!a.success)throw new Ge({message:"Invalid JSON response",cause:a.error,statusCode:e.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}};function dr(t){return t?.replace(/\/$/,"")}function Ry(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*uu({execute:t,input:e,options:r}){let n=t(e,r);if(Ry(n)){let o;for await(let a of n)o=a,yield{type:"preliminary",output:a};yield{type:"final",output:o}}else yield{type:"final",output:await n}}import{z as Rn}from"zod/v4";import{z as u}from"zod/v4";import{z as te}from"zod/v4";import{z as Ut}from"zod/v4";import{z as ze}from"zod/v4";import{z as Me}from"zod/v4";import{z as Ft}from"zod/v4";import{z as ne}from"zod/v4";import{z as Lr}from"zod/v4";import{z as Za}from"zod/v4";import{z as Qa}from"zod/v4";import{z as On}from"zod/v4";import{z as Ct}from"zod/v4";import{z as Pe}from"zod/v4";import{z as pr}from"zod/v4";import{z as hr}from"zod/v4";import{z as fr}from"zod/v4";import{z as Ur}from"zod/v4";var Oy="3.0.13",Ny=q(()=>H(Rn.object({type:Rn.literal("error"),error:Rn.object({type:Rn.string(),message:Rn.string()})}))),du=Qe({errorSchema:Ny,errorToMessage:t=>t.error.message}),My=q(()=>H(u.object({type:u.literal("message"),id:u.string().nullish(),model:u.string().nullish(),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string(),citations:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])).optional()}),u.object({type:u.literal("thinking"),thinking:u.string(),signature:u.string()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])),stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}))),Py=q(()=>H(u.discriminatedUnion("type",[u.object({type:u.literal("message_start"),message:u.object({id:u.string().nullish(),model:u.string().nullish(),role:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()})])).nullish(),stop_reason:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string()}).nullish()})}),u.object({type:u.literal("content_block_start"),index:u.number(),content_block:u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("thinking"),thinking:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).optional(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])}),u.object({type:u.literal("content_block_delta"),index:u.number(),delta:u.discriminatedUnion("type",[u.object({type:u.literal("input_json_delta"),partial_json:u.string()}),u.object({type:u.literal("text_delta"),text:u.string()}),u.object({type:u.literal("thinking_delta"),thinking:u.string()}),u.object({type:u.literal("signature_delta"),signature:u.string()}),u.object({type:u.literal("citations_delta"),citation:u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])})])}),u.object({type:u.literal("content_block_stop"),index:u.number()}),u.object({type:u.literal("error"),error:u.object({type:u.string(),message:u.string()})}),u.object({type:u.literal("message_delta"),delta:u.object({stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}),usage:u.looseObject({input_tokens:u.number().nullish(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish()})}),u.object({type:u.literal("message_stop")}),u.object({type:u.literal("ping")})]))),Dy=q(()=>H(u.object({signature:u.string().optional(),redactedData:u.string().optional()}))),pu=te.object({citations:te.object({enabled:te.boolean()}).optional(),title:te.string().optional(),context:te.string().optional()}),jy=te.object({sendReasoning:te.boolean().optional(),structuredOutputMode:te.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:te.object({type:te.union([te.literal("enabled"),te.literal("disabled")]),budgetTokens:te.number().optional()}).optional(),disableParallelToolUse:te.boolean().optional(),cacheControl:te.object({type:te.literal("ephemeral"),ttl:te.union([te.literal("5m"),te.literal("1h")]).optional()}).optional(),mcpServers:te.array(te.object({type:te.literal("url"),name:te.string(),url:te.string(),authorizationToken:te.string().nullish(),toolConfiguration:te.object({enabled:te.boolean().nullish(),allowedTools:te.array(te.string()).nullish()}).nullish()})).optional(),container:te.object({id:te.string().optional(),skills:te.array(te.object({type:te.union([te.literal("anthropic"),te.literal("custom")]),skillId:te.string(),version:te.string().optional()})).optional()}).optional(),toolStreaming:te.boolean().optional(),effort:te.enum(["low","medium","high"]).optional(),contextManagement:te.object({edits:te.array(te.discriminatedUnion("type",[te.object({type:te.literal("clear_tool_uses_20250919"),trigger:te.discriminatedUnion("type",[te.object({type:te.literal("input_tokens"),value:te.number()}),te.object({type:te.literal("tool_uses"),value:te.number()})]).optional(),keep:te.object({type:te.literal("tool_uses"),value:te.number()}).optional(),clearAtLeast:te.object({type:te.literal("input_tokens"),value:te.number()}).optional(),clearToolInputs:te.boolean().optional(),excludeTools:te.array(te.string()).optional()}),te.object({type:te.literal("clear_thinking_20251015"),keep:te.union([te.literal("all"),te.object({type:te.literal("thinking_turns"),value:te.number()})]).optional()})]))}).optional()}),hu=4;function Ly(t){var e;let r=t?.anthropic;return(e=r?.cacheControl)!=null?e:r?.cache_control}var ei=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(t,e){let r=Ly(t);if(r){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>hu){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${hu} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},Uy=q(()=>H(Ut.object({maxCharacters:Ut.number().optional()}))),Fy=q(()=>H(Ut.object({command:Ut.enum(["view","create","str_replace","insert"]),path:Ut.string(),file_text:Ut.string().optional(),insert_line:Ut.number().int().optional(),new_str:Ut.string().optional(),old_str:Ut.string().optional(),view_range:Ut.array(Ut.number().int()).optional()}))),Hy=we({id:"anthropic.text_editor_20250728",inputSchema:Fy}),qy=(t={})=>Hy(t),Gy=q(()=>H(ze.object({maxUses:ze.number().optional(),allowedDomains:ze.array(ze.string()).optional(),blockedDomains:ze.array(ze.string()).optional(),userLocation:ze.object({type:ze.literal("approximate"),city:ze.string().optional(),region:ze.string().optional(),country:ze.string().optional(),timezone:ze.string().optional()}).optional()}))),yu=q(()=>H(ze.array(ze.object({url:ze.string(),title:ze.string().nullable(),pageAge:ze.string().nullable(),encryptedContent:ze.string(),type:ze.literal("web_search_result")})))),$y=q(()=>H(ze.object({query:ze.string()}))),By=Ze({id:"anthropic.web_search_20250305",inputSchema:$y,outputSchema:yu,supportsDeferredResults:!0}),Vy=(t={})=>By(t),zy=q(()=>H(Me.object({maxUses:Me.number().optional(),allowedDomains:Me.array(Me.string()).optional(),blockedDomains:Me.array(Me.string()).optional(),citations:Me.object({enabled:Me.boolean()}).optional(),maxContentTokens:Me.number().optional()}))),vu=q(()=>H(Me.object({type:Me.literal("web_fetch_result"),url:Me.string(),content:Me.object({type:Me.literal("document"),title:Me.string().nullable(),citations:Me.object({enabled:Me.boolean()}).optional(),source:Me.union([Me.object({type:Me.literal("base64"),mediaType:Me.literal("application/pdf"),data:Me.string()}),Me.object({type:Me.literal("text"),mediaType:Me.literal("text/plain"),data:Me.string()})])}),retrievedAt:Me.string().nullable()}))),Wy=q(()=>H(Me.object({url:Me.string()}))),Jy=Ze({id:"anthropic.web_fetch_20250910",inputSchema:Wy,outputSchema:vu,supportsDeferredResults:!0}),Ky=(t={})=>Jy(t);async function Yy({tools:t,toolChoice:e,disableParallelToolUse:r,cacheControlValidator:n,supportsStructuredOutput:o}){var a;t=t?.length?t:void 0;let i=[],s=new Set,l=n||new ei;if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};let c=[];for(let h of t)switch(h.type){case"function":{let m=l.getCacheControl(h.providerOptions,{type:"tool definition",canCache:!0}),g=(a=h.providerOptions)==null?void 0:a.anthropic,T=g?.deferLoading,y=g?.allowedCallers;c.push({name:h.name,description:h.description,input_schema:h.inputSchema,cache_control:m,...o===!0&&h.strict!=null?{strict:h.strict}:{},...T!=null?{defer_loading:T}:{},...y!=null?{allowed_callers:y}:{},...h.inputExamples!=null?{input_examples:h.inputExamples.map(b=>b.input)}:{}}),o===!0&&s.add("structured-outputs-2025-11-13"),(h.inputExamples!=null||y!=null)&&s.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(h.id){case"anthropic.code_execution_20250522":{s.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{s.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let m=await St({value:h.args,schema:Uy});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:m.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{s.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{s.add("web-fetch-2025-09-10");let m=await St({value:h.args,schema:zy});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:m.maxUses,allowed_domains:m.allowedDomains,blocked_domains:m.blockedDomains,citations:m.citations,max_content_tokens:m.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let m=await St({value:h.args,schema:Gy});c.push({type:"web_search_20250305",name:"web_search",max_uses:m.maxUses,allowed_domains:m.allowedDomains,blocked_domains:m.blockedDomains,user_location:m.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{i.push({type:"unsupported",feature:`provider-defined tool ${h.id}`});break}}break}default:{i.push({type:"unsupported",feature:`tool ${h}`});break}}if(e==null)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:s};let p=e.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};case"tool":return{tools:c,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:s};default:{let h=p;throw new tt({functionality:`tool choice type: ${h}`})}}}function fu(t){var e,r;let n=t.input_tokens,o=t.output_tokens,a=(e=t.cache_creation_input_tokens)!=null?e:0,i=(r=t.cache_read_input_tokens)!=null?r:0;return{inputTokens:{total:n+a+i,noCache:n,cacheRead:i,cacheWrite:a},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:t}}var bu=q(()=>H(Ft.object({type:Ft.literal("code_execution_result"),stdout:Ft.string(),stderr:Ft.string(),return_code:Ft.number(),content:Ft.array(Ft.object({type:Ft.literal("code_execution_output"),file_id:Ft.string()})).optional().default([])}))),Xy=q(()=>H(Ft.object({code:Ft.string()}))),Zy=Ze({id:"anthropic.code_execution_20250522",inputSchema:Xy,outputSchema:bu}),Qy=(t={})=>Zy(t),_u=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("code_execution_result"),stdout:ne.string(),stderr:ne.string(),return_code:ne.number(),content:ne.array(ne.object({type:ne.literal("code_execution_output"),file_id:ne.string()})).optional().default([])}),ne.object({type:ne.literal("bash_code_execution_result"),content:ne.array(ne.object({type:ne.literal("bash_code_execution_output"),file_id:ne.string()})),stdout:ne.string(),stderr:ne.string(),return_code:ne.number()}),ne.object({type:ne.literal("bash_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_view_result"),content:ne.string(),file_type:ne.string(),num_lines:ne.number().nullable(),start_line:ne.number().nullable(),total_lines:ne.number().nullable()}),ne.object({type:ne.literal("text_editor_code_execution_create_result"),is_file_update:ne.boolean()}),ne.object({type:ne.literal("text_editor_code_execution_str_replace_result"),lines:ne.array(ne.string()).nullable(),new_lines:ne.number().nullable(),new_start:ne.number().nullable(),old_lines:ne.number().nullable(),old_start:ne.number().nullable()})]))),ev=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("programmatic-tool-call"),code:ne.string()}),ne.object({type:ne.literal("bash_code_execution"),command:ne.string()}),ne.discriminatedUnion("command",[ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("view"),path:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("create"),path:ne.string(),file_text:ne.string().nullish()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("str_replace"),path:ne.string(),old_str:ne.string(),new_str:ne.string()})])]))),tv=Ze({id:"anthropic.code_execution_20250825",inputSchema:ev,outputSchema:_u,supportsDeferredResults:!0}),rv=(t={})=>tv(t),wu=q(()=>H(Lr.array(Lr.object({type:Lr.literal("tool_reference"),toolName:Lr.string()})))),nv=q(()=>H(Lr.object({pattern:Lr.string(),limit:Lr.number().optional()}))),ov=Ze({id:"anthropic.tool_search_regex_20251119",inputSchema:nv,outputSchema:wu}),av=(t={})=>ov(t);function iv(t){if(typeof t=="string")return Buffer.from(t,"base64").toString("utf-8");if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw t instanceof URL?new tt({functionality:"URL-based text documents are not supported for citations"}):new tt({functionality:`unsupported data type for text documents: ${typeof t}`})}function Ka(t){return t instanceof URL||sv(t)}function sv(t){return typeof t=="string"&&/^https?:\/\//i.test(t)}function Ya(t){return t instanceof URL?t.toString():t}async function lv({prompt:t,sendReasoning:e,warnings:r,cacheControlValidator:n,toolNameMapping:o}){var a,i,s,l,c,p,h,m,g,T,y,b,_,D,V;let X=new Set,P=cv(t),N=n||new ei,R,Q=[];async function E(Z){var Y,ce;let B=await Ve({provider:"anthropic",providerOptions:Z,schema:pu});return(ce=(Y=B?.citations)==null?void 0:Y.enabled)!=null?ce:!1}async function re(Z){let Y=await Ve({provider:"anthropic",providerOptions:Z,schema:pu});return{title:Y?.title,context:Y?.context}}for(let Z=0;Z<P.length;Z++){let Y=P[Z],ce=Z===P.length-1,B=Y.type;switch(B){case"system":{if(R!=null)throw new tt({functionality:"Multiple system messages that are separated by user/assistant messages"});R=Y.messages.map(({content:J,providerOptions:fe})=>({type:"text",text:J,cache_control:N.getCacheControl(fe,{type:"system message",canCache:!0})}));break}case"user":{let J=[];for(let fe of Y.messages){let{role:j,content:ye}=fe;switch(j){case"user":{for(let Se=0;Se<ye.length;Se++){let he=ye[Se],Ue=Se===ye.length-1,z=(a=N.getCacheControl(he.providerOptions,{type:"user message part",canCache:!0}))!=null?a:Ue?N.getCacheControl(fe.providerOptions,{type:"user message",canCache:!0}):void 0;switch(he.type){case"text":{J.push({type:"text",text:he.text,cache_control:z});break}case"file":{if(he.mediaType.startsWith("image/"))J.push({type:"image",source:Ka(he.data)?{type:"url",url:Ya(he.data)}:{type:"base64",media_type:he.mediaType==="image/*"?"image/jpeg":he.mediaType,data:lr(he.data)},cache_control:z});else if(he.mediaType==="application/pdf"){X.add("pdfs-2024-09-25");let F=await E(he.providerOptions),ve=await re(he.providerOptions);J.push({type:"document",source:Ka(he.data)?{type:"url",url:Ya(he.data)}:{type:"base64",media_type:"application/pdf",data:lr(he.data)},title:(i=ve.title)!=null?i:he.filename,...ve.context&&{context:ve.context},...F&&{citations:{enabled:!0}},cache_control:z})}else if(he.mediaType==="text/plain"){let F=await E(he.providerOptions),ve=await re(he.providerOptions);J.push({type:"document",source:Ka(he.data)?{type:"url",url:Ya(he.data)}:{type:"text",media_type:"text/plain",data:iv(he.data)},title:(s=ve.title)!=null?s:he.filename,...ve.context&&{context:ve.context},...F&&{citations:{enabled:!0}},cache_control:z})}else throw new tt({functionality:`media type: ${he.mediaType}`});break}}}break}case"tool":{for(let Se=0;Se<ye.length;Se++){let he=ye[Se];if(he.type==="tool-approval-response")continue;let Ue=Se===ye.length-1,z=(l=N.getCacheControl(he.providerOptions,{type:"tool result part",canCache:!0}))!=null?l:Ue?N.getCacheControl(fe.providerOptions,{type:"tool result message",canCache:!0}):void 0,F=he.output,ve;switch(F.type){case"content":ve=F.value.map(_e=>{switch(_e.type){case"text":return{type:"text",text:_e.text};case"image-data":return{type:"image",source:{type:"base64",media_type:_e.mediaType,data:_e.data}};case"image-url":return{type:"image",source:{type:"url",url:_e.url}};case"file-url":return{type:"document",source:{type:"url",url:_e.url}};case"file-data":{if(_e.mediaType==="application/pdf")return X.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:_e.mediaType,data:_e.data}};r.push({type:"other",message:`unsupported tool content part type: ${_e.type} with media type: ${_e.mediaType}`});return}default:{r.push({type:"other",message:`unsupported tool content part type: ${_e.type}`});return}}}).filter(nu);break;case"text":case"error-text":ve=F.value;break;case"execution-denied":ve=(c=F.reason)!=null?c:"Tool execution denied.";break;case"json":case"error-json":default:ve=JSON.stringify(F.value);break}J.push({type:"tool_result",tool_use_id:he.toolCallId,content:ve,is_error:F.type==="error-text"||F.type==="error-json"?!0:void 0,cache_control:z})}break}default:{let Se=j;throw new Error(`Unsupported role: ${Se}`)}}}Q.push({role:"user",content:J});break}case"assistant":{let J=[],fe=new Set;for(let j=0;j<Y.messages.length;j++){let ye=Y.messages[j],Se=j===Y.messages.length-1,{content:he}=ye;for(let Ue=0;Ue<he.length;Ue++){let z=he[Ue],F=Ue===he.length-1,ve=(p=N.getCacheControl(z.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:F?N.getCacheControl(ye.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(z.type){case"text":{J.push({type:"text",text:ce&&Se&&F?z.text.trim():z.text,cache_control:ve});break}case"reasoning":{if(e){let _e=await Ve({provider:"anthropic",providerOptions:z.providerOptions,schema:Dy});_e!=null?_e.signature!=null?(N.getCacheControl(z.providerOptions,{type:"thinking block",canCache:!1}),J.push({type:"thinking",thinking:z.text,signature:_e.signature})):_e.redactedData!=null?(N.getCacheControl(z.providerOptions,{type:"redacted thinking block",canCache:!1}),J.push({type:"redacted_thinking",data:_e.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(z.providerExecuted){let ae=o.toProviderToolName(z.toolName);if(((m=(h=z.providerOptions)==null?void 0:h.anthropic)==null?void 0:m.type)==="mcp-tool-use"){fe.add(z.toolCallId);let d=(T=(g=z.providerOptions)==null?void 0:g.anthropic)==null?void 0:T.serverName;if(d==null||typeof d!="string"){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}J.push({type:"mcp_tool_use",id:z.toolCallId,name:z.toolName,input:z.input,server_name:d,cache_control:ve})}else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&typeof z.input.type=="string"&&(z.input.type==="bash_code_execution"||z.input.type==="text_editor_code_execution"))J.push({type:"server_tool_use",id:z.toolCallId,name:z.input.type,input:z.input,cache_control:ve});else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&z.input.type==="programmatic-tool-call"){let{type:d,...f}=z.input;J.push({type:"server_tool_use",id:z.toolCallId,name:"code_execution",input:f,cache_control:ve})}else ae==="code_execution"||ae==="web_fetch"||ae==="web_search"?J.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:ve}):ae==="tool_search_tool_regex"||ae==="tool_search_tool_bm25"?J.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:ve}):r.push({type:"other",message:`provider executed tool call for tool ${z.toolName} is not supported`});break}let _e=(y=z.providerOptions)==null?void 0:y.anthropic,ue=_e?.caller?_e.caller.type==="code_execution_20250825"&&_e.caller.toolId?{type:"code_execution_20250825",tool_id:_e.caller.toolId}:_e.caller.type==="direct"?{type:"direct"}:void 0:void 0;J.push({type:"tool_use",id:z.toolCallId,name:z.toolName,input:z.input,...ue&&{caller:ue},cache_control:ve});break}case"tool-result":{let _e=o.toProviderToolName(z.toolName);if(fe.has(z.toolCallId)){let ue=z.output;if(ue.type!=="json"&&ue.type!=="error-json"){r.push({type:"other",message:`provider executed tool result output type ${ue.type} for tool ${z.toolName} is not supported`});break}J.push({type:"mcp_tool_result",tool_use_id:z.toolCallId,is_error:ue.type==="error-json",content:ue.value,cache_control:ve})}else if(_e==="code_execution"){let ue=z.output;if(ue.type==="error-text"||ue.type==="error-json"){let ae={};try{typeof ue.value=="string"?ae=JSON.parse(ue.value):typeof ue.value=="object"&&ue.value!==null&&(ae=ue.value)}catch{}ae.type==="code_execution_tool_result_error"?J.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=ae.errorCode)!=null?b:"unknown"},cache_control:ve}):J.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:ve,content:{type:"bash_code_execution_tool_result_error",error_code:(_=ae.errorCode)!=null?_:"unknown"}});break}if(ue.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${ue.type} for tool ${z.toolName} is not supported`});break}if(ue.value==null||typeof ue.value!="object"||!("type"in ue.value)||typeof ue.value.type!="string"){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${z.toolName}`});break}if(ue.value.type==="code_execution_result"){let ae=await St({value:ue.value,schema:bu});J.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(D=ae.content)!=null?D:[]},cache_control:ve})}else{let ae=await St({value:ue.value,schema:_u});ae.type==="code_execution_result"?J.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(V=ae.content)!=null?V:[]},cache_control:ve}):ae.type==="bash_code_execution_result"||ae.type==="bash_code_execution_tool_result_error"?J.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:ve,content:ae}):J.push({type:"text_editor_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:ve,content:ae})}break}if(_e==="web_fetch"){let ue=z.output;if(ue.type==="error-json"){let K=JSON.parse(ue.value);J.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:K.errorCode},cache_control:ve});break}if(ue.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${ue.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:ue.value,schema:vu});J.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_result",url:ae.url,retrieved_at:ae.retrievedAt,content:{type:"document",title:ae.content.title,citations:ae.content.citations,source:{type:ae.content.source.type,media_type:ae.content.source.mediaType,data:ae.content.source.data}}},cache_control:ve});break}if(_e==="web_search"){let ue=z.output;if(ue.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${ue.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:ue.value,schema:yu});J.push({type:"web_search_tool_result",tool_use_id:z.toolCallId,content:ae.map(K=>({url:K.url,title:K.title,page_age:K.pageAge,encrypted_content:K.encryptedContent,type:K.type})),cache_control:ve});break}if(_e==="tool_search_tool_regex"||_e==="tool_search_tool_bm25"){let ue=z.output;if(ue.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${ue.type} for tool ${z.toolName} is not supported`});break}let K=(await St({value:ue.value,schema:wu})).map(d=>({type:"tool_reference",tool_name:d.toolName}));J.push({type:"tool_search_tool_result",tool_use_id:z.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:K},cache_control:ve});break}r.push({type:"other",message:`provider executed tool result for tool ${z.toolName} is not supported`});break}}}}Q.push({role:"assistant",content:J});break}default:{let J=B;throw new Error(`content type: ${J}`)}}}return{prompt:{system:R,messages:Q},betas:X}}function cv(t){let e=[],r;for(let n of t){let{role:o}=n;switch(o){case"system":{r?.type!=="system"&&(r={type:"system",messages:[]},e.push(r)),r.messages.push(n);break}case"assistant":{r?.type!=="assistant"&&(r={type:"assistant",messages:[]},e.push(r)),r.messages.push(n);break}case"user":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}case"tool":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}}return e}function Xa({finishReason:t,isJsonResponseFromTool:e}){switch(t){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}function mu(t,e,r){var n;if(t.type!=="page_location"&&t.type!=="char_location")return;let o=e[t.document_index];if(o)return{type:"source",sourceType:"document",id:r(),mediaType:o.mediaType,title:(n=t.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:t.type==="page_location"?{citedText:t.cited_text,startPageNumber:t.start_page_number,endPageNumber:t.end_page_number}:{citedText:t.cited_text,startCharIndex:t.start_char_index,endCharIndex:t.end_char_index}}}}var uv=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}supportsUrl(t){return t.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({userSuppliedBetas:t,prompt:e,maxOutputTokens:r,temperature:n,topP:o,topK:a,frequencyPenalty:i,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:h,toolChoice:m,providerOptions:g,stream:T}){var y,b,_,D,V,X;let P=[];i!=null&&P.push({type:"unsupported",feature:"frequencyPenalty"}),s!=null&&P.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&P.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(P.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(P.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),c?.type==="json"&&c.schema==null&&P.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let N=await Ve({provider:"anthropic",providerOptions:g,schema:jy}),{maxOutputTokens:R,supportsStructuredOutput:Q,isKnownModel:E}=dv(this.modelId),re=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&Q,Z=(b=N?.structuredOutputMode)!=null?b:"auto",Y=Z==="outputFormat"||Z==="auto"&&re,ce=c?.type==="json"&&c.schema!=null&&!Y?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,B=N?.contextManagement,J=new ei,fe=Xc({tools:h,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:j,betas:ye}=await lv({prompt:e,sendReasoning:(_=N?.sendReasoning)!=null?_:!0,warnings:P,cacheControlValidator:J,toolNameMapping:fe}),Se=((D=N?.thinking)==null?void 0:D.type)==="enabled",he=(V=N?.thinking)==null?void 0:V.budgetTokens,Ue=r??R,z={model:this.modelId,max_tokens:Ue,temperature:n,top_k:a,top_p:o,stop_sequences:l,...Se&&{thinking:{type:"enabled",budget_tokens:he}},...N?.effort&&{output_config:{effort:N.effort}},...Y&&c?.type==="json"&&c.schema!=null&&{output_format:{type:"json_schema",schema:c.schema}},...N?.mcpServers&&N.mcpServers.length>0&&{mcp_servers:N.mcpServers.map(d=>({type:d.type,name:d.name,url:d.url,authorization_token:d.authorizationToken,tool_configuration:d.toolConfiguration?{allowed_tools:d.toolConfiguration.allowedTools,enabled:d.toolConfiguration.enabled}:void 0}))},...N?.container&&{container:N.container.skills&&N.container.skills.length>0?{id:N.container.id,skills:N.container.skills.map(d=>({type:d.type,skill_id:d.skillId,version:d.version}))}:N.container.id},system:j.system,messages:j.messages,...B&&{context_management:{edits:B.edits.map(d=>{let f=d.type;switch(f){case"clear_tool_uses_20250919":return{type:d.type,...d.trigger!==void 0&&{trigger:d.trigger},...d.keep!==void 0&&{keep:d.keep},...d.clearAtLeast!==void 0&&{clear_at_least:d.clearAtLeast},...d.clearToolInputs!==void 0&&{clear_tool_inputs:d.clearToolInputs},...d.excludeTools!==void 0&&{exclude_tools:d.excludeTools}};case"clear_thinking_20251015":return{type:d.type,...d.keep!==void 0&&{keep:d.keep}};default:P.push({type:"other",message:`Unknown context management strategy: ${f}`});return}}).filter(d=>d!==void 0)}}};Se?(he==null&&(P.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),z.thinking={type:"enabled",budget_tokens:1024},he=1024),z.temperature!=null&&(z.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),a!=null&&(z.top_k=void 0,P.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(z.top_p=void 0,P.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),z.max_tokens=Ue+(he??0)):o!=null&&n!=null&&(P.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),z.top_p=void 0),E&&z.max_tokens>R&&(r!=null&&P.push({type:"unsupported",feature:"maxOutputTokens",details:`${z.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${R} max output tokens. The max output tokens have been limited to ${R}.`}),z.max_tokens=R),N?.mcpServers&&N.mcpServers.length>0&&ye.add("mcp-client-2025-04-04"),B&&ye.add("context-management-2025-06-27"),N?.container&&N.container.skills&&N.container.skills.length>0&&(ye.add("code-execution-2025-08-25"),ye.add("skills-2025-10-02"),ye.add("files-api-2025-04-14"),h?.some(d=>d.type==="provider"&&d.id==="anthropic.code_execution_20250825")||P.push({type:"other",message:"code execution tool is required when using skills"})),N?.effort&&ye.add("effort-2025-11-24"),T&&((X=N?.toolStreaming)==null||X)&&ye.add("fine-grained-tool-streaming-2025-05-14"),Y&&c?.type==="json"&&c.schema!=null&&ye.add("structured-outputs-2025-11-13");let{tools:ve,toolChoice:_e,toolWarnings:ue,betas:ae}=await Yy(ce!=null?{tools:[...h??[],ce],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:J,supportsStructuredOutput:re}:{tools:h??[],toolChoice:m,disableParallelToolUse:N?.disableParallelToolUse,cacheControlValidator:J,supportsStructuredOutput:re}),K=J.getWarnings();return{args:{...z,tools:ve,tool_choice:_e,stream:T===!0?!0:void 0},warnings:[...P,...ue,...K],betas:new Set([...ye,...ae,...t]),usesJsonResponseTool:ce!=null,toolNameMapping:fe}}async getHeaders({betas:t,headers:e}){return $e(await Te(this.config.headers),e,t.size>0?{"anthropic-beta":Array.from(t).join(",")}:{})}async getBetasFromHeaders(t){var e,r;let o=(e=(await Te(this.config.headers))["anthropic-beta"])!=null?e:"",a=(r=t?.["anthropic-beta"])!=null?r:"";return new Set([...o.toLowerCase().split(","),...a.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(t){var e,r,n;return(n=(r=(e=this.config).buildRequestUrl)==null?void 0:r.call(e,this.config.baseURL,t))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(t){var e,r,n;return(n=(r=(e=this.config).transformRequestBody)==null?void 0:r.call(e,t))!=null?n:t}extractCitationDocuments(t){let e=r=>{var n,o;if(r.type!=="file"||r.mediaType!=="application/pdf"&&r.mediaType!=="text/plain")return!1;let a=(n=r.providerOptions)==null?void 0:n.anthropic,i=a?.citations;return(o=i?.enabled)!=null?o:!1};return t.filter(r=>r.role==="user").flatMap(r=>r.content).filter(e).map(r=>{var n;let o=r;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(t){var e,r,n,o,a,i,s,l,c,p,h;let{args:m,warnings:g,betas:T,usesJsonResponseTool:y,toolNameMapping:b}=await this.getArgs({...t,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),_=this.extractCitationDocuments(t.prompt),{responseHeaders:D,value:V,rawValue:X}=await Fe({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:T,headers:t.headers}),body:this.transformRequestBody(m),failedResponseHandler:du,successfulResponseHandler:qe(My),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=[],N={},R={},Q=!1;for(let E of V.content)switch(E.type){case"text":{if(!y&&(P.push({type:"text",text:E.text}),E.citations))for(let re of E.citations){let Z=mu(re,_,this.generateId);Z&&P.push(Z)}break}case"thinking":{P.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{P.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"tool_use":{if(y&&E.name==="json")Q=!0,P.push({type:"text",text:JSON.stringify(E.input)});else{let Z=E.caller,Y=Z?{type:Z.type,toolId:"tool_id"in Z?Z.tool_id:void 0}:void 0;P.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...Y&&{providerMetadata:{anthropic:{caller:Y}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")P.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let re=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;P.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(re),providerExecuted:!0})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(R[E.id]=E.name,P.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{N[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},P.push(N[E.id]);break}case"mcp_tool_result":{P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:N[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:N[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}}):E.content.type==="web_fetch_tool_result_error"&&P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),result:E.content.map(re=>{var Z;return{url:re.url,title:re.title,pageAge:(Z=re.page_age)!=null?Z:null,encryptedContent:re.encrypted_content,type:re.type}})});for(let re of E.content)P.push({type:"source",sourceType:"url",id:this.generateId(),url:re.url,title:re.title,providerMetadata:{anthropic:{pageAge:(e=re.page_age)!=null?e:null}}})}else P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(r=E.content.content)!=null?r:[]}}):E.content.type==="code_execution_tool_result_error"&&P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let re=(n=R[E.tool_use_id])!=null?n:"tool_search_tool_regex";E.content.type==="tool_search_tool_search_result"?P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(re),result:E.content.tool_references.map(Z=>({type:Z.type,toolName:Z.tool_name}))}):P.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(re),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:P,finishReason:{unified:Xa({finishReason:V.stop_reason,isJsonResponseFromTool:Q}),raw:(o=V.stop_reason)!=null?o:void 0},usage:fu(V.usage),request:{body:m},response:{id:(a=V.id)!=null?a:void 0,modelId:(i=V.model)!=null?i:void 0,headers:D,body:X},warnings:g,providerMetadata:{anthropic:{usage:V.usage,cacheCreationInputTokens:(s=V.usage.cache_creation_input_tokens)!=null?s:null,stopSequence:(l=V.stop_sequence)!=null?l:null,container:V.container?{expiresAt:V.container.expires_at,id:V.container.id,skills:(p=(c=V.container.skills)==null?void 0:c.map(E=>({type:E.type,skillId:E.skill_id,version:E.version})))!=null?p:null}:null,contextManagement:(h=gu(V.context_management))!=null?h:null}}}}async doStream(t){var e,r;let{args:n,warnings:o,betas:a,usesJsonResponseTool:i,toolNameMapping:s}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),l=this.extractCitationDocuments(t.prompt),c=this.buildRequestUrl(!0),{responseHeaders:p,value:h}=await Fe({url:c,headers:await this.getHeaders({betas:a,headers:t.headers}),body:this.transformRequestBody(n),failedResponseHandler:du,successfulResponseHandler:Sr(Py),abortSignal:t.abortSignal,fetch:this.config.fetch}),m={unified:"other",raw:void 0},g={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},T={},y={},b={},_=null,D,V=null,X=null,P=null,N=!1,R,Q=this.generateId,E=h.pipeThrough(new TransformStream({start(ce){ce.enqueue({type:"stream-start",warnings:o})},transform(ce,B){var J,fe,j,ye,Se,he,Ue,z,F,ve,_e,ue,ae;if(t.includeRawChunks&&B.enqueue({type:"raw",rawValue:ce.rawValue}),!ce.success){B.enqueue({type:"error",error:ce.error});return}let K=ce.value;switch(K.type){case"ping":return;case"content_block_start":{let d=K.content_block,f=d.type;switch(R=f,f){case"text":{if(i)return;T[K.index]={type:"text"},B.enqueue({type:"text-start",id:String(K.index)});return}case"thinking":{T[K.index]={type:"reasoning"},B.enqueue({type:"reasoning-start",id:String(K.index)});return}case"redacted_thinking":{T[K.index]={type:"reasoning"},B.enqueue({type:"reasoning-start",id:String(K.index),providerMetadata:{anthropic:{redactedData:d.data}}});return}case"tool_use":{if(i&&d.name==="json")N=!0,T[K.index]={type:"text"},B.enqueue({type:"text-start",id:String(K.index)});else{let C=d.caller,S=C?{type:C.type,toolId:"tool_id"in C?C.tool_id:void 0}:void 0,M=d.input&&Object.keys(d.input).length>0?JSON.stringify(d.input):"";T[K.index]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:M,firstDelta:M.length===0,...S&&{caller:S}},B.enqueue({type:"tool-input-start",id:d.id,toolName:d.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(d.name)){let v=d.name==="text_editor_code_execution"||d.name==="bash_code_execution"?"code_execution":d.name,C=s.toCustomToolName(v);T[K.index]={type:"tool-call",toolCallId:d.id,toolName:C,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},B.enqueue({type:"tool-input-start",id:d.id,toolName:C,providerExecuted:!0})}else if(d.name==="tool_search_tool_regex"||d.name==="tool_search_tool_bm25"){b[d.id]=d.name;let v=s.toCustomToolName(d.name);T[K.index]={type:"tool-call",toolCallId:d.id,toolName:v,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},B.enqueue({type:"tool-input-start",id:d.id,toolName:v,providerExecuted:!0})}return}case"web_fetch_tool_result":{d.content.type==="web_fetch_result"?B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:d.content.url,retrievedAt:d.content.retrieved_at,content:{type:d.content.content.type,title:d.content.content.title,citations:d.content.content.citations,source:{type:d.content.content.source.type,mediaType:d.content.content.source.media_type,data:d.content.content.source.data}}}}):d.content.type==="web_fetch_tool_result_error"&&B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:d.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(d.content)){B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),result:d.content.map(v=>{var C;return{url:v.url,title:v.title,pageAge:(C=v.page_age)!=null?C:null,encryptedContent:v.encrypted_content,type:v.type}})});for(let v of d.content)B.enqueue({type:"source",sourceType:"url",id:Q(),url:v.url,title:v.title,providerMetadata:{anthropic:{pageAge:(J=v.page_age)!=null?J:null}}})}else B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:d.content.error_code}});return}case"code_execution_tool_result":{d.content.type==="code_execution_result"?B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:{type:d.content.type,stdout:d.content.stdout,stderr:d.content.stderr,return_code:d.content.return_code,content:(fe=d.content.content)!=null?fe:[]}}):d.content.type==="code_execution_tool_result_error"&&B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:d.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:d.content});return}case"tool_search_tool_result":{let v=(j=b[d.tool_use_id])!=null?j:"tool_search_tool_regex";d.content.type==="tool_search_tool_search_result"?B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),result:d.content.tool_references.map(C=>({type:C.type,toolName:C.tool_name}))}):B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:d.content.error_code}});return}case"mcp_tool_use":{y[d.id]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:JSON.stringify(d.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:d.server_name}}},B.enqueue(y[d.id]);return}case"mcp_tool_result":{B.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:y[d.tool_use_id].toolName,isError:d.is_error,result:d.content,dynamic:!0,providerMetadata:y[d.tool_use_id].providerMetadata});return}default:{let v=f;throw new Error(`Unsupported content block type: ${v}`)}}}case"content_block_stop":{if(T[K.index]!=null){let d=T[K.index];switch(d.type){case"text":{B.enqueue({type:"text-end",id:String(K.index)});break}case"reasoning":{B.enqueue({type:"reasoning-end",id:String(K.index)});break}case"tool-call":if(!(i&&d.toolName==="json")){B.enqueue({type:"tool-input-end",id:d.toolCallId});let v=d.input===""?"{}":d.input;if(d.providerToolName==="code_execution")try{let C=JSON.parse(v);C!=null&&typeof C=="object"&&"code"in C&&!("type"in C)&&(v=JSON.stringify({type:"programmatic-tool-call",...C}))}catch{}B.enqueue({type:"tool-call",toolCallId:d.toolCallId,toolName:d.toolName,input:v,providerExecuted:d.providerExecuted,...d.caller&&{providerMetadata:{anthropic:{caller:d.caller}}}})}break}delete T[K.index]}R=void 0;return}case"content_block_delta":{let d=K.delta.type;switch(d){case"text_delta":{if(i)return;B.enqueue({type:"text-delta",id:String(K.index),delta:K.delta.text});return}case"thinking_delta":{B.enqueue({type:"reasoning-delta",id:String(K.index),delta:K.delta.thinking});return}case"signature_delta":{R==="thinking"&&B.enqueue({type:"reasoning-delta",id:String(K.index),delta:"",providerMetadata:{anthropic:{signature:K.delta.signature}}});return}case"input_json_delta":{let f=T[K.index],v=K.delta.partial_json;if(v.length===0)return;if(N){if(f?.type!=="text")return;B.enqueue({type:"text-delta",id:String(K.index),delta:v})}else{if(f?.type!=="tool-call")return;f.firstDelta&&(f.providerToolName==="bash_code_execution"||f.providerToolName==="text_editor_code_execution")&&(v=`{"type": "${f.providerToolName}",${v.substring(1)}`),B.enqueue({type:"tool-input-delta",id:f.toolCallId,delta:v}),f.input+=v,f.firstDelta=!1}return}case"citations_delta":{let f=K.delta.citation,v=mu(f,l,Q);v&&B.enqueue(v);return}default:{let f=d;throw new Error(`Unsupported delta type: ${f}`)}}}case"message_start":{if(g.input_tokens=K.message.usage.input_tokens,g.cache_read_input_tokens=(ye=K.message.usage.cache_read_input_tokens)!=null?ye:0,g.cache_creation_input_tokens=(Se=K.message.usage.cache_creation_input_tokens)!=null?Se:0,D={...K.message.usage},V=(he=K.message.usage.cache_creation_input_tokens)!=null?he:null,K.message.container!=null&&(P={expiresAt:K.message.container.expires_at,id:K.message.container.id,skills:null}),K.message.stop_reason!=null&&(m={unified:Xa({finishReason:K.message.stop_reason,isJsonResponseFromTool:N}),raw:K.message.stop_reason}),B.enqueue({type:"response-metadata",id:(Ue=K.message.id)!=null?Ue:void 0,modelId:(z=K.message.model)!=null?z:void 0}),K.message.content!=null)for(let d=0;d<K.message.content.length;d++){let f=K.message.content[d];if(f.type==="tool_use"){let v=f.caller,C=v?{type:v.type,toolId:"tool_id"in v?v.tool_id:void 0}:void 0;B.enqueue({type:"tool-input-start",id:f.id,toolName:f.name});let S=JSON.stringify((F=f.input)!=null?F:{});B.enqueue({type:"tool-input-delta",id:f.id,delta:S}),B.enqueue({type:"tool-input-end",id:f.id}),B.enqueue({type:"tool-call",toolCallId:f.id,toolName:f.name,input:S,...C&&{providerMetadata:{anthropic:{caller:C}}}})}}return}case"message_delta":{K.usage.input_tokens!=null&&g.input_tokens!==K.usage.input_tokens&&(g.input_tokens=K.usage.input_tokens),g.output_tokens=K.usage.output_tokens,m={unified:Xa({finishReason:K.delta.stop_reason,isJsonResponseFromTool:N}),raw:(ve=K.delta.stop_reason)!=null?ve:void 0},X=(_e=K.delta.stop_sequence)!=null?_e:null,P=K.delta.container!=null?{expiresAt:K.delta.container.expires_at,id:K.delta.container.id,skills:(ae=(ue=K.delta.container.skills)==null?void 0:ue.map(d=>({type:d.type,skillId:d.skill_id,version:d.version})))!=null?ae:null}:null,K.delta.context_management&&(_=gu(K.delta.context_management)),D={...D,...K.usage};return}case"message_stop":{B.enqueue({type:"finish",finishReason:m,usage:fu(g),providerMetadata:{anthropic:{usage:D??null,cacheCreationInputTokens:V,stopSequence:X,container:P,contextManagement:_}}});return}case"error":{B.enqueue({type:"error",error:K.error});return}default:{let d=K;throw new Error(`Unsupported chunk type: ${d}`)}}}})),[re,Z]=E.tee(),Y=re.getReader();try{await Y.read();let ce=await Y.read();if(((e=ce.value)==null?void 0:e.type)==="raw"&&(ce=await Y.read()),((r=ce.value)==null?void 0:r.type)==="error"){let B=ce.value.error;throw new Ge({message:B.message,url:c,requestBodyValues:n,statusCode:B.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(B),isRetryable:B.type==="overloaded_error"})}}finally{Y.cancel().catch(()=>{}),Y.releaseLock()}return{stream:Z,request:{body:n},response:{headers:p}}}};function dv(t){return t.includes("claude-sonnet-4-5")||t.includes("claude-opus-4-5")||t.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-sonnet-4-")||t.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function gu(t){return t?{appliedEdits:t.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens}}}).filter(e=>e!==void 0)}:null}var pv=q(()=>H(Za.object({command:Za.string(),restart:Za.boolean().optional()}))),hv=we({id:"anthropic.bash_20241022",inputSchema:pv}),fv=q(()=>H(Qa.object({command:Qa.string(),restart:Qa.boolean().optional()}))),mv=we({id:"anthropic.bash_20250124",inputSchema:fv}),gv=q(()=>H(On.object({action:On.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:On.array(On.number().int()).optional(),text:On.string().optional()}))),yv=we({id:"anthropic.computer_20241022",inputSchema:gv}),vv=q(()=>H(Ct.object({action:Ct.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ct.tuple([Ct.number().int(),Ct.number().int()]).optional(),duration:Ct.number().optional(),scroll_amount:Ct.number().optional(),scroll_direction:Ct.enum(["up","down","left","right"]).optional(),start_coordinate:Ct.tuple([Ct.number().int(),Ct.number().int()]).optional(),text:Ct.string().optional()}))),bv=we({id:"anthropic.computer_20250124",inputSchema:vv}),_v=q(()=>H(Pe.discriminatedUnion("command",[Pe.object({command:Pe.literal("view"),path:Pe.string(),view_range:Pe.tuple([Pe.number(),Pe.number()]).optional()}),Pe.object({command:Pe.literal("create"),path:Pe.string(),file_text:Pe.string()}),Pe.object({command:Pe.literal("str_replace"),path:Pe.string(),old_str:Pe.string(),new_str:Pe.string()}),Pe.object({command:Pe.literal("insert"),path:Pe.string(),insert_line:Pe.number(),insert_text:Pe.string()}),Pe.object({command:Pe.literal("delete"),path:Pe.string()}),Pe.object({command:Pe.literal("rename"),old_path:Pe.string(),new_path:Pe.string()})]))),wv=we({id:"anthropic.memory_20250818",inputSchema:_v}),Ev=q(()=>H(pr.object({command:pr.enum(["view","create","str_replace","insert","undo_edit"]),path:pr.string(),file_text:pr.string().optional(),insert_line:pr.number().int().optional(),new_str:pr.string().optional(),old_str:pr.string().optional(),view_range:pr.array(pr.number().int()).optional()}))),Tv=we({id:"anthropic.text_editor_20241022",inputSchema:Ev}),xv=q(()=>H(hr.object({command:hr.enum(["view","create","str_replace","insert","undo_edit"]),path:hr.string(),file_text:hr.string().optional(),insert_line:hr.number().int().optional(),new_str:hr.string().optional(),old_str:hr.string().optional(),view_range:hr.array(hr.number().int()).optional()}))),Sv=we({id:"anthropic.text_editor_20250124",inputSchema:xv}),Cv=q(()=>H(fr.object({command:fr.enum(["view","create","str_replace","insert"]),path:fr.string(),file_text:fr.string().optional(),insert_line:fr.number().int().optional(),new_str:fr.string().optional(),old_str:fr.string().optional(),view_range:fr.array(fr.number().int()).optional()}))),Iv=we({id:"anthropic.text_editor_20250429",inputSchema:Cv}),Av=q(()=>H(Ur.array(Ur.object({type:Ur.literal("tool_reference"),toolName:Ur.string()})))),kv=q(()=>H(Ur.object({query:Ur.string(),limit:Ur.number().optional()}))),Rv=Ze({id:"anthropic.tool_search_bm25_20251119",inputSchema:kv,outputSchema:Av}),Ov=(t={})=>Rv(t),Nv={bash_20241022:hv,bash_20250124:mv,codeExecution_20250522:Qy,codeExecution_20250825:rv,computer_20241022:yv,computer_20250124:bv,memory_20250818:wv,textEditor_20241022:Tv,textEditor_20250124:Sv,textEditor_20250429:Iv,textEditor_20250728:qy,webFetch_20250910:Ky,webSearch_20250305:Vy,toolSearchRegex_20251119:av,toolSearchBm25_20251119:Ov};function ti(t={}){var e,r;let n=(e=dr(Lt({settingValue:t.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(r=t.name)!=null?r:"anthropic.messages",a=()=>lt({"anthropic-version":"2023-06-01","x-api-key":wo({apiKey:t.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...t.headers},`ai-sdk/anthropic/${Oy}`),i=l=>{var c;return new uv(l,{provider:o,baseURL:n,headers:a,fetch:t.fetch,generateId:(c=t.generateId)!=null?c:xt,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(l)};return s.specificationVersion="v3",s.languageModel=i,s.chat=i,s.messages=i,s.embeddingModel=l=>{throw new Ha({modelId:l,modelType:"embeddingModel"})},s.textEmbeddingModel=s.embeddingModel,s.imageModel=l=>{throw new Ha({modelId:l,modelType:"imageModel"})},s.tools=Nv,s}var ZI=ti();function Eu(t){let e=Sn().env?.ANTHROPIC_API_KEY;if(!e)throw new Error("ANTHROPIC_API_KEY not configured in SDK config");return Ee.debug(`Using Anthropic provider: model=${t}`),ti({apiKey:e})(t)}function Tu(t){return{anthropic:{structuredOutputMode:"jsonTool"}}}import{z as mr}from"zod/v4";import{z as Nn}from"zod/v4";import{z as ri}from"zod/v4";import{z as G}from"zod/v4";import{z as je}from"zod/v4";import{z as Kr}from"zod/v4";import{z as Wv}from"zod/v4";import{z as Mn}from"zod/v4";import{z as Zv}from"zod/v4";import{z as ni}from"zod/v4";import{z as tb}from"zod/v4";import{z as oi}from"zod/v4";import{z as Fr}from"zod/v4";var Mv="3.0.8",Pv=q(()=>H(Nn.object({error:Nn.object({code:Nn.number().nullable(),message:Nn.string(),status:Nn.string()})}))),Pn=Qe({errorSchema:Pv,errorToMessage:t=>t.error.message}),Dv=q(()=>H(ri.object({outputDimensionality:ri.number().optional(),taskType:ri.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}))),jv=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"google",providerOptions:n,schema:Dv});if(t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=$e(await Te(this.config.headers),e);if(t.length===1){let{responseHeaders:c,value:p,rawValue:h}=await Fe({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:t[0]}]},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType},failedResponseHandler:Pn,successfulResponseHandler:qe(Uv),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[p.embedding.values],usage:void 0,response:{headers:c,body:h}}}let{responseHeaders:i,value:s,rawValue:l}=await Fe({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:t.map(c=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:c}]},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType}))},failedResponseHandler:Pn,successfulResponseHandler:qe(Lv),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:s.embeddings.map(c=>c.values),usage:void 0,response:{headers:i,body:l}}}},Lv=q(()=>H(mr.object({embeddings:mr.array(mr.object({values:mr.array(mr.number())}))}))),Uv=q(()=>H(mr.object({embedding:mr.object({values:mr.array(mr.number())})})));function xu(t){var e,r,n,o;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let a=(e=t.promptTokenCount)!=null?e:0,i=(r=t.candidatesTokenCount)!=null?r:0,s=(n=t.cachedContentTokenCount)!=null?n:0,l=(o=t.thoughtsTokenCount)!=null?o:0;return{inputTokens:{total:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i+l,text:i,reasoning:l},raw:t}}function Kt(t,e=!0){if(t==null)return;if(Fv(t))return e?void 0:typeof t=="object"&&t.description?{type:"object",description:t.description}:{type:"object"};if(typeof t=="boolean")return{type:"boolean",properties:{}};let{type:r,description:n,required:o,properties:a,items:i,allOf:s,anyOf:l,oneOf:c,format:p,const:h,minLength:m,enum:g}=t,T={};if(n&&(T.description=n),o&&(T.required=o),p&&(T.format=p),h!==void 0&&(T.enum=[h]),r)if(Array.isArray(r)){let y=r.includes("null"),b=r.filter(_=>_!=="null");b.length===0?T.type="null":(T.anyOf=b.map(_=>({type:_})),y&&(T.nullable=!0))}else T.type=r;if(g!==void 0&&(T.enum=g),a!=null&&(T.properties=Object.entries(a).reduce((y,[b,_])=>(y[b]=Kt(_,!1),y),{})),i&&(T.items=Array.isArray(i)?i.map(y=>Kt(y,!1)):Kt(i,!1)),s&&(T.allOf=s.map(y=>Kt(y,!1))),l)if(l.some(y=>typeof y=="object"&&y?.type==="null")){let y=l.filter(b=>!(typeof b=="object"&&b?.type==="null"));if(y.length===1){let b=Kt(y[0],!1);typeof b=="object"&&(T.nullable=!0,Object.assign(T,b))}else T.anyOf=y.map(b=>Kt(b,!1)),T.nullable=!0}else T.anyOf=l.map(y=>Kt(y,!1));return c&&(T.oneOf=c.map(y=>Kt(y,!1))),m!==void 0&&(T.minLength=m),T}function Fv(t){return t!=null&&typeof t=="object"&&t.type==="object"&&(t.properties==null||Object.keys(t.properties).length===0)&&!t.additionalProperties}function Hv(t,e){var r,n,o;let a=[],i=[],s=!0,l=(r=e?.isGemmaModel)!=null?r:!1,c=(n=e?.providerOptionsName)!=null?n:"google";for(let{role:p,content:h}of t)switch(p){case"system":{if(!s)throw new tt({functionality:"system messages are only supported at the beginning of the conversation"});a.push({text:h});break}case"user":{s=!1;let m=[];for(let g of h)switch(g.type){case"text":{m.push({text:g.text});break}case"file":{let T=g.mediaType==="image/*"?"image/jpeg":g.mediaType;m.push(g.data instanceof URL?{fileData:{mimeType:T,fileUri:g.data.toString()}}:{inlineData:{mimeType:T,data:lr(g.data)}});break}}i.push({role:"user",parts:m});break}case"assistant":{s=!1,i.push({role:"model",parts:h.map(m=>{var g;let T=(g=m.providerOptions)==null?void 0:g[c],y=T?.thoughtSignature!=null?String(T.thoughtSignature):void 0;switch(m.type){case"text":return m.text.length===0?void 0:{text:m.text,thoughtSignature:y};case"reasoning":return m.text.length===0?void 0:{text:m.text,thought:!0,thoughtSignature:y};case"file":{if(m.data instanceof URL)throw new tt({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:m.mediaType,data:lr(m.data)},thoughtSignature:y}}case"tool-call":return{functionCall:{name:m.toolName,args:m.input},thoughtSignature:y}}}).filter(m=>m!==void 0)});break}case"tool":{s=!1;let m=[];for(let g of h){if(g.type==="tool-approval-response")continue;let T=g.output;if(T.type==="content")for(let y of T.value)switch(y.type){case"text":m.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:y.text}}});break;case"image-data":m.push({inlineData:{mimeType:y.mediaType,data:y.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:m.push({text:JSON.stringify(y)});break}else m.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:T.type==="execution-denied"?(o=T.reason)!=null?o:"Tool execution denied.":T.value}}})}i.push({role:"user",parts:m});break}}if(l&&a.length>0&&i.length>0&&i[0].role==="user"){let p=a.map(h=>h.text).join(`
|
|
43
|
+
]`;continue}a+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function cu(t,e){var r,n,o,a,i,s;let l={type:"object",additionalProperties:(r=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===yo.ZodString&&((o=t.keyType._def.checks)!=null&&o.length)){let{type:c,...p}=lu(t.keyType._def,e);return{...l,propertyNames:p}}else{if(((a=t.keyType)==null?void 0:a._def.typeName)===yo.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((i=t.keyType)==null?void 0:i._def.typeName)===yo.ZodBranded&&t.keyType._def.type._def.typeName===yo.ZodString&&((s=t.keyType._def.type._def.checks)!=null&&s.length)){let{type:c,...p}=iu(t.keyType._def,e);return{...l,propertyNames:p}}}return l}function Yg(t,e){if(e.mapStrategy==="record")return cu(t,e);let r=Ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||mt(),n=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||mt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Xg(t){let e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),o=Array.from(new Set(n.map(a=>typeof a)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Zg(){return{not:mt()}}function Qg(){return{type:"null"}}var Ba={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ey(t,e){let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ba&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,a)=>{let i=Ba[a._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(a._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((a,i,s)=>s.indexOf(a)===i);return{type:o.length>1?o:o[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(a=>!n.includes(a))],[])};return ty(t,e)}var ty=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Ne(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ry(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ba[t.innerType._def.typeName],"null"]};let r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ny(t){let e={type:"number"};if(!t.checks)return e;for(let r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function oy(t,e){let r={type:"object",properties:{}},n=[],o=t.shape();for(let i in o){let s=o[i];if(s===void 0||s._def===void 0)continue;let l=iy(s),c=Ne(s._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);let a=ay(t,e);return a!==void 0&&(r.additionalProperties=a),r}function ay(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ne(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function iy(t){try{return t.isOptional()}catch{return!0}}var sy=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ne(t.innerType._def,e);let n=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:mt()},n]}:mt()},ly=(t,e)=>{if(e.pipeStrategy==="input")return Ne(t.in._def,e);if(e.pipeStrategy==="output")return Ne(t.out._def,e);let r=Ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function cy(t,e){return Ne(t.type._def,e)}function uy(t,e){let n={type:"array",uniqueItems:!0,items:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function dy(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function py(){return{not:mt()}}function hy(){return mt()}var fy=(t,e)=>Ne(t.innerType._def,e),my=(t,e,r)=>{switch(e){case ke.ZodString:return lu(t,r);case ke.ZodNumber:return ny(t);case ke.ZodObject:return oy(t,r);case ke.ZodBigInt:return Fg(t);case ke.ZodBoolean:return Ug();case ke.ZodDate:return su(t,r);case ke.ZodUndefined:return py();case ke.ZodNull:return Qg();case ke.ZodArray:return Lg(t,r);case ke.ZodUnion:case ke.ZodDiscriminatedUnion:return ey(t,r);case ke.ZodIntersection:return zg(t,r);case ke.ZodTuple:return dy(t,r);case ke.ZodRecord:return cu(t,r);case ke.ZodLiteral:return Wg(t);case ke.ZodEnum:return Bg(t);case ke.ZodNativeEnum:return Xg(t);case ke.ZodNullable:return ry(t,r);case ke.ZodOptional:return sy(t,r);case ke.ZodMap:return Yg(t,r);case ke.ZodSet:return uy(t,r);case ke.ZodLazy:return()=>t.getter()._def;case ke.ZodPromise:return cy(t,r);case ke.ZodNaN:case ke.ZodNever:return Zg();case ke.ZodEffects:return Gg(t,r);case ke.ZodAny:return mt();case ke.ZodUnknown:return hy();case ke.ZodDefault:return $g(t,r);case ke.ZodBranded:return iu(t,r);case ke.ZodReadonly:return fy(t,r);case ke.ZodCatch:return Hg(t,r);case ke.ZodPipeline:return ly(t,r);case ke.ZodFunction:case ke.ZodVoid:case ke.ZodSymbol:return;default:return(n=>{})(e)}},gy=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ne(t,e,r=!1){var n;let o=e.seen.get(t);if(e.override){let l=(n=e.override)==null?void 0:n.call(e,t,e,o,r);if(l!==Pg)return l}if(o&&!r){let l=yy(o,e);if(l!==void 0)return l}let a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);let i=my(t,t.typeName,e),s=typeof i=="function"?Ne(i(),e):i;if(s&&vy(t,e,s),e.postProcess){let l=e.postProcess(s,t,e);return a.jsonSchema=s,l}return a.jsonSchema=s,s}var yy=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gy(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),mt()):e.$refStrategy==="seen"?mt():void 0}},vy=(t,e,r)=>(t.description&&(r.description=t.description),r),by=t=>{let e=Dg(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},_y=(t,e)=>{var r;let n=by(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[p,h])=>{var g;return{...c,[p]:(g=Ne(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0))!=null?g:mt()}},{}):void 0,a=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=(r=Ne(t._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1))!=null?r:mt(),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s);let l=a===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...o,[a]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Va=Symbol.for("vercel.ai.schema");function q(t){let e;return()=>(e==null&&(e=t()),e)}function To(t,{validate:e}={}){return{[Va]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function wy(t){return typeof t=="object"&&t!==null&&Va in t&&t[Va]===!0&&"jsonSchema"in t&&"validate"in t}function ur(t){return t==null?To({properties:{},additionalProperties:!1}):wy(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?H(t):Ey(t):t()}function Ey(t){return To(()=>Ja(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async e=>{let r=await t["~standard"].validate(e);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new Pt({value:e,cause:r.issues})}}})}function Ty(t,e){var r;let n=(r=e?.useReferences)!=null?r:!1;return To(()=>_y(t,{$refStrategy:n?"root":"none"}),{validate:async o=>{let a=await t.safeParseAsync(o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function xy(t,e){var r;let n=(r=e?.useReferences)!=null?r:!1;return To(()=>Ja(Eo.toJSONSchema(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{let a=await Eo.safeParseAsync(t,o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function Sy(t){return"_zod"in t}function H(t,e){return Sy(t)?xy(t,e):Ty(t,e)}async function St({value:t,schema:e}){let r=await nt({value:t,schema:e});if(!r.success)throw Pt.wrap({value:t,cause:r.error});return r.value}async function nt({value:t,schema:e}){let r=ur(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};let n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:Pt.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:Pt.wrap({value:t,cause:n}),rawValue:t}}}async function Cy({text:t,schema:e}){try{let r=au(t);return e==null?r:St({value:r,schema:e})}catch(r){throw Cn.isInstance(r)||Pt.isInstance(r)?r:new Cn({text:t,cause:r})}}async function pt({text:t,schema:e}){try{let r=au(t);return e==null?{success:!0,value:r,rawValue:r}:await nt({value:r,schema:e})}catch(r){return{success:!1,error:Cn.isInstance(r)?r:new Cn({text:t,cause:r}),rawValue:void 0}}}function Iy({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new go).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await pt({text:r,schema:e}))}}))}async function Ve({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;let n=await nt({value:e[t],schema:r});if(!n.success)throw new ho({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var Ay=()=>globalThis.fetch,Ue=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>ky({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i});var ky=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=Ay()})=>{try{let s=await i(t,{method:"POST",headers:lt(e,`ai-sdk/provider-utils/${ru}`,_o()),body:r.content,signal:a}),l=kn(s);if(!s.ok){let c;try{c=await o({response:s,url:t,requestBodyValues:r.values})}catch(p){throw xr(p)||$e.isInstance(p)?p:new $e({message:"Failed to process error response",cause:p,statusCode:s.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(xr(c)||$e.isInstance(c))?c:new $e({message:"Failed to process successful response",cause:c,statusCode:s.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw tu({error:s,url:t,requestBodyValues:r.values})}};function Ee({id:t,inputSchema:e}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider",id:t,args:c,inputSchema:e,outputSchema:n,execute:r,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l})}function Ze({id:t,inputSchema:e,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,...p})=>({type:"provider",id:t,args:p,inputSchema:e,outputSchema:r,execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Te(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var Qe=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{let i=await n.text(),s=kn(n);if(i.trim()==="")return{responseHeaders:s,value:new $e({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{let l=await Cy({text:i,schema:t});return{responseHeaders:s,value:new $e({message:e(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new $e({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},Sr=t=>async({response:e})=>{let r=kn(e);if(e.body==null)throw new wc({});return{responseHeaders:r,value:Iy({stream:e.body,schema:t})}},qe=t=>async({response:e,url:r,requestBodyValues:n})=>{let o=await e.text(),a=await pt({text:o,schema:t}),i=kn(e);if(!a.success)throw new $e({message:"Invalid JSON response",cause:a.error,statusCode:e.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}};function dr(t){return t?.replace(/\/$/,"")}function Ry(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*uu({execute:t,input:e,options:r}){let n=t(e,r);if(Ry(n)){let o;for await(let a of n)o=a,yield{type:"preliminary",output:a};yield{type:"final",output:o}}else yield{type:"final",output:await n}}import{z as Rn}from"zod/v4";import{z as u}from"zod/v4";import{z as re}from"zod/v4";import{z as Ft}from"zod/v4";import{z as ze}from"zod/v4";import{z as Me}from"zod/v4";import{z as Ut}from"zod/v4";import{z as ne}from"zod/v4";import{z as Lr}from"zod/v4";import{z as Za}from"zod/v4";import{z as Qa}from"zod/v4";import{z as On}from"zod/v4";import{z as Ct}from"zod/v4";import{z as Pe}from"zod/v4";import{z as pr}from"zod/v4";import{z as hr}from"zod/v4";import{z as fr}from"zod/v4";import{z as Fr}from"zod/v4";var Oy="3.0.13",Ny=q(()=>H(Rn.object({type:Rn.literal("error"),error:Rn.object({type:Rn.string(),message:Rn.string()})}))),du=Qe({errorSchema:Ny,errorToMessage:t=>t.error.message}),My=q(()=>H(u.object({type:u.literal("message"),id:u.string().nullish(),model:u.string().nullish(),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string(),citations:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])).optional()}),u.object({type:u.literal("thinking"),thinking:u.string(),signature:u.string()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])),stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}))),Py=q(()=>H(u.discriminatedUnion("type",[u.object({type:u.literal("message_start"),message:u.object({id:u.string().nullish(),model:u.string().nullish(),role:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()})])).nullish(),stop_reason:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string()}).nullish()})}),u.object({type:u.literal("content_block_start"),index:u.number(),content_block:u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("thinking"),thinking:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).optional(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])}),u.object({type:u.literal("content_block_delta"),index:u.number(),delta:u.discriminatedUnion("type",[u.object({type:u.literal("input_json_delta"),partial_json:u.string()}),u.object({type:u.literal("text_delta"),text:u.string()}),u.object({type:u.literal("thinking_delta"),thinking:u.string()}),u.object({type:u.literal("signature_delta"),signature:u.string()}),u.object({type:u.literal("citations_delta"),citation:u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])})])}),u.object({type:u.literal("content_block_stop"),index:u.number()}),u.object({type:u.literal("error"),error:u.object({type:u.string(),message:u.string()})}),u.object({type:u.literal("message_delta"),delta:u.object({stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}),usage:u.looseObject({input_tokens:u.number().nullish(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish()})}),u.object({type:u.literal("message_stop")}),u.object({type:u.literal("ping")})]))),Dy=q(()=>H(u.object({signature:u.string().optional(),redactedData:u.string().optional()}))),pu=re.object({citations:re.object({enabled:re.boolean()}).optional(),title:re.string().optional(),context:re.string().optional()}),jy=re.object({sendReasoning:re.boolean().optional(),structuredOutputMode:re.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:re.object({type:re.union([re.literal("enabled"),re.literal("disabled")]),budgetTokens:re.number().optional()}).optional(),disableParallelToolUse:re.boolean().optional(),cacheControl:re.object({type:re.literal("ephemeral"),ttl:re.union([re.literal("5m"),re.literal("1h")]).optional()}).optional(),mcpServers:re.array(re.object({type:re.literal("url"),name:re.string(),url:re.string(),authorizationToken:re.string().nullish(),toolConfiguration:re.object({enabled:re.boolean().nullish(),allowedTools:re.array(re.string()).nullish()}).nullish()})).optional(),container:re.object({id:re.string().optional(),skills:re.array(re.object({type:re.union([re.literal("anthropic"),re.literal("custom")]),skillId:re.string(),version:re.string().optional()})).optional()}).optional(),toolStreaming:re.boolean().optional(),effort:re.enum(["low","medium","high"]).optional(),contextManagement:re.object({edits:re.array(re.discriminatedUnion("type",[re.object({type:re.literal("clear_tool_uses_20250919"),trigger:re.discriminatedUnion("type",[re.object({type:re.literal("input_tokens"),value:re.number()}),re.object({type:re.literal("tool_uses"),value:re.number()})]).optional(),keep:re.object({type:re.literal("tool_uses"),value:re.number()}).optional(),clearAtLeast:re.object({type:re.literal("input_tokens"),value:re.number()}).optional(),clearToolInputs:re.boolean().optional(),excludeTools:re.array(re.string()).optional()}),re.object({type:re.literal("clear_thinking_20251015"),keep:re.union([re.literal("all"),re.object({type:re.literal("thinking_turns"),value:re.number()})]).optional()})]))}).optional()}),hu=4;function Ly(t){var e;let r=t?.anthropic;return(e=r?.cacheControl)!=null?e:r?.cache_control}var ei=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(t,e){let r=Ly(t);if(r){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>hu){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${hu} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},Fy=q(()=>H(Ft.object({maxCharacters:Ft.number().optional()}))),Uy=q(()=>H(Ft.object({command:Ft.enum(["view","create","str_replace","insert"]),path:Ft.string(),file_text:Ft.string().optional(),insert_line:Ft.number().int().optional(),new_str:Ft.string().optional(),old_str:Ft.string().optional(),view_range:Ft.array(Ft.number().int()).optional()}))),Hy=Ee({id:"anthropic.text_editor_20250728",inputSchema:Uy}),qy=(t={})=>Hy(t),$y=q(()=>H(ze.object({maxUses:ze.number().optional(),allowedDomains:ze.array(ze.string()).optional(),blockedDomains:ze.array(ze.string()).optional(),userLocation:ze.object({type:ze.literal("approximate"),city:ze.string().optional(),region:ze.string().optional(),country:ze.string().optional(),timezone:ze.string().optional()}).optional()}))),yu=q(()=>H(ze.array(ze.object({url:ze.string(),title:ze.string().nullable(),pageAge:ze.string().nullable(),encryptedContent:ze.string(),type:ze.literal("web_search_result")})))),Gy=q(()=>H(ze.object({query:ze.string()}))),By=Ze({id:"anthropic.web_search_20250305",inputSchema:Gy,outputSchema:yu,supportsDeferredResults:!0}),Vy=(t={})=>By(t),zy=q(()=>H(Me.object({maxUses:Me.number().optional(),allowedDomains:Me.array(Me.string()).optional(),blockedDomains:Me.array(Me.string()).optional(),citations:Me.object({enabled:Me.boolean()}).optional(),maxContentTokens:Me.number().optional()}))),vu=q(()=>H(Me.object({type:Me.literal("web_fetch_result"),url:Me.string(),content:Me.object({type:Me.literal("document"),title:Me.string().nullable(),citations:Me.object({enabled:Me.boolean()}).optional(),source:Me.union([Me.object({type:Me.literal("base64"),mediaType:Me.literal("application/pdf"),data:Me.string()}),Me.object({type:Me.literal("text"),mediaType:Me.literal("text/plain"),data:Me.string()})])}),retrievedAt:Me.string().nullable()}))),Wy=q(()=>H(Me.object({url:Me.string()}))),Jy=Ze({id:"anthropic.web_fetch_20250910",inputSchema:Wy,outputSchema:vu,supportsDeferredResults:!0}),Ky=(t={})=>Jy(t);async function Yy({tools:t,toolChoice:e,disableParallelToolUse:r,cacheControlValidator:n,supportsStructuredOutput:o}){var a;t=t?.length?t:void 0;let i=[],s=new Set,l=n||new ei;if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};let c=[];for(let h of t)switch(h.type){case"function":{let g=l.getCacheControl(h.providerOptions,{type:"tool definition",canCache:!0}),y=(a=h.providerOptions)==null?void 0:a.anthropic,S=y?.deferLoading,f=y?.allowedCallers;c.push({name:h.name,description:h.description,input_schema:h.inputSchema,cache_control:g,...o===!0&&h.strict!=null?{strict:h.strict}:{},...S!=null?{defer_loading:S}:{},...f!=null?{allowed_callers:f}:{},...h.inputExamples!=null?{input_examples:h.inputExamples.map(b=>b.input)}:{}}),o===!0&&s.add("structured-outputs-2025-11-13"),(h.inputExamples!=null||f!=null)&&s.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(h.id){case"anthropic.code_execution_20250522":{s.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{s.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let g=await St({value:h.args,schema:Fy});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:g.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{s.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{s.add("web-fetch-2025-09-10");let g=await St({value:h.args,schema:zy});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,citations:g.citations,max_content_tokens:g.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let g=await St({value:h.args,schema:$y});c.push({type:"web_search_20250305",name:"web_search",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,user_location:g.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{i.push({type:"unsupported",feature:`provider-defined tool ${h.id}`});break}}break}default:{i.push({type:"unsupported",feature:`tool ${h}`});break}}if(e==null)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:s};let p=e.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};case"tool":return{tools:c,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:s};default:{let h=p;throw new tt({functionality:`tool choice type: ${h}`})}}}function fu(t){var e,r;let n=t.input_tokens,o=t.output_tokens,a=(e=t.cache_creation_input_tokens)!=null?e:0,i=(r=t.cache_read_input_tokens)!=null?r:0;return{inputTokens:{total:n+a+i,noCache:n,cacheRead:i,cacheWrite:a},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:t}}var bu=q(()=>H(Ut.object({type:Ut.literal("code_execution_result"),stdout:Ut.string(),stderr:Ut.string(),return_code:Ut.number(),content:Ut.array(Ut.object({type:Ut.literal("code_execution_output"),file_id:Ut.string()})).optional().default([])}))),Xy=q(()=>H(Ut.object({code:Ut.string()}))),Zy=Ze({id:"anthropic.code_execution_20250522",inputSchema:Xy,outputSchema:bu}),Qy=(t={})=>Zy(t),_u=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("code_execution_result"),stdout:ne.string(),stderr:ne.string(),return_code:ne.number(),content:ne.array(ne.object({type:ne.literal("code_execution_output"),file_id:ne.string()})).optional().default([])}),ne.object({type:ne.literal("bash_code_execution_result"),content:ne.array(ne.object({type:ne.literal("bash_code_execution_output"),file_id:ne.string()})),stdout:ne.string(),stderr:ne.string(),return_code:ne.number()}),ne.object({type:ne.literal("bash_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_view_result"),content:ne.string(),file_type:ne.string(),num_lines:ne.number().nullable(),start_line:ne.number().nullable(),total_lines:ne.number().nullable()}),ne.object({type:ne.literal("text_editor_code_execution_create_result"),is_file_update:ne.boolean()}),ne.object({type:ne.literal("text_editor_code_execution_str_replace_result"),lines:ne.array(ne.string()).nullable(),new_lines:ne.number().nullable(),new_start:ne.number().nullable(),old_lines:ne.number().nullable(),old_start:ne.number().nullable()})]))),ev=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("programmatic-tool-call"),code:ne.string()}),ne.object({type:ne.literal("bash_code_execution"),command:ne.string()}),ne.discriminatedUnion("command",[ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("view"),path:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("create"),path:ne.string(),file_text:ne.string().nullish()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("str_replace"),path:ne.string(),old_str:ne.string(),new_str:ne.string()})])]))),tv=Ze({id:"anthropic.code_execution_20250825",inputSchema:ev,outputSchema:_u,supportsDeferredResults:!0}),rv=(t={})=>tv(t),wu=q(()=>H(Lr.array(Lr.object({type:Lr.literal("tool_reference"),toolName:Lr.string()})))),nv=q(()=>H(Lr.object({pattern:Lr.string(),limit:Lr.number().optional()}))),ov=Ze({id:"anthropic.tool_search_regex_20251119",inputSchema:nv,outputSchema:wu}),av=(t={})=>ov(t);function iv(t){if(typeof t=="string")return Buffer.from(t,"base64").toString("utf-8");if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw t instanceof URL?new tt({functionality:"URL-based text documents are not supported for citations"}):new tt({functionality:`unsupported data type for text documents: ${typeof t}`})}function Ka(t){return t instanceof URL||sv(t)}function sv(t){return typeof t=="string"&&/^https?:\/\//i.test(t)}function Ya(t){return t instanceof URL?t.toString():t}async function lv({prompt:t,sendReasoning:e,warnings:r,cacheControlValidator:n,toolNameMapping:o}){var a,i,s,l,c,p,h,g,y,S,f,b,_,M,B;let Z=new Set,N=cv(t),R=n||new ei,O,ee=[];async function E(X){var W,ue;let V=await Ve({provider:"anthropic",providerOptions:X,schema:pu});return(ue=(W=V?.citations)==null?void 0:W.enabled)!=null?ue:!1}async function Q(X){let W=await Ve({provider:"anthropic",providerOptions:X,schema:pu});return{title:W?.title,context:W?.context}}for(let X=0;X<N.length;X++){let W=N[X],ue=X===N.length-1,V=W.type;switch(V){case"system":{if(O!=null)throw new tt({functionality:"Multiple system messages that are separated by user/assistant messages"});O=W.messages.map(({content:K,providerOptions:me})=>({type:"text",text:K,cache_control:R.getCacheControl(me,{type:"system message",canCache:!0})}));break}case"user":{let K=[];for(let me of W.messages){let{role:j,content:ve}=me;switch(j){case"user":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se],Fe=Se===ve.length-1,z=(a=R.getCacheControl(fe.providerOptions,{type:"user message part",canCache:!0}))!=null?a:Fe?R.getCacheControl(me.providerOptions,{type:"user message",canCache:!0}):void 0;switch(fe.type){case"text":{K.push({type:"text",text:fe.text,cache_control:z});break}case"file":{if(fe.mediaType.startsWith("image/"))K.push({type:"image",source:Ka(fe.data)?{type:"url",url:Ya(fe.data)}:{type:"base64",media_type:fe.mediaType==="image/*"?"image/jpeg":fe.mediaType,data:lr(fe.data)},cache_control:z});else if(fe.mediaType==="application/pdf"){Z.add("pdfs-2024-09-25");let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:Ka(fe.data)?{type:"url",url:Ya(fe.data)}:{type:"base64",media_type:"application/pdf",data:lr(fe.data)},title:(i=be.title)!=null?i:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else if(fe.mediaType==="text/plain"){let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:Ka(fe.data)?{type:"url",url:Ya(fe.data)}:{type:"text",media_type:"text/plain",data:iv(fe.data)},title:(s=be.title)!=null?s:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else throw new tt({functionality:`media type: ${fe.mediaType}`});break}}}break}case"tool":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se];if(fe.type==="tool-approval-response")continue;let Fe=Se===ve.length-1,z=(l=R.getCacheControl(fe.providerOptions,{type:"tool result part",canCache:!0}))!=null?l:Fe?R.getCacheControl(me.providerOptions,{type:"tool result message",canCache:!0}):void 0,U=fe.output,be;switch(U.type){case"content":be=U.value.map(we=>{switch(we.type){case"text":return{type:"text",text:we.text};case"image-data":return{type:"image",source:{type:"base64",media_type:we.mediaType,data:we.data}};case"image-url":return{type:"image",source:{type:"url",url:we.url}};case"file-url":return{type:"document",source:{type:"url",url:we.url}};case"file-data":{if(we.mediaType==="application/pdf")return Z.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:we.mediaType,data:we.data}};r.push({type:"other",message:`unsupported tool content part type: ${we.type} with media type: ${we.mediaType}`});return}default:{r.push({type:"other",message:`unsupported tool content part type: ${we.type}`});return}}}).filter(nu);break;case"text":case"error-text":be=U.value;break;case"execution-denied":be=(c=U.reason)!=null?c:"Tool execution denied.";break;case"json":case"error-json":default:be=JSON.stringify(U.value);break}K.push({type:"tool_result",tool_use_id:fe.toolCallId,content:be,is_error:U.type==="error-text"||U.type==="error-json"?!0:void 0,cache_control:z})}break}default:{let Se=j;throw new Error(`Unsupported role: ${Se}`)}}}ee.push({role:"user",content:K});break}case"assistant":{let K=[],me=new Set;for(let j=0;j<W.messages.length;j++){let ve=W.messages[j],Se=j===W.messages.length-1,{content:fe}=ve;for(let Fe=0;Fe<fe.length;Fe++){let z=fe[Fe],U=Fe===fe.length-1,be=(p=R.getCacheControl(z.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:U?R.getCacheControl(ve.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(z.type){case"text":{K.push({type:"text",text:ue&&Se&&U?z.text.trim():z.text,cache_control:be});break}case"reasoning":{if(e){let we=await Ve({provider:"anthropic",providerOptions:z.providerOptions,schema:Dy});we!=null?we.signature!=null?(R.getCacheControl(z.providerOptions,{type:"thinking block",canCache:!1}),K.push({type:"thinking",thinking:z.text,signature:we.signature})):we.redactedData!=null?(R.getCacheControl(z.providerOptions,{type:"redacted thinking block",canCache:!1}),K.push({type:"redacted_thinking",data:we.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(z.providerExecuted){let ae=o.toProviderToolName(z.toolName);if(((g=(h=z.providerOptions)==null?void 0:h.anthropic)==null?void 0:g.type)==="mcp-tool-use"){me.add(z.toolCallId);let d=(S=(y=z.providerOptions)==null?void 0:y.anthropic)==null?void 0:S.serverName;if(d==null||typeof d!="string"){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}K.push({type:"mcp_tool_use",id:z.toolCallId,name:z.toolName,input:z.input,server_name:d,cache_control:be})}else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&typeof z.input.type=="string"&&(z.input.type==="bash_code_execution"||z.input.type==="text_editor_code_execution"))K.push({type:"server_tool_use",id:z.toolCallId,name:z.input.type,input:z.input,cache_control:be});else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&z.input.type==="programmatic-tool-call"){let{type:d,...m}=z.input;K.push({type:"server_tool_use",id:z.toolCallId,name:"code_execution",input:m,cache_control:be})}else ae==="code_execution"||ae==="web_fetch"||ae==="web_search"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):ae==="tool_search_tool_regex"||ae==="tool_search_tool_bm25"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):r.push({type:"other",message:`provider executed tool call for tool ${z.toolName} is not supported`});break}let we=(f=z.providerOptions)==null?void 0:f.anthropic,de=we?.caller?we.caller.type==="code_execution_20250825"&&we.caller.toolId?{type:"code_execution_20250825",tool_id:we.caller.toolId}:we.caller.type==="direct"?{type:"direct"}:void 0:void 0;K.push({type:"tool_use",id:z.toolCallId,name:z.toolName,input:z.input,...de&&{caller:de},cache_control:be});break}case"tool-result":{let we=o.toProviderToolName(z.toolName);if(me.has(z.toolCallId)){let de=z.output;if(de.type!=="json"&&de.type!=="error-json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}K.push({type:"mcp_tool_result",tool_use_id:z.toolCallId,is_error:de.type==="error-json",content:de.value,cache_control:be})}else if(we==="code_execution"){let de=z.output;if(de.type==="error-text"||de.type==="error-json"){let ae={};try{typeof de.value=="string"?ae=JSON.parse(de.value):typeof de.value=="object"&&de.value!==null&&(ae=de.value)}catch{}ae.type==="code_execution_tool_result_error"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=ae.errorCode)!=null?b:"unknown"},cache_control:be}):K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:{type:"bash_code_execution_tool_result_error",error_code:(_=ae.errorCode)!=null?_:"unknown"}});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}if(de.value==null||typeof de.value!="object"||!("type"in de.value)||typeof de.value.type!="string"){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${z.toolName}`});break}if(de.value.type==="code_execution_result"){let ae=await St({value:de.value,schema:bu});K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(M=ae.content)!=null?M:[]},cache_control:be})}else{let ae=await St({value:de.value,schema:_u});ae.type==="code_execution_result"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(B=ae.content)!=null?B:[]},cache_control:be}):ae.type==="bash_code_execution_result"||ae.type==="bash_code_execution_tool_result_error"?K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae}):K.push({type:"text_editor_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae})}break}if(we==="web_fetch"){let de=z.output;if(de.type==="error-json"){let Y=JSON.parse(de.value);K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:Y.errorCode},cache_control:be});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:vu});K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_result",url:ae.url,retrieved_at:ae.retrievedAt,content:{type:"document",title:ae.content.title,citations:ae.content.citations,source:{type:ae.content.source.type,media_type:ae.content.source.mediaType,data:ae.content.source.data}}},cache_control:be});break}if(we==="web_search"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:yu});K.push({type:"web_search_tool_result",tool_use_id:z.toolCallId,content:ae.map(Y=>({url:Y.url,title:Y.title,page_age:Y.pageAge,encrypted_content:Y.encryptedContent,type:Y.type})),cache_control:be});break}if(we==="tool_search_tool_regex"||we==="tool_search_tool_bm25"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let Y=(await St({value:de.value,schema:wu})).map(d=>({type:"tool_reference",tool_name:d.toolName}));K.push({type:"tool_search_tool_result",tool_use_id:z.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:Y},cache_control:be});break}r.push({type:"other",message:`provider executed tool result for tool ${z.toolName} is not supported`});break}}}}ee.push({role:"assistant",content:K});break}default:{let K=V;throw new Error(`content type: ${K}`)}}}return{prompt:{system:O,messages:ee},betas:Z}}function cv(t){let e=[],r;for(let n of t){let{role:o}=n;switch(o){case"system":{r?.type!=="system"&&(r={type:"system",messages:[]},e.push(r)),r.messages.push(n);break}case"assistant":{r?.type!=="assistant"&&(r={type:"assistant",messages:[]},e.push(r)),r.messages.push(n);break}case"user":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}case"tool":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}}return e}function Xa({finishReason:t,isJsonResponseFromTool:e}){switch(t){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}function mu(t,e,r){var n;if(t.type!=="page_location"&&t.type!=="char_location")return;let o=e[t.document_index];if(o)return{type:"source",sourceType:"document",id:r(),mediaType:o.mediaType,title:(n=t.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:t.type==="page_location"?{citedText:t.cited_text,startPageNumber:t.start_page_number,endPageNumber:t.end_page_number}:{citedText:t.cited_text,startCharIndex:t.start_char_index,endCharIndex:t.end_char_index}}}}var uv=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}supportsUrl(t){return t.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({userSuppliedBetas:t,prompt:e,maxOutputTokens:r,temperature:n,topP:o,topK:a,frequencyPenalty:i,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:h,toolChoice:g,providerOptions:y,stream:S}){var f,b,_,M,B,Z;let N=[];i!=null&&N.push({type:"unsupported",feature:"frequencyPenalty"}),s!=null&&N.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&N.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(N.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(N.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),c?.type==="json"&&c.schema==null&&N.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let R=await Ve({provider:"anthropic",providerOptions:y,schema:jy}),{maxOutputTokens:O,supportsStructuredOutput:ee,isKnownModel:E}=dv(this.modelId),Q=((f=this.config.supportsNativeStructuredOutput)!=null?f:!0)&&ee,X=(b=R?.structuredOutputMode)!=null?b:"auto",W=X==="outputFormat"||X==="auto"&&Q,ue=c?.type==="json"&&c.schema!=null&&!W?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,V=R?.contextManagement,K=new ei,me=Xc({tools:h,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:j,betas:ve}=await lv({prompt:e,sendReasoning:(_=R?.sendReasoning)!=null?_:!0,warnings:N,cacheControlValidator:K,toolNameMapping:me}),Se=((M=R?.thinking)==null?void 0:M.type)==="enabled",fe=(B=R?.thinking)==null?void 0:B.budgetTokens,Fe=r??O,z={model:this.modelId,max_tokens:Fe,temperature:n,top_k:a,top_p:o,stop_sequences:l,...Se&&{thinking:{type:"enabled",budget_tokens:fe}},...R?.effort&&{output_config:{effort:R.effort}},...W&&c?.type==="json"&&c.schema!=null&&{output_format:{type:"json_schema",schema:c.schema}},...R?.mcpServers&&R.mcpServers.length>0&&{mcp_servers:R.mcpServers.map(d=>({type:d.type,name:d.name,url:d.url,authorization_token:d.authorizationToken,tool_configuration:d.toolConfiguration?{allowed_tools:d.toolConfiguration.allowedTools,enabled:d.toolConfiguration.enabled}:void 0}))},...R?.container&&{container:R.container.skills&&R.container.skills.length>0?{id:R.container.id,skills:R.container.skills.map(d=>({type:d.type,skill_id:d.skillId,version:d.version}))}:R.container.id},system:j.system,messages:j.messages,...V&&{context_management:{edits:V.edits.map(d=>{let m=d.type;switch(m){case"clear_tool_uses_20250919":return{type:d.type,...d.trigger!==void 0&&{trigger:d.trigger},...d.keep!==void 0&&{keep:d.keep},...d.clearAtLeast!==void 0&&{clear_at_least:d.clearAtLeast},...d.clearToolInputs!==void 0&&{clear_tool_inputs:d.clearToolInputs},...d.excludeTools!==void 0&&{exclude_tools:d.excludeTools}};case"clear_thinking_20251015":return{type:d.type,...d.keep!==void 0&&{keep:d.keep}};default:N.push({type:"other",message:`Unknown context management strategy: ${m}`});return}}).filter(d=>d!==void 0)}}};Se?(fe==null&&(N.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),z.thinking={type:"enabled",budget_tokens:1024},fe=1024),z.temperature!=null&&(z.temperature=void 0,N.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),a!=null&&(z.top_k=void 0,N.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(z.top_p=void 0,N.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),z.max_tokens=Fe+(fe??0)):o!=null&&n!=null&&(N.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),z.top_p=void 0),E&&z.max_tokens>O&&(r!=null&&N.push({type:"unsupported",feature:"maxOutputTokens",details:`${z.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${O} max output tokens. The max output tokens have been limited to ${O}.`}),z.max_tokens=O),R?.mcpServers&&R.mcpServers.length>0&&ve.add("mcp-client-2025-04-04"),V&&ve.add("context-management-2025-06-27"),R?.container&&R.container.skills&&R.container.skills.length>0&&(ve.add("code-execution-2025-08-25"),ve.add("skills-2025-10-02"),ve.add("files-api-2025-04-14"),h?.some(d=>d.type==="provider"&&d.id==="anthropic.code_execution_20250825")||N.push({type:"other",message:"code execution tool is required when using skills"})),R?.effort&&ve.add("effort-2025-11-24"),S&&((Z=R?.toolStreaming)==null||Z)&&ve.add("fine-grained-tool-streaming-2025-05-14"),W&&c?.type==="json"&&c.schema!=null&&ve.add("structured-outputs-2025-11-13");let{tools:be,toolChoice:we,toolWarnings:de,betas:ae}=await Yy(ue!=null?{tools:[...h??[],ue],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:K,supportsStructuredOutput:Q}:{tools:h??[],toolChoice:g,disableParallelToolUse:R?.disableParallelToolUse,cacheControlValidator:K,supportsStructuredOutput:Q}),Y=K.getWarnings();return{args:{...z,tools:be,tool_choice:we,stream:S===!0?!0:void 0},warnings:[...N,...de,...Y],betas:new Set([...ve,...ae,...t]),usesJsonResponseTool:ue!=null,toolNameMapping:me}}async getHeaders({betas:t,headers:e}){return Ge(await Te(this.config.headers),e,t.size>0?{"anthropic-beta":Array.from(t).join(",")}:{})}async getBetasFromHeaders(t){var e,r;let o=(e=(await Te(this.config.headers))["anthropic-beta"])!=null?e:"",a=(r=t?.["anthropic-beta"])!=null?r:"";return new Set([...o.toLowerCase().split(","),...a.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(t){var e,r,n;return(n=(r=(e=this.config).buildRequestUrl)==null?void 0:r.call(e,this.config.baseURL,t))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(t){var e,r,n;return(n=(r=(e=this.config).transformRequestBody)==null?void 0:r.call(e,t))!=null?n:t}extractCitationDocuments(t){let e=r=>{var n,o;if(r.type!=="file"||r.mediaType!=="application/pdf"&&r.mediaType!=="text/plain")return!1;let a=(n=r.providerOptions)==null?void 0:n.anthropic,i=a?.citations;return(o=i?.enabled)!=null?o:!1};return t.filter(r=>r.role==="user").flatMap(r=>r.content).filter(e).map(r=>{var n;let o=r;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(t){var e,r,n,o,a,i,s,l,c,p,h;let{args:g,warnings:y,betas:S,usesJsonResponseTool:f,toolNameMapping:b}=await this.getArgs({...t,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),_=this.extractCitationDocuments(t.prompt),{responseHeaders:M,value:B,rawValue:Z}=await Ue({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:S,headers:t.headers}),body:this.transformRequestBody(g),failedResponseHandler:du,successfulResponseHandler:qe(My),abortSignal:t.abortSignal,fetch:this.config.fetch}),N=[],R={},O={},ee=!1;for(let E of B.content)switch(E.type){case"text":{if(!f&&(N.push({type:"text",text:E.text}),E.citations))for(let Q of E.citations){let X=mu(Q,_,this.generateId);X&&N.push(X)}break}case"thinking":{N.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{N.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"tool_use":{if(f&&E.name==="json")ee=!0,N.push({type:"text",text:JSON.stringify(E.input)});else{let X=E.caller,W=X?{type:X.type,toolId:"tool_id"in X?X.tool_id:void 0}:void 0;N.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...W&&{providerMetadata:{anthropic:{caller:W}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let Q=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(Q),providerExecuted:!0})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(O[E.id]=E.name,N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{R[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},N.push(R[E.id]);break}case"mcp_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:R[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:R[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}}):E.content.type==="web_fetch_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),result:E.content.map(Q=>{var X;return{url:Q.url,title:Q.title,pageAge:(X=Q.page_age)!=null?X:null,encryptedContent:Q.encrypted_content,type:Q.type}})});for(let Q of E.content)N.push({type:"source",sourceType:"url",id:this.generateId(),url:Q.url,title:Q.title,providerMetadata:{anthropic:{pageAge:(e=Q.page_age)!=null?e:null}}})}else N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(r=E.content.content)!=null?r:[]}}):E.content.type==="code_execution_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let Q=(n=O[E.tool_use_id])!=null?n:"tool_search_tool_regex";E.content.type==="tool_search_tool_search_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),result:E.content.tool_references.map(X=>({type:X.type,toolName:X.tool_name}))}):N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:N,finishReason:{unified:Xa({finishReason:B.stop_reason,isJsonResponseFromTool:ee}),raw:(o=B.stop_reason)!=null?o:void 0},usage:fu(B.usage),request:{body:g},response:{id:(a=B.id)!=null?a:void 0,modelId:(i=B.model)!=null?i:void 0,headers:M,body:Z},warnings:y,providerMetadata:{anthropic:{usage:B.usage,cacheCreationInputTokens:(s=B.usage.cache_creation_input_tokens)!=null?s:null,stopSequence:(l=B.stop_sequence)!=null?l:null,container:B.container?{expiresAt:B.container.expires_at,id:B.container.id,skills:(p=(c=B.container.skills)==null?void 0:c.map(E=>({type:E.type,skillId:E.skill_id,version:E.version})))!=null?p:null}:null,contextManagement:(h=gu(B.context_management))!=null?h:null}}}}async doStream(t){var e,r;let{args:n,warnings:o,betas:a,usesJsonResponseTool:i,toolNameMapping:s}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),l=this.extractCitationDocuments(t.prompt),c=this.buildRequestUrl(!0),{responseHeaders:p,value:h}=await Ue({url:c,headers:await this.getHeaders({betas:a,headers:t.headers}),body:this.transformRequestBody(n),failedResponseHandler:du,successfulResponseHandler:Sr(Py),abortSignal:t.abortSignal,fetch:this.config.fetch}),g={unified:"other",raw:void 0},y={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},S={},f={},b={},_=null,M,B=null,Z=null,N=null,R=!1,O,ee=this.generateId,E=h.pipeThrough(new TransformStream({start(ue){ue.enqueue({type:"stream-start",warnings:o})},transform(ue,V){var K,me,j,ve,Se,fe,Fe,z,U,be,we,de,ae;if(t.includeRawChunks&&V.enqueue({type:"raw",rawValue:ue.rawValue}),!ue.success){V.enqueue({type:"error",error:ue.error});return}let Y=ue.value;switch(Y.type){case"ping":return;case"content_block_start":{let d=Y.content_block,m=d.type;switch(O=m,m){case"text":{if(i)return;S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});return}case"thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index)});return}case"redacted_thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index),providerMetadata:{anthropic:{redactedData:d.data}}});return}case"tool_use":{if(i&&d.name==="json")R=!0,S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});else{let C=d.caller,x=C?{type:C.type,toolId:"tool_id"in C?C.tool_id:void 0}:void 0,D=d.input&&Object.keys(d.input).length>0?JSON.stringify(d.input):"";S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:D,firstDelta:D.length===0,...x&&{caller:x}},V.enqueue({type:"tool-input-start",id:d.id,toolName:d.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(d.name)){let v=d.name==="text_editor_code_execution"||d.name==="bash_code_execution"?"code_execution":d.name,C=s.toCustomToolName(v);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:C,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:C,providerExecuted:!0})}else if(d.name==="tool_search_tool_regex"||d.name==="tool_search_tool_bm25"){b[d.id]=d.name;let v=s.toCustomToolName(d.name);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:v,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:v,providerExecuted:!0})}return}case"web_fetch_tool_result":{d.content.type==="web_fetch_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:d.content.url,retrievedAt:d.content.retrieved_at,content:{type:d.content.content.type,title:d.content.content.title,citations:d.content.content.citations,source:{type:d.content.content.source.type,mediaType:d.content.content.source.media_type,data:d.content.content.source.data}}}}):d.content.type==="web_fetch_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:d.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(d.content)){V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),result:d.content.map(v=>{var C;return{url:v.url,title:v.title,pageAge:(C=v.page_age)!=null?C:null,encryptedContent:v.encrypted_content,type:v.type}})});for(let v of d.content)V.enqueue({type:"source",sourceType:"url",id:ee(),url:v.url,title:v.title,providerMetadata:{anthropic:{pageAge:(K=v.page_age)!=null?K:null}}})}else V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:d.content.error_code}});return}case"code_execution_tool_result":{d.content.type==="code_execution_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:{type:d.content.type,stdout:d.content.stdout,stderr:d.content.stderr,return_code:d.content.return_code,content:(me=d.content.content)!=null?me:[]}}):d.content.type==="code_execution_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:d.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:d.content});return}case"tool_search_tool_result":{let v=(j=b[d.tool_use_id])!=null?j:"tool_search_tool_regex";d.content.type==="tool_search_tool_search_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),result:d.content.tool_references.map(C=>({type:C.type,toolName:C.tool_name}))}):V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:d.content.error_code}});return}case"mcp_tool_use":{f[d.id]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:JSON.stringify(d.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:d.server_name}}},V.enqueue(f[d.id]);return}case"mcp_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:f[d.tool_use_id].toolName,isError:d.is_error,result:d.content,dynamic:!0,providerMetadata:f[d.tool_use_id].providerMetadata});return}default:{let v=m;throw new Error(`Unsupported content block type: ${v}`)}}}case"content_block_stop":{if(S[Y.index]!=null){let d=S[Y.index];switch(d.type){case"text":{V.enqueue({type:"text-end",id:String(Y.index)});break}case"reasoning":{V.enqueue({type:"reasoning-end",id:String(Y.index)});break}case"tool-call":if(!(i&&d.toolName==="json")){V.enqueue({type:"tool-input-end",id:d.toolCallId});let v=d.input===""?"{}":d.input;if(d.providerToolName==="code_execution")try{let C=JSON.parse(v);C!=null&&typeof C=="object"&&"code"in C&&!("type"in C)&&(v=JSON.stringify({type:"programmatic-tool-call",...C}))}catch{}V.enqueue({type:"tool-call",toolCallId:d.toolCallId,toolName:d.toolName,input:v,providerExecuted:d.providerExecuted,...d.caller&&{providerMetadata:{anthropic:{caller:d.caller}}}})}break}delete S[Y.index]}O=void 0;return}case"content_block_delta":{let d=Y.delta.type;switch(d){case"text_delta":{if(i)return;V.enqueue({type:"text-delta",id:String(Y.index),delta:Y.delta.text});return}case"thinking_delta":{V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:Y.delta.thinking});return}case"signature_delta":{O==="thinking"&&V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:"",providerMetadata:{anthropic:{signature:Y.delta.signature}}});return}case"input_json_delta":{let m=S[Y.index],v=Y.delta.partial_json;if(v.length===0)return;if(R){if(m?.type!=="text")return;V.enqueue({type:"text-delta",id:String(Y.index),delta:v})}else{if(m?.type!=="tool-call")return;m.firstDelta&&(m.providerToolName==="bash_code_execution"||m.providerToolName==="text_editor_code_execution")&&(v=`{"type": "${m.providerToolName}",${v.substring(1)}`),V.enqueue({type:"tool-input-delta",id:m.toolCallId,delta:v}),m.input+=v,m.firstDelta=!1}return}case"citations_delta":{let m=Y.delta.citation,v=mu(m,l,ee);v&&V.enqueue(v);return}default:{let m=d;throw new Error(`Unsupported delta type: ${m}`)}}}case"message_start":{if(y.input_tokens=Y.message.usage.input_tokens,y.cache_read_input_tokens=(ve=Y.message.usage.cache_read_input_tokens)!=null?ve:0,y.cache_creation_input_tokens=(Se=Y.message.usage.cache_creation_input_tokens)!=null?Se:0,M={...Y.message.usage},B=(fe=Y.message.usage.cache_creation_input_tokens)!=null?fe:null,Y.message.container!=null&&(N={expiresAt:Y.message.container.expires_at,id:Y.message.container.id,skills:null}),Y.message.stop_reason!=null&&(g={unified:Xa({finishReason:Y.message.stop_reason,isJsonResponseFromTool:R}),raw:Y.message.stop_reason}),V.enqueue({type:"response-metadata",id:(Fe=Y.message.id)!=null?Fe:void 0,modelId:(z=Y.message.model)!=null?z:void 0}),Y.message.content!=null)for(let d=0;d<Y.message.content.length;d++){let m=Y.message.content[d];if(m.type==="tool_use"){let v=m.caller,C=v?{type:v.type,toolId:"tool_id"in v?v.tool_id:void 0}:void 0;V.enqueue({type:"tool-input-start",id:m.id,toolName:m.name});let x=JSON.stringify((U=m.input)!=null?U:{});V.enqueue({type:"tool-input-delta",id:m.id,delta:x}),V.enqueue({type:"tool-input-end",id:m.id}),V.enqueue({type:"tool-call",toolCallId:m.id,toolName:m.name,input:x,...C&&{providerMetadata:{anthropic:{caller:C}}}})}}return}case"message_delta":{Y.usage.input_tokens!=null&&y.input_tokens!==Y.usage.input_tokens&&(y.input_tokens=Y.usage.input_tokens),y.output_tokens=Y.usage.output_tokens,g={unified:Xa({finishReason:Y.delta.stop_reason,isJsonResponseFromTool:R}),raw:(be=Y.delta.stop_reason)!=null?be:void 0},Z=(we=Y.delta.stop_sequence)!=null?we:null,N=Y.delta.container!=null?{expiresAt:Y.delta.container.expires_at,id:Y.delta.container.id,skills:(ae=(de=Y.delta.container.skills)==null?void 0:de.map(d=>({type:d.type,skillId:d.skill_id,version:d.version})))!=null?ae:null}:null,Y.delta.context_management&&(_=gu(Y.delta.context_management)),M={...M,...Y.usage};return}case"message_stop":{V.enqueue({type:"finish",finishReason:g,usage:fu(y),providerMetadata:{anthropic:{usage:M??null,cacheCreationInputTokens:B,stopSequence:Z,container:N,contextManagement:_}}});return}case"error":{V.enqueue({type:"error",error:Y.error});return}default:{let d=Y;throw new Error(`Unsupported chunk type: ${d}`)}}}})),[Q,X]=E.tee(),W=Q.getReader();try{await W.read();let ue=await W.read();if(((e=ue.value)==null?void 0:e.type)==="raw"&&(ue=await W.read()),((r=ue.value)==null?void 0:r.type)==="error"){let V=ue.value.error;throw new $e({message:V.message,url:c,requestBodyValues:n,statusCode:V.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(V),isRetryable:V.type==="overloaded_error"})}}finally{W.cancel().catch(()=>{}),W.releaseLock()}return{stream:X,request:{body:n},response:{headers:p}}}};function dv(t){return t.includes("claude-sonnet-4-5")||t.includes("claude-opus-4-5")||t.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-sonnet-4-")||t.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function gu(t){return t?{appliedEdits:t.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens}}}).filter(e=>e!==void 0)}:null}var pv=q(()=>H(Za.object({command:Za.string(),restart:Za.boolean().optional()}))),hv=Ee({id:"anthropic.bash_20241022",inputSchema:pv}),fv=q(()=>H(Qa.object({command:Qa.string(),restart:Qa.boolean().optional()}))),mv=Ee({id:"anthropic.bash_20250124",inputSchema:fv}),gv=q(()=>H(On.object({action:On.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:On.array(On.number().int()).optional(),text:On.string().optional()}))),yv=Ee({id:"anthropic.computer_20241022",inputSchema:gv}),vv=q(()=>H(Ct.object({action:Ct.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ct.tuple([Ct.number().int(),Ct.number().int()]).optional(),duration:Ct.number().optional(),scroll_amount:Ct.number().optional(),scroll_direction:Ct.enum(["up","down","left","right"]).optional(),start_coordinate:Ct.tuple([Ct.number().int(),Ct.number().int()]).optional(),text:Ct.string().optional()}))),bv=Ee({id:"anthropic.computer_20250124",inputSchema:vv}),_v=q(()=>H(Pe.discriminatedUnion("command",[Pe.object({command:Pe.literal("view"),path:Pe.string(),view_range:Pe.tuple([Pe.number(),Pe.number()]).optional()}),Pe.object({command:Pe.literal("create"),path:Pe.string(),file_text:Pe.string()}),Pe.object({command:Pe.literal("str_replace"),path:Pe.string(),old_str:Pe.string(),new_str:Pe.string()}),Pe.object({command:Pe.literal("insert"),path:Pe.string(),insert_line:Pe.number(),insert_text:Pe.string()}),Pe.object({command:Pe.literal("delete"),path:Pe.string()}),Pe.object({command:Pe.literal("rename"),old_path:Pe.string(),new_path:Pe.string()})]))),wv=Ee({id:"anthropic.memory_20250818",inputSchema:_v}),Ev=q(()=>H(pr.object({command:pr.enum(["view","create","str_replace","insert","undo_edit"]),path:pr.string(),file_text:pr.string().optional(),insert_line:pr.number().int().optional(),new_str:pr.string().optional(),old_str:pr.string().optional(),view_range:pr.array(pr.number().int()).optional()}))),Tv=Ee({id:"anthropic.text_editor_20241022",inputSchema:Ev}),xv=q(()=>H(hr.object({command:hr.enum(["view","create","str_replace","insert","undo_edit"]),path:hr.string(),file_text:hr.string().optional(),insert_line:hr.number().int().optional(),new_str:hr.string().optional(),old_str:hr.string().optional(),view_range:hr.array(hr.number().int()).optional()}))),Sv=Ee({id:"anthropic.text_editor_20250124",inputSchema:xv}),Cv=q(()=>H(fr.object({command:fr.enum(["view","create","str_replace","insert"]),path:fr.string(),file_text:fr.string().optional(),insert_line:fr.number().int().optional(),new_str:fr.string().optional(),old_str:fr.string().optional(),view_range:fr.array(fr.number().int()).optional()}))),Iv=Ee({id:"anthropic.text_editor_20250429",inputSchema:Cv}),Av=q(()=>H(Fr.array(Fr.object({type:Fr.literal("tool_reference"),toolName:Fr.string()})))),kv=q(()=>H(Fr.object({query:Fr.string(),limit:Fr.number().optional()}))),Rv=Ze({id:"anthropic.tool_search_bm25_20251119",inputSchema:kv,outputSchema:Av}),Ov=(t={})=>Rv(t),Nv={bash_20241022:hv,bash_20250124:mv,codeExecution_20250522:Qy,codeExecution_20250825:rv,computer_20241022:yv,computer_20250124:bv,memory_20250818:wv,textEditor_20241022:Tv,textEditor_20250124:Sv,textEditor_20250429:Iv,textEditor_20250728:qy,webFetch_20250910:Ky,webSearch_20250305:Vy,toolSearchRegex_20251119:av,toolSearchBm25_20251119:Ov};function ti(t={}){var e,r;let n=(e=dr(Lt({settingValue:t.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(r=t.name)!=null?r:"anthropic.messages",a=()=>lt({"anthropic-version":"2023-06-01","x-api-key":wo({apiKey:t.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...t.headers},`ai-sdk/anthropic/${Oy}`),i=l=>{var c;return new uv(l,{provider:o,baseURL:n,headers:a,fetch:t.fetch,generateId:(c=t.generateId)!=null?c:xt,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(l)};return s.specificationVersion="v3",s.languageModel=i,s.chat=i,s.messages=i,s.embeddingModel=l=>{throw new Ha({modelId:l,modelType:"embeddingModel"})},s.textEmbeddingModel=s.embeddingModel,s.imageModel=l=>{throw new Ha({modelId:l,modelType:"imageModel"})},s.tools=Nv,s}var ZI=ti();function Eu(t){let e=Sn().env?.ANTHROPIC_API_KEY;if(!e)throw new Error("ANTHROPIC_API_KEY not configured in SDK config");return ce.debug(`Using Anthropic provider: model=${t}`),ti({apiKey:e})(t)}function Tu(t){return{anthropic:{structuredOutputMode:"jsonTool"}}}import{z as mr}from"zod/v4";import{z as Nn}from"zod/v4";import{z as ri}from"zod/v4";import{z as $}from"zod/v4";import{z as je}from"zod/v4";import{z as Kr}from"zod/v4";import{z as Wv}from"zod/v4";import{z as Mn}from"zod/v4";import{z as Zv}from"zod/v4";import{z as ni}from"zod/v4";import{z as tb}from"zod/v4";import{z as oi}from"zod/v4";import{z as Ur}from"zod/v4";var Mv="3.0.8",Pv=q(()=>H(Nn.object({error:Nn.object({code:Nn.number().nullable(),message:Nn.string(),status:Nn.string()})}))),Pn=Qe({errorSchema:Pv,errorToMessage:t=>t.error.message}),Dv=q(()=>H(ri.object({outputDimensionality:ri.number().optional(),taskType:ri.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}))),jv=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"google",providerOptions:n,schema:Dv});if(t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=Ge(await Te(this.config.headers),e);if(t.length===1){let{responseHeaders:c,value:p,rawValue:h}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:t[0]}]},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType},failedResponseHandler:Pn,successfulResponseHandler:qe(Fv),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[p.embedding.values],usage:void 0,response:{headers:c,body:h}}}let{responseHeaders:i,value:s,rawValue:l}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:t.map(c=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:c}]},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType}))},failedResponseHandler:Pn,successfulResponseHandler:qe(Lv),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:s.embeddings.map(c=>c.values),usage:void 0,response:{headers:i,body:l}}}},Lv=q(()=>H(mr.object({embeddings:mr.array(mr.object({values:mr.array(mr.number())}))}))),Fv=q(()=>H(mr.object({embedding:mr.object({values:mr.array(mr.number())})})));function xu(t){var e,r,n,o;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let a=(e=t.promptTokenCount)!=null?e:0,i=(r=t.candidatesTokenCount)!=null?r:0,s=(n=t.cachedContentTokenCount)!=null?n:0,l=(o=t.thoughtsTokenCount)!=null?o:0;return{inputTokens:{total:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i+l,text:i,reasoning:l},raw:t}}function Kt(t,e=!0){if(t==null)return;if(Uv(t))return e?void 0:typeof t=="object"&&t.description?{type:"object",description:t.description}:{type:"object"};if(typeof t=="boolean")return{type:"boolean",properties:{}};let{type:r,description:n,required:o,properties:a,items:i,allOf:s,anyOf:l,oneOf:c,format:p,const:h,minLength:g,enum:y}=t,S={};if(n&&(S.description=n),o&&(S.required=o),p&&(S.format=p),h!==void 0&&(S.enum=[h]),r)if(Array.isArray(r)){let f=r.includes("null"),b=r.filter(_=>_!=="null");b.length===0?S.type="null":(S.anyOf=b.map(_=>({type:_})),f&&(S.nullable=!0))}else S.type=r;if(y!==void 0&&(S.enum=y),a!=null&&(S.properties=Object.entries(a).reduce((f,[b,_])=>(f[b]=Kt(_,!1),f),{})),i&&(S.items=Array.isArray(i)?i.map(f=>Kt(f,!1)):Kt(i,!1)),s&&(S.allOf=s.map(f=>Kt(f,!1))),l)if(l.some(f=>typeof f=="object"&&f?.type==="null")){let f=l.filter(b=>!(typeof b=="object"&&b?.type==="null"));if(f.length===1){let b=Kt(f[0],!1);typeof b=="object"&&(S.nullable=!0,Object.assign(S,b))}else S.anyOf=f.map(b=>Kt(b,!1)),S.nullable=!0}else S.anyOf=l.map(f=>Kt(f,!1));return c&&(S.oneOf=c.map(f=>Kt(f,!1))),g!==void 0&&(S.minLength=g),S}function Uv(t){return t!=null&&typeof t=="object"&&t.type==="object"&&(t.properties==null||Object.keys(t.properties).length===0)&&!t.additionalProperties}function Hv(t,e){var r,n,o;let a=[],i=[],s=!0,l=(r=e?.isGemmaModel)!=null?r:!1,c=(n=e?.providerOptionsName)!=null?n:"google";for(let{role:p,content:h}of t)switch(p){case"system":{if(!s)throw new tt({functionality:"system messages are only supported at the beginning of the conversation"});a.push({text:h});break}case"user":{s=!1;let g=[];for(let y of h)switch(y.type){case"text":{g.push({text:y.text});break}case"file":{let S=y.mediaType==="image/*"?"image/jpeg":y.mediaType;g.push(y.data instanceof URL?{fileData:{mimeType:S,fileUri:y.data.toString()}}:{inlineData:{mimeType:S,data:lr(y.data)}});break}}i.push({role:"user",parts:g});break}case"assistant":{s=!1,i.push({role:"model",parts:h.map(g=>{var y;let S=(y=g.providerOptions)==null?void 0:y[c],f=S?.thoughtSignature!=null?String(S.thoughtSignature):void 0;switch(g.type){case"text":return g.text.length===0?void 0:{text:g.text,thoughtSignature:f};case"reasoning":return g.text.length===0?void 0:{text:g.text,thought:!0,thoughtSignature:f};case"file":{if(g.data instanceof URL)throw new tt({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:g.mediaType,data:lr(g.data)},thoughtSignature:f}}case"tool-call":return{functionCall:{name:g.toolName,args:g.input},thoughtSignature:f}}}).filter(g=>g!==void 0)});break}case"tool":{s=!1;let g=[];for(let y of h){if(y.type==="tool-approval-response")continue;let S=y.output;if(S.type==="content")for(let f of S.value)switch(f.type){case"text":g.push({functionResponse:{name:y.toolName,response:{name:y.toolName,content:f.text}}});break;case"image-data":g.push({inlineData:{mimeType:f.mediaType,data:f.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:g.push({text:JSON.stringify(f)});break}else g.push({functionResponse:{name:y.toolName,response:{name:y.toolName,content:S.type==="execution-denied"?(o=S.reason)!=null?o:"Tool execution denied.":S.value}}})}i.push({role:"user",parts:g});break}}if(l&&a.length>0&&i.length>0&&i[0].role==="user"){let p=a.map(h=>h.text).join(`
|
|
44
44
|
|
|
45
45
|
`);i[0].parts.unshift({text:p+`
|
|
46
46
|
|
|
47
|
-
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function Su(t){return t.includes("/")?t:`models/${t}`}var Cu=q(()=>H(je.object({responseModalities:je.array(je.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:je.object({thinkingBudget:je.number().optional(),includeThoughts:je.boolean().optional(),thinkingLevel:je.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:je.string().optional(),structuredOutputs:je.boolean().optional(),safetySettings:je.array(je.object({category:je.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:je.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:je.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:je.boolean().optional(),labels:je.record(je.string(),je.string()).optional(),mediaResolution:je.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:je.object({aspectRatio:je.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:je.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:je.object({latLng:je.object({latitude:je.number(),longitude:je.number()}).optional()}).optional()})));function qv({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(g=>g===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(g=>g.type==="function"),p=t.some(g=>g.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let g=[];return t.filter(y=>y.type==="provider").forEach(y=>{switch(y.id){case"google.google_search":i?g.push({googleSearch:{}}):s?g.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:y.args.mode,dynamicThreshold:y.args.dynamicThreshold}}}):g.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?g.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?g.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?g.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?g.push({fileSearch:{...y.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?g.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:y.args.ragCorpus},similarity_top_k:y.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?g.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`});break}}),{tools:g.length>0?g:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let g of t)switch(g.type){case"function":h.push({name:g.name,description:(n=g.description)!=null?n:"",parameters:Kt(g.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${g.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let m=e.type;switch(m){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let g=m;throw new tt({functionality:`tool choice type: ${g}`})}}}function Iu({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var Gv=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:m}){var g;let T=[],y=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:y,providerOptions:m,schema:Cu});b==null&&y!=="google"&&(b=await Ve({provider:"google",providerOptions:m,schema:Cu})),p?.some(R=>R.type==="provider"&&R.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&T.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:D,systemInstruction:V}=Hv(t,{isGemmaModel:_,providerOptionsName:y}),{tools:X,toolConfig:P,toolWarnings:N}=qv({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((g=b?.structuredOutputs)==null||g)?Kt(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:D,systemInstruction:_?void 0:V,safetySettings:b?.safetySettings,tools:X,toolConfig:b?.retrievalConfig?{...P,retrievalConfig:b.retrievalConfig}:P,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...T,...N],providerOptionsName:y}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:m}=await this.getArgs(t),g=$e(await Te(this.config.headers),t.headers),{responseHeaders:T,value:y,rawValue:b}=await Fe({url:`${this.config.baseURL}/${Su(this.modelId)}:generateContent`,headers:g,body:p,failedResponseHandler:Pn,successfulResponseHandler:qe(Bv),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=y.candidates[0],D=[],V=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],X=y.usageMetadata,P;for(let R of V)if("executableCode"in R&&((n=R.executableCode)!=null&&n.code)){let Q=this.config.generateId();P=Q,D.push({type:"tool-call",toolCallId:Q,toolName:"code_execution",input:JSON.stringify(R.executableCode),providerExecuted:!0})}else"codeExecutionResult"in R&&R.codeExecutionResult?(D.push({type:"tool-result",toolCallId:P,toolName:"code_execution",result:{outcome:R.codeExecutionResult.outcome,output:R.codeExecutionResult.output}}),P=void 0):"text"in R&&R.text!=null&&R.text.length>0?D.push({type:R.thought===!0?"reasoning":"text",text:R.text,providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0}):"functionCall"in R?D.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:R.functionCall.name,input:JSON.stringify(R.functionCall.args),providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0}):"inlineData"in R&&D.push({type:"file",data:R.inlineData.data,mediaType:R.inlineData.mimeType,providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0});let N=(o=Au({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let R of N)D.push(R);return{content:D,finishReason:{unified:Iu({finishReason:_.finishReason,hasToolCalls:D.some(R=>R.type==="tool-call"&&!R.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:xu(X),warnings:h,providerMetadata:{[m]:{promptFeedback:(i=y.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:X??null}},request:{body:p},response:{headers:T,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=$e(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Fe({url:`${this.config.baseURL}/${Su(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:Pn,successfulResponseHandler:Sr(Vv),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,m=null,g=null,T=0,y=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,D){var V,X,P,N,R,Q,E;if(t.includeRawChunks&&D.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){D.enqueue({type:"error",error:_.error});return}let re=_.value,Z=re.usageMetadata;Z!=null&&(l=Z);let Y=(V=re.candidates)==null?void 0:V[0];if(Y==null)return;let ce=Y.content,B=Au({groundingMetadata:Y.groundingMetadata,generateId:p});if(B!=null)for(let J of B)J.sourceType==="url"&&!y.has(J.url)&&(y.add(J.url),D.enqueue(J));if(ce!=null){let J=(X=ce.parts)!=null?X:[];for(let j of J)if("executableCode"in j&&((P=j.executableCode)!=null&&P.code)){let ye=p();b=ye,D.enqueue({type:"tool-call",toolCallId:ye,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ye=b;ye&&(D.enqueue({type:"tool-result",toolCallId:ye,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(m!==null&&(D.enqueue({type:"text-end",id:m}),m=null),g===null&&(g=String(T++),D.enqueue({type:"reasoning-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),D.enqueue({type:"reasoning-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(g!==null&&(D.enqueue({type:"reasoning-end",id:g}),g=null),m===null&&(m=String(T++),D.enqueue({type:"text-start",id:m,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),D.enqueue({type:"text-delta",id:m,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&D.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let fe=$v({parts:ce.parts,generateId:p,providerOptionsName:n});if(fe!=null)for(let j of fe)D.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}Y.finishReason!=null&&(s={unified:Iu({finishReason:Y.finishReason,hasToolCalls:h}),raw:Y.finishReason},c={[n]:{promptFeedback:(N=re.promptFeedback)!=null?N:null,groundingMetadata:(R=Y.groundingMetadata)!=null?R:null,urlContextMetadata:(Q=Y.urlContextMetadata)!=null?Q:null,safetyRatings:(E=Y.safetyRatings)!=null?E:null}},Z!=null&&(c[n].usageMetadata=Z))},flush(_){m!==null&&_.enqueue({type:"text-end",id:m}),g!==null&&_.enqueue({type:"reasoning-end",id:g}),_.enqueue({type:"finish",finishReason:s,usage:xu(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function $v({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function Au({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",m="application/octet-stream",g;c.endsWith(".pdf")?(m="application/pdf",g=c.split("/").pop()):c.endsWith(".txt")?(m="text/plain",g=c.split("/").pop()):c.endsWith(".docx")?(m="application/vnd.openxmlformats-officedocument.wordprocessingml.document",g=c.split("/").pop()):c.endsWith(".doc")?(m="application/msword",g=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(m="text/markdown"),g=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:m,title:h,filename:g})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var ku=()=>G.object({webSearchQueries:G.array(G.string()).nullish(),retrievalQueries:G.array(G.string()).nullish(),searchEntryPoint:G.object({renderedContent:G.string()}).nullish(),groundingChunks:G.array(G.object({web:G.object({uri:G.string(),title:G.string().nullish()}).nullish(),retrievedContext:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),fileSearchStore:G.string().nullish()}).nullish(),maps:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),placeId:G.string().nullish()}).nullish()})).nullish(),groundingSupports:G.array(G.object({segment:G.object({startIndex:G.number().nullish(),endIndex:G.number().nullish(),text:G.string().nullish()}),segment_text:G.string().nullish(),groundingChunkIndices:G.array(G.number()).nullish(),supportChunkIndices:G.array(G.number()).nullish(),confidenceScores:G.array(G.number()).nullish(),confidenceScore:G.array(G.number()).nullish()})).nullish(),retrievalMetadata:G.union([G.object({webDynamicRetrievalScore:G.number()}),G.object({})]).nullish()}),Ru=()=>G.object({parts:G.array(G.union([G.object({functionCall:G.object({name:G.string(),args:G.unknown()}),thoughtSignature:G.string().nullish()}),G.object({inlineData:G.object({mimeType:G.string(),data:G.string()}),thoughtSignature:G.string().nullish()}),G.object({executableCode:G.object({language:G.string(),code:G.string()}).nullish(),codeExecutionResult:G.object({outcome:G.string(),output:G.string()}).nullish(),text:G.string().nullish(),thought:G.boolean().nullish(),thoughtSignature:G.string().nullish()})])).nullish()}),xo=()=>G.object({category:G.string().nullish(),probability:G.string().nullish(),probabilityScore:G.number().nullish(),severity:G.string().nullish(),severityScore:G.number().nullish(),blocked:G.boolean().nullish()}),Ou=G.object({cachedContentTokenCount:G.number().nullish(),thoughtsTokenCount:G.number().nullish(),promptTokenCount:G.number().nullish(),candidatesTokenCount:G.number().nullish(),totalTokenCount:G.number().nullish(),trafficType:G.string().nullish()}),Nu=()=>G.object({urlMetadata:G.array(G.object({retrievedUrl:G.string(),urlRetrievalStatus:G.string()}))}),Bv=q(()=>H(G.object({candidates:G.array(G.object({content:Ru().nullish().or(G.object({}).strict()),finishReason:G.string().nullish(),safetyRatings:G.array(xo()).nullish(),groundingMetadata:ku().nullish(),urlContextMetadata:Nu().nullish()})),usageMetadata:Ou.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(xo()).nullish()}).nullish()}))),Vv=q(()=>H(G.object({candidates:G.array(G.object({content:Ru().nullish(),finishReason:G.string().nullish(),safetyRatings:G.array(xo()).nullish(),groundingMetadata:ku().nullish(),urlContextMetadata:Nu().nullish()})).nullish(),usageMetadata:Ou.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(xo()).nullish()}).nullish()}))),zv=Ze({id:"google.code_execution",inputSchema:Kr.object({language:Kr.string().describe("The programming language of the code."),code:Kr.string().describe("The code to be executed.")}),outputSchema:Kr.object({outcome:Kr.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:Kr.string().describe("The output from the code execution.")})}),Jv=we({id:"google.enterprise_web_search",inputSchema:q(()=>H(Wv.object({})))}),Kv=Mn.object({fileSearchStoreNames:Mn.array(Mn.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:Mn.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:Mn.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),Yv=q(()=>H(Kv)),Xv=we({id:"google.file_search",inputSchema:Yv}),Qv=we({id:"google.google_maps",inputSchema:q(()=>H(Zv.object({})))}),eb=we({id:"google.google_search",inputSchema:q(()=>H(ni.object({mode:ni.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ni.number().default(1)})))}),rb=we({id:"google.url_context",inputSchema:q(()=>H(tb.object({})))}),nb=we({id:"google.vertex_rag_store",inputSchema:oi.object({ragCorpus:oi.string(),topK:oi.number().optional()})}),ob={googleSearch:eb,enterpriseWebSearch:Jv,googleMaps:Qv,urlContext:rb,fileSearch:Xv,codeExecution:zv,vertexRagStore:nb},ab=class{constructor(t,e,r){this.modelId=t,this.settings=e,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=this.settings.maxImagesPerCall)!=null?t:4}get provider(){return this.config.provider}async doGenerate(t){var e,r,n;let{prompt:o,n:a=1,size:i,aspectRatio:s="1:1",seed:l,providerOptions:c,headers:p,abortSignal:h,files:m,mask:g}=t,T=[];if(m!=null&&m.length>0)throw new Error("Google Generative AI does not support image editing. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(g!=null)throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");i!=null&&T.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),l!=null&&T.push({type:"unsupported",feature:"seed",details:"This model does not support the `seed` option through this provider."});let y=await Ve({provider:"google",providerOptions:c,schema:sb}),b=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,_={sampleCount:a};s!=null&&(_.aspectRatio=s),y&&Object.assign(_,y);let D={instances:[{prompt:o}],parameters:_},{responseHeaders:V,value:X}=await Fe({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:$e(await Te(this.config.headers),p),body:D,failedResponseHandler:Pn,successfulResponseHandler:qe(ib),abortSignal:h,fetch:this.config.fetch});return{images:X.predictions.map(P=>P.bytesBase64Encoded),warnings:T??[],providerMetadata:{google:{images:X.predictions.map(P=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:V}}}},ib=q(()=>H(Fr.object({predictions:Fr.array(Fr.object({bytesBase64Encoded:Fr.string()})).default([])}))),sb=q(()=>H(Fr.object({personGeneration:Fr.enum(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Fr.enum(["1:1","3:4","4:3","9:16","16:9"]).nullish()})));function ai(t={}){var e,r;let n=(e=dr(t.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",o=(r=t.name)!=null?r:"google.generative-ai",a=()=>lt({"x-goog-api-key":wo({apiKey:t.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...t.headers},`ai-sdk/google/${Mv}`),i=p=>{var h;return new Gv(p,{provider:o,baseURL:n,headers:a,generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:t.fetch})},s=p=>new jv(p,{provider:o,baseURL:n,headers:a,fetch:t.fetch}),l=(p,h={})=>new ab(p,h,{provider:o,baseURL:n,headers:a,fetch:t.fetch}),c=function(p){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.chat=i,c.generativeAI=i,c.embedding=s,c.embeddingModel=s,c.textEmbedding=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=ob,c}var LA=ai();var Dh=Ua(bh(),1);import{z as $}from"zod/v4";import{z as to}from"zod/v4";import{z as Le}from"zod/v4";import{z as yn}from"zod/v4";import{z as kT}from"zod/v4";import{z as ro}from"zod/v4";import{z as PT}from"zod/v4";import{z as ol}from"zod/v4";import{z as LT}from"zod/v4";import{z as al}from"zod/v4";function _h(t){var e,r,n,o;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let a=(e=t.promptTokenCount)!=null?e:0,i=(r=t.candidatesTokenCount)!=null?r:0,s=(n=t.cachedContentTokenCount)!=null?n:0,l=(o=t.thoughtsTokenCount)!=null?o:0;return{inputTokens:{total:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i+l,text:i,reasoning:l},raw:t}}function or(t,e=!0){if(t==null)return;if(wT(t))return e?void 0:typeof t=="object"&&t.description?{type:"object",description:t.description}:{type:"object"};if(typeof t=="boolean")return{type:"boolean",properties:{}};let{type:r,description:n,required:o,properties:a,items:i,allOf:s,anyOf:l,oneOf:c,format:p,const:h,minLength:m,enum:g}=t,T={};if(n&&(T.description=n),o&&(T.required=o),p&&(T.format=p),h!==void 0&&(T.enum=[h]),r)if(Array.isArray(r)){let y=r.includes("null"),b=r.filter(_=>_!=="null");b.length===0?T.type="null":(T.anyOf=b.map(_=>({type:_})),y&&(T.nullable=!0))}else T.type=r;if(g!==void 0&&(T.enum=g),a!=null&&(T.properties=Object.entries(a).reduce((y,[b,_])=>(y[b]=or(_,!1),y),{})),i&&(T.items=Array.isArray(i)?i.map(y=>or(y,!1)):or(i,!1)),s&&(T.allOf=s.map(y=>or(y,!1))),l)if(l.some(y=>typeof y=="object"&&y?.type==="null")){let y=l.filter(b=>!(typeof b=="object"&&b?.type==="null"));if(y.length===1){let b=or(y[0],!1);typeof b=="object"&&(T.nullable=!0,Object.assign(T,b))}else T.anyOf=y.map(b=>or(b,!1)),T.nullable=!0}else T.anyOf=l.map(y=>or(y,!1));return c&&(T.oneOf=c.map(y=>or(y,!1))),m!==void 0&&(T.minLength=m),T}function wT(t){return t!=null&&typeof t=="object"&&t.type==="object"&&(t.properties==null||Object.keys(t.properties).length===0)&&!t.additionalProperties}function ET(t,e){var r,n,o;let a=[],i=[],s=!0,l=(r=e?.isGemmaModel)!=null?r:!1,c=(n=e?.providerOptionsName)!=null?n:"google";for(let{role:p,content:h}of t)switch(p){case"system":{if(!s)throw new tt({functionality:"system messages are only supported at the beginning of the conversation"});a.push({text:h});break}case"user":{s=!1;let m=[];for(let g of h)switch(g.type){case"text":{m.push({text:g.text});break}case"file":{let T=g.mediaType==="image/*"?"image/jpeg":g.mediaType;m.push(g.data instanceof URL?{fileData:{mimeType:T,fileUri:g.data.toString()}}:{inlineData:{mimeType:T,data:lr(g.data)}});break}}i.push({role:"user",parts:m});break}case"assistant":{s=!1,i.push({role:"model",parts:h.map(m=>{var g;let T=(g=m.providerOptions)==null?void 0:g[c],y=T?.thoughtSignature!=null?String(T.thoughtSignature):void 0;switch(m.type){case"text":return m.text.length===0?void 0:{text:m.text,thoughtSignature:y};case"reasoning":return m.text.length===0?void 0:{text:m.text,thought:!0,thoughtSignature:y};case"file":{if(m.data instanceof URL)throw new tt({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:m.mediaType,data:lr(m.data)},thoughtSignature:y}}case"tool-call":return{functionCall:{name:m.toolName,args:m.input},thoughtSignature:y}}}).filter(m=>m!==void 0)});break}case"tool":{s=!1;let m=[];for(let g of h){if(g.type==="tool-approval-response")continue;let T=g.output;if(T.type==="content")for(let y of T.value)switch(y.type){case"text":m.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:y.text}}});break;case"image-data":m.push({inlineData:{mimeType:y.mediaType,data:y.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:m.push({text:JSON.stringify(y)});break}else m.push({functionResponse:{name:g.toolName,response:{name:g.toolName,content:T.type==="execution-denied"?(o=T.reason)!=null?o:"Tool execution denied.":T.value}}})}i.push({role:"user",parts:m});break}}if(l&&a.length>0&&i.length>0&&i[0].role==="user"){let p=a.map(h=>h.text).join(`
|
|
47
|
+
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function Su(t){return t.includes("/")?t:`models/${t}`}var Cu=q(()=>H(je.object({responseModalities:je.array(je.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:je.object({thinkingBudget:je.number().optional(),includeThoughts:je.boolean().optional(),thinkingLevel:je.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:je.string().optional(),structuredOutputs:je.boolean().optional(),safetySettings:je.array(je.object({category:je.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:je.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:je.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:je.boolean().optional(),labels:je.record(je.string(),je.string()).optional(),mediaResolution:je.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:je.object({aspectRatio:je.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:je.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:je.object({latLng:je.object({latitude:je.number(),longitude:je.number()}).optional()}).optional()})));function qv({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(y=>y===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(y=>y.type==="function"),p=t.some(y=>y.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let y=[];return t.filter(f=>f.type==="provider").forEach(f=>{switch(f.id){case"google.google_search":i?y.push({googleSearch:{}}):s?y.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:f.args.mode,dynamicThreshold:f.args.dynamicThreshold}}}):y.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?y.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?y.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?y.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?y.push({fileSearch:{...f.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?y.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:f.args.ragCorpus},similarity_top_k:f.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?y.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`});break}}),{tools:y.length>0?y:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let y of t)switch(y.type){case"function":h.push({name:y.name,description:(n=y.description)!=null?n:"",parameters:Kt(y.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${y.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let g=e.type;switch(g){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let y=g;throw new tt({functionality:`tool choice type: ${y}`})}}}function Iu({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var $v=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:g}){var y;let S=[],f=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:f,providerOptions:g,schema:Cu});b==null&&f!=="google"&&(b=await Ve({provider:"google",providerOptions:g,schema:Cu})),p?.some(O=>O.type==="provider"&&O.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&S.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:M,systemInstruction:B}=Hv(t,{isGemmaModel:_,providerOptionsName:f}),{tools:Z,toolConfig:N,toolWarnings:R}=qv({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((y=b?.structuredOutputs)==null||y)?Kt(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:M,systemInstruction:_?void 0:B,safetySettings:b?.safetySettings,tools:Z,toolConfig:b?.retrievalConfig?{...N,retrievalConfig:b.retrievalConfig}:N,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...S,...R],providerOptionsName:f}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:g}=await this.getArgs(t),y=Ge(await Te(this.config.headers),t.headers),{responseHeaders:S,value:f,rawValue:b}=await Ue({url:`${this.config.baseURL}/${Su(this.modelId)}:generateContent`,headers:y,body:p,failedResponseHandler:Pn,successfulResponseHandler:qe(Bv),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=f.candidates[0],M=[],B=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],Z=f.usageMetadata,N;for(let O of B)if("executableCode"in O&&((n=O.executableCode)!=null&&n.code)){let ee=this.config.generateId();N=ee,M.push({type:"tool-call",toolCallId:ee,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else"codeExecutionResult"in O&&O.codeExecutionResult?(M.push({type:"tool-result",toolCallId:N,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:O.codeExecutionResult.output}}),N=void 0):"text"in O&&O.text!=null&&O.text.length>0?M.push({type:O.thought===!0?"reasoning":"text",text:O.text,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"functionCall"in O?M.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:O.functionCall.name,input:JSON.stringify(O.functionCall.args),providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"inlineData"in O&&M.push({type:"file",data:O.inlineData.data,mediaType:O.inlineData.mimeType,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0});let R=(o=Au({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let O of R)M.push(O);return{content:M,finishReason:{unified:Iu({finishReason:_.finishReason,hasToolCalls:M.some(O=>O.type==="tool-call"&&!O.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:xu(Z),warnings:h,providerMetadata:{[g]:{promptFeedback:(i=f.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:Z??null}},request:{body:p},response:{headers:S,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=Ge(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Ue({url:`${this.config.baseURL}/${Su(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:Pn,successfulResponseHandler:Sr(Vv),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,g=null,y=null,S=0,f=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,M){var B,Z,N,R,O,ee,E;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){M.enqueue({type:"error",error:_.error});return}let Q=_.value,X=Q.usageMetadata;X!=null&&(l=X);let W=(B=Q.candidates)==null?void 0:B[0];if(W==null)return;let ue=W.content,V=Au({groundingMetadata:W.groundingMetadata,generateId:p});if(V!=null)for(let K of V)K.sourceType==="url"&&!f.has(K.url)&&(f.add(K.url),M.enqueue(K));if(ue!=null){let K=(Z=ue.parts)!=null?Z:[];for(let j of K)if("executableCode"in j&&((N=j.executableCode)!=null&&N.code)){let ve=p();b=ve,M.enqueue({type:"tool-call",toolCallId:ve,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ve=b;ve&&(M.enqueue({type:"tool-result",toolCallId:ve,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(g!==null&&(M.enqueue({type:"text-end",id:g}),g=null),y===null&&(y=String(S++),M.enqueue({type:"reasoning-start",id:y,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"reasoning-delta",id:y,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(y!==null&&(M.enqueue({type:"reasoning-end",id:y}),y=null),g===null&&(g=String(S++),M.enqueue({type:"text-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"text-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&M.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let me=Gv({parts:ue.parts,generateId:p,providerOptionsName:n});if(me!=null)for(let j of me)M.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}W.finishReason!=null&&(s={unified:Iu({finishReason:W.finishReason,hasToolCalls:h}),raw:W.finishReason},c={[n]:{promptFeedback:(R=Q.promptFeedback)!=null?R:null,groundingMetadata:(O=W.groundingMetadata)!=null?O:null,urlContextMetadata:(ee=W.urlContextMetadata)!=null?ee:null,safetyRatings:(E=W.safetyRatings)!=null?E:null}},X!=null&&(c[n].usageMetadata=X))},flush(_){g!==null&&_.enqueue({type:"text-end",id:g}),y!==null&&_.enqueue({type:"reasoning-end",id:y}),_.enqueue({type:"finish",finishReason:s,usage:xu(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function Gv({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function Au({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",g="application/octet-stream",y;c.endsWith(".pdf")?(g="application/pdf",y=c.split("/").pop()):c.endsWith(".txt")?(g="text/plain",y=c.split("/").pop()):c.endsWith(".docx")?(g="application/vnd.openxmlformats-officedocument.wordprocessingml.document",y=c.split("/").pop()):c.endsWith(".doc")?(g="application/msword",y=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(g="text/markdown"),y=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:g,title:h,filename:y})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var ku=()=>$.object({webSearchQueries:$.array($.string()).nullish(),retrievalQueries:$.array($.string()).nullish(),searchEntryPoint:$.object({renderedContent:$.string()}).nullish(),groundingChunks:$.array($.object({web:$.object({uri:$.string(),title:$.string().nullish()}).nullish(),retrievedContext:$.object({uri:$.string().nullish(),title:$.string().nullish(),text:$.string().nullish(),fileSearchStore:$.string().nullish()}).nullish(),maps:$.object({uri:$.string().nullish(),title:$.string().nullish(),text:$.string().nullish(),placeId:$.string().nullish()}).nullish()})).nullish(),groundingSupports:$.array($.object({segment:$.object({startIndex:$.number().nullish(),endIndex:$.number().nullish(),text:$.string().nullish()}),segment_text:$.string().nullish(),groundingChunkIndices:$.array($.number()).nullish(),supportChunkIndices:$.array($.number()).nullish(),confidenceScores:$.array($.number()).nullish(),confidenceScore:$.array($.number()).nullish()})).nullish(),retrievalMetadata:$.union([$.object({webDynamicRetrievalScore:$.number()}),$.object({})]).nullish()}),Ru=()=>$.object({parts:$.array($.union([$.object({functionCall:$.object({name:$.string(),args:$.unknown()}),thoughtSignature:$.string().nullish()}),$.object({inlineData:$.object({mimeType:$.string(),data:$.string()}),thoughtSignature:$.string().nullish()}),$.object({executableCode:$.object({language:$.string(),code:$.string()}).nullish(),codeExecutionResult:$.object({outcome:$.string(),output:$.string()}).nullish(),text:$.string().nullish(),thought:$.boolean().nullish(),thoughtSignature:$.string().nullish()})])).nullish()}),xo=()=>$.object({category:$.string().nullish(),probability:$.string().nullish(),probabilityScore:$.number().nullish(),severity:$.string().nullish(),severityScore:$.number().nullish(),blocked:$.boolean().nullish()}),Ou=$.object({cachedContentTokenCount:$.number().nullish(),thoughtsTokenCount:$.number().nullish(),promptTokenCount:$.number().nullish(),candidatesTokenCount:$.number().nullish(),totalTokenCount:$.number().nullish(),trafficType:$.string().nullish()}),Nu=()=>$.object({urlMetadata:$.array($.object({retrievedUrl:$.string(),urlRetrievalStatus:$.string()}))}),Bv=q(()=>H($.object({candidates:$.array($.object({content:Ru().nullish().or($.object({}).strict()),finishReason:$.string().nullish(),safetyRatings:$.array(xo()).nullish(),groundingMetadata:ku().nullish(),urlContextMetadata:Nu().nullish()})),usageMetadata:Ou.nullish(),promptFeedback:$.object({blockReason:$.string().nullish(),safetyRatings:$.array(xo()).nullish()}).nullish()}))),Vv=q(()=>H($.object({candidates:$.array($.object({content:Ru().nullish(),finishReason:$.string().nullish(),safetyRatings:$.array(xo()).nullish(),groundingMetadata:ku().nullish(),urlContextMetadata:Nu().nullish()})).nullish(),usageMetadata:Ou.nullish(),promptFeedback:$.object({blockReason:$.string().nullish(),safetyRatings:$.array(xo()).nullish()}).nullish()}))),zv=Ze({id:"google.code_execution",inputSchema:Kr.object({language:Kr.string().describe("The programming language of the code."),code:Kr.string().describe("The code to be executed.")}),outputSchema:Kr.object({outcome:Kr.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:Kr.string().describe("The output from the code execution.")})}),Jv=Ee({id:"google.enterprise_web_search",inputSchema:q(()=>H(Wv.object({})))}),Kv=Mn.object({fileSearchStoreNames:Mn.array(Mn.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:Mn.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:Mn.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),Yv=q(()=>H(Kv)),Xv=Ee({id:"google.file_search",inputSchema:Yv}),Qv=Ee({id:"google.google_maps",inputSchema:q(()=>H(Zv.object({})))}),eb=Ee({id:"google.google_search",inputSchema:q(()=>H(ni.object({mode:ni.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ni.number().default(1)})))}),rb=Ee({id:"google.url_context",inputSchema:q(()=>H(tb.object({})))}),nb=Ee({id:"google.vertex_rag_store",inputSchema:oi.object({ragCorpus:oi.string(),topK:oi.number().optional()})}),ob={googleSearch:eb,enterpriseWebSearch:Jv,googleMaps:Qv,urlContext:rb,fileSearch:Xv,codeExecution:zv,vertexRagStore:nb},ab=class{constructor(t,e,r){this.modelId=t,this.settings=e,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=this.settings.maxImagesPerCall)!=null?t:4}get provider(){return this.config.provider}async doGenerate(t){var e,r,n;let{prompt:o,n:a=1,size:i,aspectRatio:s="1:1",seed:l,providerOptions:c,headers:p,abortSignal:h,files:g,mask:y}=t,S=[];if(g!=null&&g.length>0)throw new Error("Google Generative AI does not support image editing. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(y!=null)throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");i!=null&&S.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),l!=null&&S.push({type:"unsupported",feature:"seed",details:"This model does not support the `seed` option through this provider."});let f=await Ve({provider:"google",providerOptions:c,schema:sb}),b=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,_={sampleCount:a};s!=null&&(_.aspectRatio=s),f&&Object.assign(_,f);let M={instances:[{prompt:o}],parameters:_},{responseHeaders:B,value:Z}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Ge(await Te(this.config.headers),p),body:M,failedResponseHandler:Pn,successfulResponseHandler:qe(ib),abortSignal:h,fetch:this.config.fetch});return{images:Z.predictions.map(N=>N.bytesBase64Encoded),warnings:S??[],providerMetadata:{google:{images:Z.predictions.map(N=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:B}}}},ib=q(()=>H(Ur.object({predictions:Ur.array(Ur.object({bytesBase64Encoded:Ur.string()})).default([])}))),sb=q(()=>H(Ur.object({personGeneration:Ur.enum(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Ur.enum(["1:1","3:4","4:3","9:16","16:9"]).nullish()})));function ai(t={}){var e,r;let n=(e=dr(t.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",o=(r=t.name)!=null?r:"google.generative-ai",a=()=>lt({"x-goog-api-key":wo({apiKey:t.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...t.headers},`ai-sdk/google/${Mv}`),i=p=>{var h;return new $v(p,{provider:o,baseURL:n,headers:a,generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:t.fetch})},s=p=>new jv(p,{provider:o,baseURL:n,headers:a,fetch:t.fetch}),l=(p,h={})=>new ab(p,h,{provider:o,baseURL:n,headers:a,fetch:t.fetch}),c=function(p){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.chat=i,c.generativeAI=i,c.embedding=s,c.embeddingModel=s,c.textEmbedding=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=ob,c}var LA=ai();var Dh=Fa(bh(),1);import{z as G}from"zod/v4";import{z as to}from"zod/v4";import{z as Le}from"zod/v4";import{z as yn}from"zod/v4";import{z as kT}from"zod/v4";import{z as ro}from"zod/v4";import{z as PT}from"zod/v4";import{z as ol}from"zod/v4";import{z as LT}from"zod/v4";import{z as al}from"zod/v4";function _h(t){var e,r,n,o;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let a=(e=t.promptTokenCount)!=null?e:0,i=(r=t.candidatesTokenCount)!=null?r:0,s=(n=t.cachedContentTokenCount)!=null?n:0,l=(o=t.thoughtsTokenCount)!=null?o:0;return{inputTokens:{total:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i+l,text:i,reasoning:l},raw:t}}function or(t,e=!0){if(t==null)return;if(wT(t))return e?void 0:typeof t=="object"&&t.description?{type:"object",description:t.description}:{type:"object"};if(typeof t=="boolean")return{type:"boolean",properties:{}};let{type:r,description:n,required:o,properties:a,items:i,allOf:s,anyOf:l,oneOf:c,format:p,const:h,minLength:g,enum:y}=t,S={};if(n&&(S.description=n),o&&(S.required=o),p&&(S.format=p),h!==void 0&&(S.enum=[h]),r)if(Array.isArray(r)){let f=r.includes("null"),b=r.filter(_=>_!=="null");b.length===0?S.type="null":(S.anyOf=b.map(_=>({type:_})),f&&(S.nullable=!0))}else S.type=r;if(y!==void 0&&(S.enum=y),a!=null&&(S.properties=Object.entries(a).reduce((f,[b,_])=>(f[b]=or(_,!1),f),{})),i&&(S.items=Array.isArray(i)?i.map(f=>or(f,!1)):or(i,!1)),s&&(S.allOf=s.map(f=>or(f,!1))),l)if(l.some(f=>typeof f=="object"&&f?.type==="null")){let f=l.filter(b=>!(typeof b=="object"&&b?.type==="null"));if(f.length===1){let b=or(f[0],!1);typeof b=="object"&&(S.nullable=!0,Object.assign(S,b))}else S.anyOf=f.map(b=>or(b,!1)),S.nullable=!0}else S.anyOf=l.map(f=>or(f,!1));return c&&(S.oneOf=c.map(f=>or(f,!1))),g!==void 0&&(S.minLength=g),S}function wT(t){return t!=null&&typeof t=="object"&&t.type==="object"&&(t.properties==null||Object.keys(t.properties).length===0)&&!t.additionalProperties}function ET(t,e){var r,n,o;let a=[],i=[],s=!0,l=(r=e?.isGemmaModel)!=null?r:!1,c=(n=e?.providerOptionsName)!=null?n:"google";for(let{role:p,content:h}of t)switch(p){case"system":{if(!s)throw new tt({functionality:"system messages are only supported at the beginning of the conversation"});a.push({text:h});break}case"user":{s=!1;let g=[];for(let y of h)switch(y.type){case"text":{g.push({text:y.text});break}case"file":{let S=y.mediaType==="image/*"?"image/jpeg":y.mediaType;g.push(y.data instanceof URL?{fileData:{mimeType:S,fileUri:y.data.toString()}}:{inlineData:{mimeType:S,data:lr(y.data)}});break}}i.push({role:"user",parts:g});break}case"assistant":{s=!1,i.push({role:"model",parts:h.map(g=>{var y;let S=(y=g.providerOptions)==null?void 0:y[c],f=S?.thoughtSignature!=null?String(S.thoughtSignature):void 0;switch(g.type){case"text":return g.text.length===0?void 0:{text:g.text,thoughtSignature:f};case"reasoning":return g.text.length===0?void 0:{text:g.text,thought:!0,thoughtSignature:f};case"file":{if(g.data instanceof URL)throw new tt({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:g.mediaType,data:lr(g.data)},thoughtSignature:f}}case"tool-call":return{functionCall:{name:g.toolName,args:g.input},thoughtSignature:f}}}).filter(g=>g!==void 0)});break}case"tool":{s=!1;let g=[];for(let y of h){if(y.type==="tool-approval-response")continue;let S=y.output;if(S.type==="content")for(let f of S.value)switch(f.type){case"text":g.push({functionResponse:{name:y.toolName,response:{name:y.toolName,content:f.text}}});break;case"image-data":g.push({inlineData:{mimeType:f.mediaType,data:f.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:g.push({text:JSON.stringify(f)});break}else g.push({functionResponse:{name:y.toolName,response:{name:y.toolName,content:S.type==="execution-denied"?(o=S.reason)!=null?o:"Tool execution denied.":S.value}}})}i.push({role:"user",parts:g});break}}if(l&&a.length>0&&i.length>0&&i[0].role==="user"){let p=a.map(h=>h.text).join(`
|
|
48
48
|
|
|
49
49
|
`);i[0].parts.unshift({text:p+`
|
|
50
50
|
|
|
51
|
-
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function wh(t){return t.includes("/")?t:`models/${t}`}var TT=q(()=>H(to.object({error:to.object({code:to.number().nullable(),message:to.string(),status:to.string()})}))),Eh=Qe({errorSchema:TT,errorToMessage:t=>t.error.message}),Th=q(()=>H(Le.object({responseModalities:Le.array(Le.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:Le.object({thinkingBudget:Le.number().optional(),includeThoughts:Le.boolean().optional(),thinkingLevel:Le.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:Le.string().optional(),structuredOutputs:Le.boolean().optional(),safetySettings:Le.array(Le.object({category:Le.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Le.boolean().optional(),labels:Le.record(Le.string(),Le.string()).optional(),mediaResolution:Le.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:Le.object({aspectRatio:Le.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:Le.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:Le.object({latLng:Le.object({latitude:Le.number(),longitude:Le.number()}).optional()}).optional()})));function xT({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(g=>g===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(g=>g.type==="function"),p=t.some(g=>g.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let g=[];return t.filter(y=>y.type==="provider").forEach(y=>{switch(y.id){case"google.google_search":i?g.push({googleSearch:{}}):s?g.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:y.args.mode,dynamicThreshold:y.args.dynamicThreshold}}}):g.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?g.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?g.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?g.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?g.push({fileSearch:{...y.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?g.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:y.args.ragCorpus},similarity_top_k:y.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?g.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${y.id}`});break}}),{tools:g.length>0?g:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let g of t)switch(g.type){case"function":h.push({name:g.name,description:(n=g.description)!=null?n:"",parameters:or(g.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${g.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let m=e.type;switch(m){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let g=m;throw new tt({functionality:`tool choice type: ${g}`})}}}function xh({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var Ch=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:m}){var g;let T=[],y=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:y,providerOptions:m,schema:Th});b==null&&y!=="google"&&(b=await Ve({provider:"google",providerOptions:m,schema:Th})),p?.some(R=>R.type==="provider"&&R.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&T.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:D,systemInstruction:V}=ET(t,{isGemmaModel:_,providerOptionsName:y}),{tools:X,toolConfig:P,toolWarnings:N}=xT({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((g=b?.structuredOutputs)==null||g)?or(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:D,systemInstruction:_?void 0:V,safetySettings:b?.safetySettings,tools:X,toolConfig:b?.retrievalConfig?{...P,retrievalConfig:b.retrievalConfig}:P,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...T,...N],providerOptionsName:y}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:m}=await this.getArgs(t),g=$e(await Te(this.config.headers),t.headers),{responseHeaders:T,value:y,rawValue:b}=await Fe({url:`${this.config.baseURL}/${wh(this.modelId)}:generateContent`,headers:g,body:p,failedResponseHandler:Eh,successfulResponseHandler:qe(CT),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=y.candidates[0],D=[],V=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],X=y.usageMetadata,P;for(let R of V)if("executableCode"in R&&((n=R.executableCode)!=null&&n.code)){let Q=this.config.generateId();P=Q,D.push({type:"tool-call",toolCallId:Q,toolName:"code_execution",input:JSON.stringify(R.executableCode),providerExecuted:!0})}else"codeExecutionResult"in R&&R.codeExecutionResult?(D.push({type:"tool-result",toolCallId:P,toolName:"code_execution",result:{outcome:R.codeExecutionResult.outcome,output:R.codeExecutionResult.output}}),P=void 0):"text"in R&&R.text!=null&&R.text.length>0?D.push({type:R.thought===!0?"reasoning":"text",text:R.text,providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0}):"functionCall"in R?D.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:R.functionCall.name,input:JSON.stringify(R.functionCall.args),providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0}):"inlineData"in R&&D.push({type:"file",data:R.inlineData.data,mediaType:R.inlineData.mimeType,providerMetadata:R.thoughtSignature?{[m]:{thoughtSignature:R.thoughtSignature}}:void 0});let N=(o=Sh({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let R of N)D.push(R);return{content:D,finishReason:{unified:xh({finishReason:_.finishReason,hasToolCalls:D.some(R=>R.type==="tool-call"&&!R.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:_h(X),warnings:h,providerMetadata:{[m]:{promptFeedback:(i=y.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:X??null}},request:{body:p},response:{headers:T,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=$e(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Fe({url:`${this.config.baseURL}/${wh(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:Eh,successfulResponseHandler:Sr(IT),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,m=null,g=null,T=0,y=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,D){var V,X,P,N,R,Q,E;if(t.includeRawChunks&&D.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){D.enqueue({type:"error",error:_.error});return}let re=_.value,Z=re.usageMetadata;Z!=null&&(l=Z);let Y=(V=re.candidates)==null?void 0:V[0];if(Y==null)return;let ce=Y.content,B=Sh({groundingMetadata:Y.groundingMetadata,generateId:p});if(B!=null)for(let J of B)J.sourceType==="url"&&!y.has(J.url)&&(y.add(J.url),D.enqueue(J));if(ce!=null){let J=(X=ce.parts)!=null?X:[];for(let j of J)if("executableCode"in j&&((P=j.executableCode)!=null&&P.code)){let ye=p();b=ye,D.enqueue({type:"tool-call",toolCallId:ye,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ye=b;ye&&(D.enqueue({type:"tool-result",toolCallId:ye,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(m!==null&&(D.enqueue({type:"text-end",id:m}),m=null),g===null&&(g=String(T++),D.enqueue({type:"reasoning-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),D.enqueue({type:"reasoning-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(g!==null&&(D.enqueue({type:"reasoning-end",id:g}),g=null),m===null&&(m=String(T++),D.enqueue({type:"text-start",id:m,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),D.enqueue({type:"text-delta",id:m,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&D.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let fe=ST({parts:ce.parts,generateId:p,providerOptionsName:n});if(fe!=null)for(let j of fe)D.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),D.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}Y.finishReason!=null&&(s={unified:xh({finishReason:Y.finishReason,hasToolCalls:h}),raw:Y.finishReason},c={[n]:{promptFeedback:(N=re.promptFeedback)!=null?N:null,groundingMetadata:(R=Y.groundingMetadata)!=null?R:null,urlContextMetadata:(Q=Y.urlContextMetadata)!=null?Q:null,safetyRatings:(E=Y.safetyRatings)!=null?E:null}},Z!=null&&(c[n].usageMetadata=Z))},flush(_){m!==null&&_.enqueue({type:"text-end",id:m}),g!==null&&_.enqueue({type:"reasoning-end",id:g}),_.enqueue({type:"finish",finishReason:s,usage:_h(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function ST({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function Sh({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",m="application/octet-stream",g;c.endsWith(".pdf")?(m="application/pdf",g=c.split("/").pop()):c.endsWith(".txt")?(m="text/plain",g=c.split("/").pop()):c.endsWith(".docx")?(m="application/vnd.openxmlformats-officedocument.wordprocessingml.document",g=c.split("/").pop()):c.endsWith(".doc")?(m="application/msword",g=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(m="text/markdown"),g=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:m,title:h,filename:g})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var Ih=()=>$.object({webSearchQueries:$.array($.string()).nullish(),retrievalQueries:$.array($.string()).nullish(),searchEntryPoint:$.object({renderedContent:$.string()}).nullish(),groundingChunks:$.array($.object({web:$.object({uri:$.string(),title:$.string().nullish()}).nullish(),retrievedContext:$.object({uri:$.string().nullish(),title:$.string().nullish(),text:$.string().nullish(),fileSearchStore:$.string().nullish()}).nullish(),maps:$.object({uri:$.string().nullish(),title:$.string().nullish(),text:$.string().nullish(),placeId:$.string().nullish()}).nullish()})).nullish(),groundingSupports:$.array($.object({segment:$.object({startIndex:$.number().nullish(),endIndex:$.number().nullish(),text:$.string().nullish()}),segment_text:$.string().nullish(),groundingChunkIndices:$.array($.number()).nullish(),supportChunkIndices:$.array($.number()).nullish(),confidenceScores:$.array($.number()).nullish(),confidenceScore:$.array($.number()).nullish()})).nullish(),retrievalMetadata:$.union([$.object({webDynamicRetrievalScore:$.number()}),$.object({})]).nullish()}),Ah=()=>$.object({parts:$.array($.union([$.object({functionCall:$.object({name:$.string(),args:$.unknown()}),thoughtSignature:$.string().nullish()}),$.object({inlineData:$.object({mimeType:$.string(),data:$.string()}),thoughtSignature:$.string().nullish()}),$.object({executableCode:$.object({language:$.string(),code:$.string()}).nullish(),codeExecutionResult:$.object({outcome:$.string(),output:$.string()}).nullish(),text:$.string().nullish(),thought:$.boolean().nullish(),thoughtSignature:$.string().nullish()})])).nullish()}),Ea=()=>$.object({category:$.string().nullish(),probability:$.string().nullish(),probabilityScore:$.number().nullish(),severity:$.string().nullish(),severityScore:$.number().nullish(),blocked:$.boolean().nullish()}),kh=$.object({cachedContentTokenCount:$.number().nullish(),thoughtsTokenCount:$.number().nullish(),promptTokenCount:$.number().nullish(),candidatesTokenCount:$.number().nullish(),totalTokenCount:$.number().nullish(),trafficType:$.string().nullish()}),Rh=()=>$.object({urlMetadata:$.array($.object({retrievedUrl:$.string(),urlRetrievalStatus:$.string()}))}),CT=q(()=>H($.object({candidates:$.array($.object({content:Ah().nullish().or($.object({}).strict()),finishReason:$.string().nullish(),safetyRatings:$.array(Ea()).nullish(),groundingMetadata:Ih().nullish(),urlContextMetadata:Rh().nullish()})),usageMetadata:kh.nullish(),promptFeedback:$.object({blockReason:$.string().nullish(),safetyRatings:$.array(Ea()).nullish()}).nullish()}))),IT=q(()=>H($.object({candidates:$.array($.object({content:Ah().nullish(),finishReason:$.string().nullish(),safetyRatings:$.array(Ea()).nullish(),groundingMetadata:Ih().nullish(),urlContextMetadata:Rh().nullish()})).nullish(),usageMetadata:kh.nullish(),promptFeedback:$.object({blockReason:$.string().nullish(),safetyRatings:$.array(Ea()).nullish()}).nullish()}))),AT=Ze({id:"google.code_execution",inputSchema:yn.object({language:yn.string().describe("The programming language of the code."),code:yn.string().describe("The code to be executed.")}),outputSchema:yn.object({outcome:yn.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:yn.string().describe("The output from the code execution.")})}),RT=we({id:"google.enterprise_web_search",inputSchema:q(()=>H(kT.object({})))}),OT=ro.object({fileSearchStoreNames:ro.array(ro.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:ro.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:ro.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),NT=q(()=>H(OT)),MT=we({id:"google.file_search",inputSchema:NT}),DT=we({id:"google.google_maps",inputSchema:q(()=>H(PT.object({})))}),jT=we({id:"google.google_search",inputSchema:q(()=>H(ol.object({mode:ol.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ol.number().default(1)})))}),UT=we({id:"google.url_context",inputSchema:q(()=>H(LT.object({})))}),FT=we({id:"google.vertex_rag_store",inputSchema:al.object({ragCorpus:al.string(),topK:al.number().optional()})}),kr={googleSearch:jT,enterpriseWebSearch:RT,googleMaps:DT,urlContext:UT,fileSearch:MT,codeExecution:AT,vertexRagStore:FT};import{z as Rr}from"zod/v4";import{z as no}from"zod/v4";import{z as oo}from"zod/v4";import{z as et}from"zod/v4";var il=null,Oh=null;function HT(t){return(!il||t!==Oh)&&(il=new Dh.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...t}),Oh=t),il}async function qT(t){let n=await(await HT(t||{}).getClient()).getAccessToken();return n?.token||null}var GT="4.0.15",$T=no.object({error:no.object({code:no.number().nullable(),message:no.string(),status:no.string()})}),jh=Qe({errorSchema:$T,errorToMessage:t=>t.error.message}),Nh=oo.object({outputDimensionality:oo.number().optional(),taskType:oo.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:oo.string().optional(),autoTruncate:oo.boolean().optional()}),BT=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"vertex",providerOptions:n,schema:Nh});if(o==null&&(o=await Ve({provider:"google",providerOptions:n,schema:Nh})),o=o??{},t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=$e(await Te(this.config.headers),e),i=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:s,value:l,rawValue:c}=await Fe({url:i,headers:a,body:{instances:t.map(p=>({content:p,task_type:o.taskType,title:o.title})),parameters:{outputDimensionality:o.outputDimensionality,autoTruncate:o.autoTruncate}},failedResponseHandler:jh,successfulResponseHandler:qe(VT),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.predictions.map(p=>p.embeddings.values),usage:{tokens:l.predictions.reduce((p,h)=>p+h.embeddings.statistics.token_count,0)},response:{headers:s,body:c}}}},VT=Rr.object({predictions:Rr.array(Rr.object({embeddings:Rr.object({values:Rr.array(Rr.number()),statistics:Rr.object({token_count:Rr.number()})})}))}),zT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=4}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:a,headers:i,abortSignal:s,files:l,mask:c}){var p,h,m,g,T,y,b;let _=[];r!=null&&_.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let D=await Ve({provider:"vertex",providerOptions:a,schema:JT}),{edit:V,...X}=D??{},{mode:P,baseSteps:N,maskMode:R,maskDilation:Q}=V??{},E=l!=null&&l.length>0,re;if(E){let B=[];for(let J=0;J<l.length;J++){let fe=l[J];B.push({referenceType:"REFERENCE_TYPE_RAW",referenceId:J+1,referenceImage:{bytesBase64Encoded:Mh(fe)}})}c!=null&&B.push({referenceType:"REFERENCE_TYPE_MASK",referenceId:l.length+1,referenceImage:{bytesBase64Encoded:Mh(c)},maskImageConfig:{maskMode:R??"MASK_MODE_USER_PROVIDED",...Q!=null?{dilation:Q}:{}}}),re={instances:[{prompt:t,referenceImages:B}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},editMode:P??"EDIT_MODE_INPAINT_INSERTION",...N!=null?{editConfig:{baseSteps:N}}:{},...X}}}else re={instances:[{prompt:t}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},...X}};let Z=(m=(h=(p=this.config._internal)==null?void 0:p.currentDate)==null?void 0:h.call(p))!=null?m:new Date,{value:Y,responseHeaders:ce}=await Fe({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:$e(await Te(this.config.headers),i),body:re,failedResponseHandler:jh,successfulResponseHandler:qe(WT),abortSignal:s,fetch:this.config.fetch});return{images:(T=(g=Y.predictions)==null?void 0:g.map(({bytesBase64Encoded:B})=>B))!=null?T:[],warnings:_,response:{timestamp:Z,modelId:this.modelId,headers:ce},providerMetadata:{vertex:{images:(b=(y=Y.predictions)==null?void 0:y.map(B=>{let{prompt:J}=B;return{...J!=null&&{revisedPrompt:J}}}))!=null?b:[]}}}}},WT=et.object({predictions:et.array(et.object({bytesBase64Encoded:et.string(),mimeType:et.string(),prompt:et.string().nullish()})).nullish()}),JT=et.object({negativePrompt:et.string().nullish(),personGeneration:et.enum(["dont_allow","allow_adult","allow_all"]).nullish(),safetySetting:et.enum(["block_low_and_above","block_medium_and_above","block_only_high","block_none"]).nullish(),addWatermark:et.boolean().nullish(),storageUri:et.string().nullish(),sampleImageSize:et.enum(["1K","2K"]).nullish(),edit:et.object({baseSteps:et.number().nullish(),mode:et.enum(["EDIT_MODE_INPAINT_INSERTION","EDIT_MODE_INPAINT_REMOVAL","EDIT_MODE_OUTPAINT","EDIT_MODE_CONTROLLED_EDITING","EDIT_MODE_PRODUCT_IMAGE","EDIT_MODE_BGSWAP"]).nullish(),maskMode:et.enum(["MASK_MODE_DEFAULT","MASK_MODE_USER_PROVIDED","MASK_MODE_DETECTION_BOX","MASK_MODE_CLOTHING_AREA","MASK_MODE_PARSED_PERSON"]).nullish(),maskDilation:et.number().nullish()}).nullish()});function Mh(t){if(t.type==="url")throw new Error("URL-based images are not supported for Google Vertex image editing. Please provide the image data directly.");return typeof t.data=="string"?t.data:Jt(t.data)}var KT={googleSearch:kr.googleSearch,enterpriseWebSearch:kr.enterpriseWebSearch,googleMaps:kr.googleMaps,urlContext:kr.urlContext,fileSearch:kr.fileSearch,codeExecution:kr.codeExecution,vertexRagStore:kr.vertexRagStore},YT="https://aiplatform.googleapis.com/v1/publishers/google";function XT(t,e){return async(r,n)=>{let o=new URL(r.toString());return o.searchParams.set("key",t),(e??fetch)(o.toString(),n)}}function Ph(t={}){let e=Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),r=()=>Wa({settingValue:t.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),n=()=>Wa({settingValue:t.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"}),o=()=>{var p,h;if(e)return(p=dr(t.baseURL))!=null?p:YT;let m=n(),g=r(),T=`${m==="global"?"":m+"-"}aiplatform.googleapis.com`;return(h=dr(t.baseURL))!=null?h:`https://${T}/v1beta1/projects/${g}/locations/${m}/publishers/google`},a=p=>{let h=async()=>{var m;let g=await Te((m=t.headers)!=null?m:{});return lt(g,`ai-sdk/google-vertex/${GT}`)};return{provider:`google.vertex.${p}`,headers:h,fetch:e?XT(e,t.fetch):t.fetch,baseURL:o()}},i=p=>{var h;return new Ch(p,{...a("chat"),generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})})},s=p=>new BT(p,a("embedding")),l=p=>new zT(p,a("image")),c=function(p){if(new.target)throw new Error("The Google Vertex AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.embeddingModel=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=KT,c}function sl(t={}){return Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"})?Ph(t):Ph({...t,headers:async()=>({Authorization:`Bearer ${await qT(t.googleAuthOptions)}`,...await Te(t.headers)})})}var jR=sl();var Lh={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"};function Uh(){let t=(Sn().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return t==="True"||t==="true"}function Fh(t){let e=Sn().env||{};if(Uh()){let n=e.GOOGLE_CLOUD_PROJECT;if(!n)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=t==="gemini-3-flash-preview"?"global":e.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return Ee.debug(`Using Vertex AI provider: model=${t}, location=${o}`),sl({project:n,location:o})(t)}let r=e.GOOGLE_API_KEY;if(!r)throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.");return Ee.debug(`Using Google AI provider (API key): model=${t}`),ai({apiKey:r})(t)}function Hh(t,e){let r={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:Lh.MEDIA_RESOLUTION_HIGH},o;switch(e){case"gemini-3-flash-preview":o={...n};break;default:o={...r},t===1&&(o.mediaResolution=Lh.MEDIA_RESOLUTION_HIGH)}return Uh()?{vertex:o}:{google:o}}function WR(t){if(t.startsWith("claude-"))return Eu(t);if(t.startsWith("gemini-"))return Fh(t);throw new Error(`Unsupported model: ${t}. Use 'claude-*' or 'gemini-*' models.`)}function JR(t,e){return t.startsWith("claude-")?Tu(t):Hh(e,t)}async function Gh(){let{default:t}=await import("sharp");return t}var qh=768;async function ll(t,e){let r=await Gh(),n=await r(t).metadata(),o=n.width||0,a=n.height||0;if(o===0||a===0)throw new Error("Invalid image dimensions");let i=a,s=0,l=Math.floor((o-i)/2),c=Math.max(0,o-i),p=(T,y)=>{let b=r(t).extract({left:T,top:0,width:y,height:i});return e?.resize&&(b=b.resize(qh,qh)),b.png().toBuffer()},[h,m,g]=await Promise.all([p(s,Math.min(i,o)),p(l,Math.min(i,o-l)),p(c,Math.min(i,o-c))]);return[h,m,g]}async function $h(t){let e=(await Gh())(t),r=await e.metadata(),n=r.width||0,o=r.height||0;if(n===0||o===0)throw new Error("Invalid image dimensions");let{data:a}=await e.grayscale().raw().toBuffer({resolveWithObject:!0}),i=[];for(let s=0;s<o;s++){i[s]=[];for(let l=0;l<n;l++)i[s][l]=a[s*n+l]}return{pixels:i,width:n,height:o}}var cl=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),Ta=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Bh=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Vh=500;function XR(t){return t?cl.has(t):!1}function ZR(t){return Ta.has(t)}function QR(t){return t.filter(e=>Ta.has(e.type))}function zh(t,e){return t.length>e?t.slice(0,e)+"...":t}var Wh=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],Jh={"react-flow__(\\S+)":"$1"};var Kh=class{constructor(t,e=null){this.isVisible=t,this.parent=e}},ao=class extends Kh{constructor(t,e,r=null){super(e,r),this.text=t,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let t=this.parent;for(;t!==null;){if(t.highlightIndex!==null)return!0;t=t.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},ar=class xa extends Kh{constructor(e,r,n,o,a,i=!1,s=!1,l=!1,c=!1,p=!1,h=!1,m=null,g=null,T=null,y=null,b=[],_=null){super(a,_),this.tagName=e,this.xpath=r,this.attributes=n,this.children=o,this.isInteractive=i,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=p,this.shadowRoot=h,this.highlightIndex=m,this.viewportCoordinates=g,this.pageCoordinates=T,this.viewportInfo=y,this.isNew=null,this.shadowHostXPaths=b}getAllTextTillNextClickableElement(e=-1){let r=[],n=(o,a)=>{if(!(e!==-1&&a>e)&&!(o instanceof xa&&o!==this&&o.highlightIndex!==null)){if(o instanceof ao)r.push(o.text);else if(o instanceof xa)for(let i of o.children)n(i,a+1)}};return n(this,0),r.join(`
|
|
52
|
-
`).trim()}clickableElementsToString(e){let r=e?.includeAttributes??Wh,n=e?.includeClassesWithRename??Jh,o=[],a=(i,s)=>{let l=s,c=" ".repeat(s);if(i instanceof xa){if(i.highlightIndex!==null){l+=1;let p=i.isScrollable?"":i.getAllTextTillNextClickableElement(),h=null;if(r.length>0){let _={};for(let
|
|
51
|
+
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function wh(t){return t.includes("/")?t:`models/${t}`}var TT=q(()=>H(to.object({error:to.object({code:to.number().nullable(),message:to.string(),status:to.string()})}))),Eh=Qe({errorSchema:TT,errorToMessage:t=>t.error.message}),Th=q(()=>H(Le.object({responseModalities:Le.array(Le.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:Le.object({thinkingBudget:Le.number().optional(),includeThoughts:Le.boolean().optional(),thinkingLevel:Le.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:Le.string().optional(),structuredOutputs:Le.boolean().optional(),safetySettings:Le.array(Le.object({category:Le.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Le.boolean().optional(),labels:Le.record(Le.string(),Le.string()).optional(),mediaResolution:Le.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:Le.object({aspectRatio:Le.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:Le.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:Le.object({latLng:Le.object({latitude:Le.number(),longitude:Le.number()}).optional()}).optional()})));function xT({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(y=>y===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(y=>y.type==="function"),p=t.some(y=>y.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let y=[];return t.filter(f=>f.type==="provider").forEach(f=>{switch(f.id){case"google.google_search":i?y.push({googleSearch:{}}):s?y.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:f.args.mode,dynamicThreshold:f.args.dynamicThreshold}}}):y.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?y.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?y.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?y.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?y.push({fileSearch:{...f.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?y.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:f.args.ragCorpus},similarity_top_k:f.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?y.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`});break}}),{tools:y.length>0?y:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let y of t)switch(y.type){case"function":h.push({name:y.name,description:(n=y.description)!=null?n:"",parameters:or(y.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${y.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let g=e.type;switch(g){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let y=g;throw new tt({functionality:`tool choice type: ${y}`})}}}function xh({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var Ch=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:g}){var y;let S=[],f=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:f,providerOptions:g,schema:Th});b==null&&f!=="google"&&(b=await Ve({provider:"google",providerOptions:g,schema:Th})),p?.some(O=>O.type==="provider"&&O.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&S.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:M,systemInstruction:B}=ET(t,{isGemmaModel:_,providerOptionsName:f}),{tools:Z,toolConfig:N,toolWarnings:R}=xT({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((y=b?.structuredOutputs)==null||y)?or(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:M,systemInstruction:_?void 0:B,safetySettings:b?.safetySettings,tools:Z,toolConfig:b?.retrievalConfig?{...N,retrievalConfig:b.retrievalConfig}:N,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...S,...R],providerOptionsName:f}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:g}=await this.getArgs(t),y=Ge(await Te(this.config.headers),t.headers),{responseHeaders:S,value:f,rawValue:b}=await Ue({url:`${this.config.baseURL}/${wh(this.modelId)}:generateContent`,headers:y,body:p,failedResponseHandler:Eh,successfulResponseHandler:qe(CT),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=f.candidates[0],M=[],B=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],Z=f.usageMetadata,N;for(let O of B)if("executableCode"in O&&((n=O.executableCode)!=null&&n.code)){let ee=this.config.generateId();N=ee,M.push({type:"tool-call",toolCallId:ee,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else"codeExecutionResult"in O&&O.codeExecutionResult?(M.push({type:"tool-result",toolCallId:N,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:O.codeExecutionResult.output}}),N=void 0):"text"in O&&O.text!=null&&O.text.length>0?M.push({type:O.thought===!0?"reasoning":"text",text:O.text,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"functionCall"in O?M.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:O.functionCall.name,input:JSON.stringify(O.functionCall.args),providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"inlineData"in O&&M.push({type:"file",data:O.inlineData.data,mediaType:O.inlineData.mimeType,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0});let R=(o=Sh({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let O of R)M.push(O);return{content:M,finishReason:{unified:xh({finishReason:_.finishReason,hasToolCalls:M.some(O=>O.type==="tool-call"&&!O.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:_h(Z),warnings:h,providerMetadata:{[g]:{promptFeedback:(i=f.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:Z??null}},request:{body:p},response:{headers:S,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=Ge(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Ue({url:`${this.config.baseURL}/${wh(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:Eh,successfulResponseHandler:Sr(IT),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,g=null,y=null,S=0,f=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,M){var B,Z,N,R,O,ee,E;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){M.enqueue({type:"error",error:_.error});return}let Q=_.value,X=Q.usageMetadata;X!=null&&(l=X);let W=(B=Q.candidates)==null?void 0:B[0];if(W==null)return;let ue=W.content,V=Sh({groundingMetadata:W.groundingMetadata,generateId:p});if(V!=null)for(let K of V)K.sourceType==="url"&&!f.has(K.url)&&(f.add(K.url),M.enqueue(K));if(ue!=null){let K=(Z=ue.parts)!=null?Z:[];for(let j of K)if("executableCode"in j&&((N=j.executableCode)!=null&&N.code)){let ve=p();b=ve,M.enqueue({type:"tool-call",toolCallId:ve,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ve=b;ve&&(M.enqueue({type:"tool-result",toolCallId:ve,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(g!==null&&(M.enqueue({type:"text-end",id:g}),g=null),y===null&&(y=String(S++),M.enqueue({type:"reasoning-start",id:y,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"reasoning-delta",id:y,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(y!==null&&(M.enqueue({type:"reasoning-end",id:y}),y=null),g===null&&(g=String(S++),M.enqueue({type:"text-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"text-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&M.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let me=ST({parts:ue.parts,generateId:p,providerOptionsName:n});if(me!=null)for(let j of me)M.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}W.finishReason!=null&&(s={unified:xh({finishReason:W.finishReason,hasToolCalls:h}),raw:W.finishReason},c={[n]:{promptFeedback:(R=Q.promptFeedback)!=null?R:null,groundingMetadata:(O=W.groundingMetadata)!=null?O:null,urlContextMetadata:(ee=W.urlContextMetadata)!=null?ee:null,safetyRatings:(E=W.safetyRatings)!=null?E:null}},X!=null&&(c[n].usageMetadata=X))},flush(_){g!==null&&_.enqueue({type:"text-end",id:g}),y!==null&&_.enqueue({type:"reasoning-end",id:y}),_.enqueue({type:"finish",finishReason:s,usage:_h(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function ST({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function Sh({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",g="application/octet-stream",y;c.endsWith(".pdf")?(g="application/pdf",y=c.split("/").pop()):c.endsWith(".txt")?(g="text/plain",y=c.split("/").pop()):c.endsWith(".docx")?(g="application/vnd.openxmlformats-officedocument.wordprocessingml.document",y=c.split("/").pop()):c.endsWith(".doc")?(g="application/msword",y=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(g="text/markdown"),y=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:g,title:h,filename:y})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var Ih=()=>G.object({webSearchQueries:G.array(G.string()).nullish(),retrievalQueries:G.array(G.string()).nullish(),searchEntryPoint:G.object({renderedContent:G.string()}).nullish(),groundingChunks:G.array(G.object({web:G.object({uri:G.string(),title:G.string().nullish()}).nullish(),retrievedContext:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),fileSearchStore:G.string().nullish()}).nullish(),maps:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),placeId:G.string().nullish()}).nullish()})).nullish(),groundingSupports:G.array(G.object({segment:G.object({startIndex:G.number().nullish(),endIndex:G.number().nullish(),text:G.string().nullish()}),segment_text:G.string().nullish(),groundingChunkIndices:G.array(G.number()).nullish(),supportChunkIndices:G.array(G.number()).nullish(),confidenceScores:G.array(G.number()).nullish(),confidenceScore:G.array(G.number()).nullish()})).nullish(),retrievalMetadata:G.union([G.object({webDynamicRetrievalScore:G.number()}),G.object({})]).nullish()}),Ah=()=>G.object({parts:G.array(G.union([G.object({functionCall:G.object({name:G.string(),args:G.unknown()}),thoughtSignature:G.string().nullish()}),G.object({inlineData:G.object({mimeType:G.string(),data:G.string()}),thoughtSignature:G.string().nullish()}),G.object({executableCode:G.object({language:G.string(),code:G.string()}).nullish(),codeExecutionResult:G.object({outcome:G.string(),output:G.string()}).nullish(),text:G.string().nullish(),thought:G.boolean().nullish(),thoughtSignature:G.string().nullish()})])).nullish()}),Ea=()=>G.object({category:G.string().nullish(),probability:G.string().nullish(),probabilityScore:G.number().nullish(),severity:G.string().nullish(),severityScore:G.number().nullish(),blocked:G.boolean().nullish()}),kh=G.object({cachedContentTokenCount:G.number().nullish(),thoughtsTokenCount:G.number().nullish(),promptTokenCount:G.number().nullish(),candidatesTokenCount:G.number().nullish(),totalTokenCount:G.number().nullish(),trafficType:G.string().nullish()}),Rh=()=>G.object({urlMetadata:G.array(G.object({retrievedUrl:G.string(),urlRetrievalStatus:G.string()}))}),CT=q(()=>H(G.object({candidates:G.array(G.object({content:Ah().nullish().or(G.object({}).strict()),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:Ih().nullish(),urlContextMetadata:Rh().nullish()})),usageMetadata:kh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),IT=q(()=>H(G.object({candidates:G.array(G.object({content:Ah().nullish(),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:Ih().nullish(),urlContextMetadata:Rh().nullish()})).nullish(),usageMetadata:kh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),AT=Ze({id:"google.code_execution",inputSchema:yn.object({language:yn.string().describe("The programming language of the code."),code:yn.string().describe("The code to be executed.")}),outputSchema:yn.object({outcome:yn.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:yn.string().describe("The output from the code execution.")})}),RT=Ee({id:"google.enterprise_web_search",inputSchema:q(()=>H(kT.object({})))}),OT=ro.object({fileSearchStoreNames:ro.array(ro.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:ro.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:ro.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),NT=q(()=>H(OT)),MT=Ee({id:"google.file_search",inputSchema:NT}),DT=Ee({id:"google.google_maps",inputSchema:q(()=>H(PT.object({})))}),jT=Ee({id:"google.google_search",inputSchema:q(()=>H(ol.object({mode:ol.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ol.number().default(1)})))}),FT=Ee({id:"google.url_context",inputSchema:q(()=>H(LT.object({})))}),UT=Ee({id:"google.vertex_rag_store",inputSchema:al.object({ragCorpus:al.string(),topK:al.number().optional()})}),kr={googleSearch:jT,enterpriseWebSearch:RT,googleMaps:DT,urlContext:FT,fileSearch:MT,codeExecution:AT,vertexRagStore:UT};import{z as Rr}from"zod/v4";import{z as no}from"zod/v4";import{z as oo}from"zod/v4";import{z as et}from"zod/v4";var il=null,Oh=null;function HT(t){return(!il||t!==Oh)&&(il=new Dh.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...t}),Oh=t),il}async function qT(t){let n=await(await HT(t||{}).getClient()).getAccessToken();return n?.token||null}var $T="4.0.15",GT=no.object({error:no.object({code:no.number().nullable(),message:no.string(),status:no.string()})}),jh=Qe({errorSchema:GT,errorToMessage:t=>t.error.message}),Nh=oo.object({outputDimensionality:oo.number().optional(),taskType:oo.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:oo.string().optional(),autoTruncate:oo.boolean().optional()}),BT=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"vertex",providerOptions:n,schema:Nh});if(o==null&&(o=await Ve({provider:"google",providerOptions:n,schema:Nh})),o=o??{},t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=Ge(await Te(this.config.headers),e),i=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:s,value:l,rawValue:c}=await Ue({url:i,headers:a,body:{instances:t.map(p=>({content:p,task_type:o.taskType,title:o.title})),parameters:{outputDimensionality:o.outputDimensionality,autoTruncate:o.autoTruncate}},failedResponseHandler:jh,successfulResponseHandler:qe(VT),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.predictions.map(p=>p.embeddings.values),usage:{tokens:l.predictions.reduce((p,h)=>p+h.embeddings.statistics.token_count,0)},response:{headers:s,body:c}}}},VT=Rr.object({predictions:Rr.array(Rr.object({embeddings:Rr.object({values:Rr.array(Rr.number()),statistics:Rr.object({token_count:Rr.number()})})}))}),zT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=4}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:a,headers:i,abortSignal:s,files:l,mask:c}){var p,h,g,y,S,f,b;let _=[];r!=null&&_.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let M=await Ve({provider:"vertex",providerOptions:a,schema:JT}),{edit:B,...Z}=M??{},{mode:N,baseSteps:R,maskMode:O,maskDilation:ee}=B??{},E=l!=null&&l.length>0,Q;if(E){let V=[];for(let K=0;K<l.length;K++){let me=l[K];V.push({referenceType:"REFERENCE_TYPE_RAW",referenceId:K+1,referenceImage:{bytesBase64Encoded:Mh(me)}})}c!=null&&V.push({referenceType:"REFERENCE_TYPE_MASK",referenceId:l.length+1,referenceImage:{bytesBase64Encoded:Mh(c)},maskImageConfig:{maskMode:O??"MASK_MODE_USER_PROVIDED",...ee!=null?{dilation:ee}:{}}}),Q={instances:[{prompt:t,referenceImages:V}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},editMode:N??"EDIT_MODE_INPAINT_INSERTION",...R!=null?{editConfig:{baseSteps:R}}:{},...Z}}}else Q={instances:[{prompt:t}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},...Z}};let X=(g=(h=(p=this.config._internal)==null?void 0:p.currentDate)==null?void 0:h.call(p))!=null?g:new Date,{value:W,responseHeaders:ue}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Ge(await Te(this.config.headers),i),body:Q,failedResponseHandler:jh,successfulResponseHandler:qe(WT),abortSignal:s,fetch:this.config.fetch});return{images:(S=(y=W.predictions)==null?void 0:y.map(({bytesBase64Encoded:V})=>V))!=null?S:[],warnings:_,response:{timestamp:X,modelId:this.modelId,headers:ue},providerMetadata:{vertex:{images:(b=(f=W.predictions)==null?void 0:f.map(V=>{let{prompt:K}=V;return{...K!=null&&{revisedPrompt:K}}}))!=null?b:[]}}}}},WT=et.object({predictions:et.array(et.object({bytesBase64Encoded:et.string(),mimeType:et.string(),prompt:et.string().nullish()})).nullish()}),JT=et.object({negativePrompt:et.string().nullish(),personGeneration:et.enum(["dont_allow","allow_adult","allow_all"]).nullish(),safetySetting:et.enum(["block_low_and_above","block_medium_and_above","block_only_high","block_none"]).nullish(),addWatermark:et.boolean().nullish(),storageUri:et.string().nullish(),sampleImageSize:et.enum(["1K","2K"]).nullish(),edit:et.object({baseSteps:et.number().nullish(),mode:et.enum(["EDIT_MODE_INPAINT_INSERTION","EDIT_MODE_INPAINT_REMOVAL","EDIT_MODE_OUTPAINT","EDIT_MODE_CONTROLLED_EDITING","EDIT_MODE_PRODUCT_IMAGE","EDIT_MODE_BGSWAP"]).nullish(),maskMode:et.enum(["MASK_MODE_DEFAULT","MASK_MODE_USER_PROVIDED","MASK_MODE_DETECTION_BOX","MASK_MODE_CLOTHING_AREA","MASK_MODE_PARSED_PERSON"]).nullish(),maskDilation:et.number().nullish()}).nullish()});function Mh(t){if(t.type==="url")throw new Error("URL-based images are not supported for Google Vertex image editing. Please provide the image data directly.");return typeof t.data=="string"?t.data:Jt(t.data)}var KT={googleSearch:kr.googleSearch,enterpriseWebSearch:kr.enterpriseWebSearch,googleMaps:kr.googleMaps,urlContext:kr.urlContext,fileSearch:kr.fileSearch,codeExecution:kr.codeExecution,vertexRagStore:kr.vertexRagStore},YT="https://aiplatform.googleapis.com/v1/publishers/google";function XT(t,e){return async(r,n)=>{let o=new URL(r.toString());return o.searchParams.set("key",t),(e??fetch)(o.toString(),n)}}function Ph(t={}){let e=Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),r=()=>Wa({settingValue:t.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),n=()=>Wa({settingValue:t.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"}),o=()=>{var p,h;if(e)return(p=dr(t.baseURL))!=null?p:YT;let g=n(),y=r(),S=`${g==="global"?"":g+"-"}aiplatform.googleapis.com`;return(h=dr(t.baseURL))!=null?h:`https://${S}/v1beta1/projects/${y}/locations/${g}/publishers/google`},a=p=>{let h=async()=>{var g;let y=await Te((g=t.headers)!=null?g:{});return lt(y,`ai-sdk/google-vertex/${$T}`)};return{provider:`google.vertex.${p}`,headers:h,fetch:e?XT(e,t.fetch):t.fetch,baseURL:o()}},i=p=>{var h;return new Ch(p,{...a("chat"),generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})})},s=p=>new BT(p,a("embedding")),l=p=>new zT(p,a("image")),c=function(p){if(new.target)throw new Error("The Google Vertex AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.embeddingModel=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=KT,c}function sl(t={}){return Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"})?Ph(t):Ph({...t,headers:async()=>({Authorization:`Bearer ${await qT(t.googleAuthOptions)}`,...await Te(t.headers)})})}var jR=sl();var Lh={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"};function Fh(){let t=(Sn().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return t==="True"||t==="true"}function Uh(t){let e=Sn().env||{};if(Fh()){let n=e.GOOGLE_CLOUD_PROJECT;if(!n)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=t==="gemini-3-flash-preview"?"global":e.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return ce.debug(`Using Vertex AI provider: model=${t}, location=${o}`),sl({project:n,location:o})(t)}let r=e.GOOGLE_API_KEY;if(!r)throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.");return ce.debug(`Using Google AI provider (API key): model=${t}`),ai({apiKey:r})(t)}function Hh(t,e){let r={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:Lh.MEDIA_RESOLUTION_HIGH},o;switch(e){case"gemini-3-flash-preview":o={...n};break;default:o={...r},t===1&&(o.mediaResolution=Lh.MEDIA_RESOLUTION_HIGH)}return Fh()?{vertex:o}:{google:o}}function WR(t){if(t.startsWith("claude-"))return Eu(t);if(t.startsWith("gemini-"))return Uh(t);throw new Error(`Unsupported model: ${t}. Use 'claude-*' or 'gemini-*' models.`)}function JR(t,e){return t.startsWith("claude-")?Tu(t):Hh(e,t)}async function $h(){let{default:t}=await import("sharp");return t}var qh=768;async function ll(t,e){let r=await $h(),n=await r(t).metadata(),o=n.width||0,a=n.height||0;if(o===0||a===0)throw new Error("Invalid image dimensions");let i=a,s=0,l=Math.floor((o-i)/2),c=Math.max(0,o-i),p=(S,f)=>{let b=r(t).extract({left:S,top:0,width:f,height:i});return e?.resize&&(b=b.resize(qh,qh)),b.png().toBuffer()},[h,g,y]=await Promise.all([p(s,Math.min(i,o)),p(l,Math.min(i,o-l)),p(c,Math.min(i,o-c))]);return[h,g,y]}async function Gh(t){let e=(await $h())(t),r=await e.metadata(),n=r.width||0,o=r.height||0;if(n===0||o===0)throw new Error("Invalid image dimensions");let{data:a}=await e.grayscale().raw().toBuffer({resolveWithObject:!0}),i=[];for(let s=0;s<o;s++){i[s]=[];for(let l=0;l<n;l++)i[s][l]=a[s*n+l]}return{pixels:i,width:n,height:o}}var cl=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),Ta=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Bh=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Vh=500;function XR(t){return t?cl.has(t):!1}function ZR(t){return Ta.has(t)}function QR(t){return t.filter(e=>Ta.has(e.type))}function zh(t,e){return t.length>e?t.slice(0,e)+"...":t}var Wh=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],Jh={"react-flow__(\\S+)":"$1"};var Kh=class{constructor(t,e=null){this.isVisible=t,this.parent=e}},ao=class extends Kh{constructor(t,e,r=null){super(e,r),this.text=t,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let t=this.parent;for(;t!==null;){if(t.highlightIndex!==null)return!0;t=t.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},ar=class xa extends Kh{constructor(e,r,n,o,a,i=!1,s=!1,l=!1,c=!1,p=!1,h=!1,g=null,y=null,S=null,f=null,b=[],_=null){super(a,_),this.tagName=e,this.xpath=r,this.attributes=n,this.children=o,this.isInteractive=i,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=p,this.shadowRoot=h,this.highlightIndex=g,this.viewportCoordinates=y,this.pageCoordinates=S,this.viewportInfo=f,this.isNew=null,this.shadowHostXPaths=b}getAllTextTillNextClickableElement(e=-1){let r=[],n=(o,a)=>{if(!(e!==-1&&a>e)&&!(o instanceof xa&&o!==this&&o.highlightIndex!==null)){if(o instanceof ao)r.push(o.text);else if(o instanceof xa)for(let i of o.children)n(i,a+1)}};return n(this,0),r.join(`
|
|
52
|
+
`).trim()}clickableElementsToString(e){let r=e?.includeAttributes??Wh,n=e?.includeClassesWithRename??Jh,o=[],a=(i,s)=>{let l=s,c=" ".repeat(s);if(i instanceof xa){if(i.highlightIndex!==null){l+=1;let p=i.isScrollable?"":i.getAllTextTillNextClickableElement(),h=null;if(r.length>0){let _={};for(let Z of Object.keys(i.attributes))if(r.includes(Z)){let N=i.attributes[Z].trim();N!==""&&(_[Z]=N)}let M=r.filter(Z=>Z in _);if(M.length>1){let Z=new Set,N={};for(let R of M){let O=_[R];O.length>5&&(O in N?Z.add(R):N[O]=R)}for(let R of Z)delete _[R]}i.tagName===_.role&&delete _.role;let B=["aria-label","placeholder","title"];for(let Z of B)_[Z]&&_[Z].trim().toLowerCase()===p.trim().toLowerCase()&&delete _[Z];Object.keys(_).length>0&&(h=Object.entries(_).map(([Z,N])=>`${Z}=${zh(N,200)}`).join(" "))}let g=i.isNew?`*[${i.highlightIndex}]`:`[${i.highlightIndex}]`,y=[];if(Object.keys(n).length>0&&i.attributes.class){let _=i.attributes.class.split(/\s+/);for(let M of _)for(let[B,Z]of Object.entries(n))try{let N=new RegExp(`^${B}$`);if(M.match(N)){let R=M.replace(N,Z);R&&y.push(R);break}}catch{continue}}let S=i.isScrollable?" (SCROLLABLE)":"",f=i.markAsClickable?" (CLICKABLE)":"",b=`${c}${g}${S}${f}<${i.tagName}`;if(y.length>0&&(b+=` ${y.join(" ")}`),h&&(b+=` ${h}`),p){let _=p.trim();h||(b+=" "),b+=`>${_}`}else h||(b+=" ");b+=" />",o.push(b)}else{let p=["data-testid","data-test-id"].filter(h=>i.attributes[h]);p.length>0&&(l+=1,o.push(`${c}<${i.tagName} ${p.map(h=>`${h}="${i.attributes[h]}"`).join(" ")} />`))}for(let p of i.children)a(p,l)}else if(i instanceof ao){if(i.hasParentWithHighlightIndex())return;i.parent&&i.parent.isVisible&&i.parent.isTopElement&&o.push(`${c}${i.text}`)}};return a(this,0),o.join(`
|
|
53
53
|
`)}};var ZT=`(
|
|
54
54
|
args = {
|
|
55
55
|
doHighlightElements: true,
|
|
@@ -59,6 +59,7 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
59
59
|
interactiveClassNames: [],
|
|
60
60
|
alwaysHighlightFileInput: false,
|
|
61
61
|
domTreeRoot: "body",
|
|
62
|
+
initialHighlightIndex: 0,
|
|
62
63
|
}
|
|
63
64
|
) => {
|
|
64
65
|
const SEMANTIC_ATTRIBUTES = ['data-testid', 'data-test-id'];
|
|
@@ -95,13 +96,14 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
95
96
|
interactiveClassNames,
|
|
96
97
|
alwaysHighlightFileInput,
|
|
97
98
|
domTreeRoot,
|
|
99
|
+
initialHighlightIndex = 0,
|
|
98
100
|
} = args;
|
|
99
101
|
|
|
100
102
|
const buttonClassNames = ['button', 'dropdown-toggle'];
|
|
101
103
|
const heuristicClassPattern = /\\b(btn|const clickable|menu|item|entry|link)\\b/i;
|
|
102
104
|
const containerSelectors = 'button,a,[role="button"],.menu,.dropdown,.list,.toolbar';
|
|
103
105
|
|
|
104
|
-
let highlightIndex =
|
|
106
|
+
let highlightIndex = initialHighlightIndex;
|
|
105
107
|
|
|
106
108
|
/**
|
|
107
109
|
* Helper function to check if element has any of the specified class names.
|
|
@@ -1762,6 +1764,7 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
1762
1764
|
}
|
|
1763
1765
|
} catch (e) {
|
|
1764
1766
|
console.warn("Unable to access iframe:", e);
|
|
1767
|
+
nodeData.inaccessibleFrame = true;
|
|
1765
1768
|
}
|
|
1766
1769
|
}
|
|
1767
1770
|
// Handle rich text editors and contenteditable elements
|
|
@@ -3863,7 +3866,7 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
3863
3866
|
// Return element data from boxes phase for use in labels phase
|
|
3864
3867
|
elementData: phase === 'boxes' ? collectedElementData : undefined,
|
|
3865
3868
|
};
|
|
3866
|
-
})`;function e0(t){return t==="about:blank"||t==="chrome://newtab/"||t==="edge://newtab/"||t==="about:newtab"}var pO=class{constructor(t={}){
|
|
3869
|
+
})`;function e0(t){return t==="about:blank"||t==="chrome://newtab/"||t==="edge://newtab/"||t==="about:newtab"}var pO=class{constructor(t={}){ce.debug("\u{1F333} Initializing DomService with options:",t),this.useDomTreeTs=t.useDomTreeTs??!1,this.domTreeRoot=t.domTreeRoot??"body",this.jsCode=this.useDomTreeTs?QT:ZT}async getClickableElements(t,e={}){let{highlightElements:r=!0,focusElement:n=-1,viewportExpansion:o=0,interactiveClassNames:a=[],alwaysHighlightFileInput:i=!1,sameRectIoUThreshold:s,actionIntent:l="all"}=e,[c,p]=await this.buildDomTree(t,r,n,o,a,i,s,l);return{elementTree:c,selectorMap:p}}async getClickableElementsWithScreenshot(t,e={}){if(e.useAccessibilityTree)return this.getClickableElementsWithAXTree(t,e);let r;e.useCleanScreenshot&&(r=await t.screenshot({type:"png",fullPage:!1}));let n=await this.getClickableElements(t,e);if(await t.waitForTimeout(100),e.useCleanScreenshot||(r=await t.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(t),!r)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let o=r.toString("base64"),a;if(e.useSlicedScreenshots)try{a=(await ll(r,{resize:e.resizeSlicedScreenshots})).map(i=>i.toString("base64"))}catch(i){ce.warn("Failed to slice screenshot:",i)}return{domState:n,screenshotBase64:o,screenshot:r,slicedScreenshotsBase64:a}}async getClickableElementsWithAXTree(t,e={}){ce.debug("\u{1F333} Using CDP Accessibility Tree for element detection");let r;e.useCleanScreenshot&&(r=await t.screenshot({type:"png",fullPage:!1}));let n=await t.context().newCDPSession(t),{nodes:o}=await n.send("Accessibility.getFullAXTree",{depth:-1});ce.debug(`\u{1F4CA} Got ${o.length} AXNodes from accessibility tree`);let a=o.filter(_=>{if(_.ignored)return!1;let M=_.role?.value;return!(!M||!cl.has(M)||_.properties?.find(B=>B.name==="disabled")?.value?.value||!_.backendDOMNodeId)});ce.debug(`\u2705 Found ${a.length} interactive elements from AXTree`);let i=o.filter(_=>_.role?.value==="button");ce.debug(`\u{1F518} Total buttons in AXTree: ${i.length}`);for(let _ of i){let M=[];_.ignored&&M.push("ignored"),_.backendDOMNodeId||M.push("no-backendDOMNodeId"),_.properties?.find(B=>B.name==="disabled")?.value?.value&&M.push("disabled"),ce.debug(` - "${_.name?.value||"(no name)"}" ${M.length>0?`[SKIPPED: ${M.join(", ")}]`:"[INCLUDED]"}`)}let s=new Set(a.map(_=>_.backendDOMNodeId)),l=await this.getElementsWithEventListeners(n,e.eventListenerLimit??500),c=0;for(let _ of l)s.has(_.backendNodeId)||(a.push({nodeId:`synthetic-${_.backendNodeId}`,ignored:!1,backendDOMNodeId:_.backendNodeId,role:{type:"role",value:"generic"},name:{type:"string",value:""},properties:[{name:"eventListeners",value:{type:"string",value:_.eventTypes.join(",")}}]}),s.add(_.backendNodeId),c++);ce.debug(`\u{1F3AF} Added ${c} elements from event listeners (total: ${a.length})`);let p=await this.resolveAXNodesToDOM(n,a),h=p.filter(_=>_.isVisible&&_.isInViewport&&_.isTopElement&&_.boundingRect),g=p.filter(_=>!(_.isVisible&&_.isInViewport&&_.isTopElement&&_.boundingRect));if(g.length>0){ce.debug(`\u{1F6AB} Filtered out ${g.length} elements:`);for(let _ of g){let M=[];_.isVisible||M.push("not-visible"),_.isInViewport||M.push("not-in-viewport"),_.isTopElement||M.push("not-top-element"),_.boundingRect||M.push("no-bounding-rect"),ce.debug(` - <${_.tagName}> "${_.axNode.name?.value||""}" [${M.join(", ")}]`)}}ce.debug(`\u{1F441}\uFE0F ${h.length} elements are visible and in viewport`);let{domState:y,highlightIndex:S}=await this.buildDomStateFromAXTree(h);e.highlightElements!==!1&&S>0&&(await this.renderHighlightsForAXElements(t,h.slice(0,S)),await t.waitForTimeout(100)),e.useCleanScreenshot||(r=await t.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(t);try{await n.detach()}catch{}if(!r)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let f=r.toString("base64"),b;if(e.useSlicedScreenshots)try{b=(await ll(r,{resize:e.resizeSlicedScreenshots})).map(_=>_.toString("base64"))}catch(_){ce.warn("Failed to slice screenshot:",_)}return{domState:y,screenshotBase64:f,screenshot:r,slicedScreenshotsBase64:b}}async resolveAXNodesToDOM(t,e){let r=[],n=e.map(a=>a.backendDOMNodeId).filter(a=>a!==void 0);if(n.length===0)return r;let o=[];for(let a of n)try{let{object:i}=await t.send("DOM.resolveNode",{backendNodeId:a});o.push(i.objectId||null)}catch{o.push(null)}for(let a=0;a<e.length;a++){let i=e[a],s=o[a];if(s)try{let{result:l}=await t.send("Runtime.callFunctionOn",{objectId:s,functionDeclaration:`function() {
|
|
3867
3870
|
const el = this;
|
|
3868
3871
|
const rect = el.getBoundingClientRect();
|
|
3869
3872
|
const rects = el.getClientRects();
|
|
@@ -3947,7 +3950,7 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
3947
3950
|
} : null,
|
|
3948
3951
|
clientRects: clientRectsArray
|
|
3949
3952
|
};
|
|
3950
|
-
}`,returnByValue:!0});l.value&&r.push({axNode:i,...l.value})}catch(l){Ee.debug(`Failed to resolve element: ${l}`)}}return r}async getElementsWithEventListeners(t,e=Vh){let r=[];try{let{root:n}=await t.send("DOM.getDocument",{depth:0}),o=Bh.join(","),{nodeIds:a}=await t.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:o});Ee.debug(`\u{1F50D} Checking ${Math.min(a.length,e)} elements for event listeners`);for(let i of a.slice(0,e))try{let{object:s}=await t.send("DOM.resolveNode",{nodeId:i});if(!s.objectId)continue;let{listeners:l}=await t.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(p=>Ta.has(p.type));if(c.length>0){let{node:p}=await t.send("DOM.describeNode",{nodeId:i});r.push({backendNodeId:p.backendNodeId,eventTypes:c.map(h=>h.type)})}await t.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}Ee.debug(`\u2705 Found ${r.length} elements with interaction event listeners`)}catch(n){Ee.warn("Failed to get elements with event listeners:",n)}return r}async buildDomStateFromAXTree(t){let e=new Map,r=new ar("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let o of t){let a=o.axNode.role?.value||"",i=o.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(a),l=new ar(o.tagName,o.xpath,o.attributes,[],o.isVisible,!0,a==="scrollbar",s,o.isTopElement,o.isInViewport,!1,n,o.boundingRect?{topLeft:{x:o.boundingRect.x,y:o.boundingRect.y},topRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y},bottomLeft:{x:o.boundingRect.x,y:o.boundingRect.y+o.boundingRect.height},bottomRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y+o.boundingRect.height},center:{x:o.boundingRect.x+o.boundingRect.width/2,y:o.boundingRect.y+o.boundingRect.height/2},width:o.boundingRect.width,height:o.boundingRect.height}:null,null,null,[],r);if(i){let c=new ao(i,!0,l);l.children.push(c)}r.children.push(l),e.set(n,l),n++}return{domState:{elementTree:r,selectorMap:e},highlightIndex:n}}async renderHighlightsForAXElements(t,e){let r=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await t.evaluate(({elements:n,colors:o})=>{let a="playwright-highlight-container",i=document.getElementById(a);i||(i=document.createElement("div"),i.id=a,i.style.position="fixed",i.style.pointerEvents="none",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.zIndex="2147483647",i.style.backgroundColor="transparent",document.body.appendChild(i)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=o[l%o.length],p=s.boundingRect,h=document.createElement("div");h.style.position="fixed",h.style.border=`1px solid ${c}`,h.style.backgroundColor="transparent",h.style.pointerEvents="none",h.style.boxSizing="border-box",h.style.top=`${p.y}px`,h.style.left=`${p.x}px`,h.style.width=`${p.width}px`,h.style.height=`${p.height}px`,i.appendChild(h);let m=document.createElement("div");m.style.position="fixed",m.style.background=c,m.style.color="white",m.style.padding="1px 4px",m.style.borderRadius="4px",m.style.fontSize=l>=100?"8px":"12px",m.textContent=String(l);let g=Math.max(0,p.y-16),T=Math.max(0,Math.min(p.x+p.width-20,window.innerWidth-25));m.style.top=`${g}px`,m.style.left=`${T}px`,i.appendChild(m)})},{elements:e,colors:r})}async removeHighlights(t){try{await t.evaluate(()=>{let e=document.getElementById("playwright-highlight-container");e&&e.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(r=>r()),window._highlightCleanupFunctions=[])}),Ee.debug("\u2705 Highlights removed from page")}catch(e){Ee.warn("Failed to remove highlights:",e.message)}}async getCrossOriginIframes(t){let e=await t.locator("iframe").filter({hasNot:t.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),r=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=t.url(),o=new URL(n).hostname,a=t.frames(),i=[];for(let s of a){let l=s.url();try{let c=new URL(l).hostname;c&&c!==o&&!e.includes(l)&&!r(l)&&i.push(l)}catch{continue}}return i}async buildDomTree(t,e,r,n,o,a,i,s="all"){if(await t.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(e0(t.url()))return[new ar("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let l={doHighlightElements:e,focusHighlightIndex:r,viewportExpansion:n,debugMode:!1,interactiveClassNames:o,alwaysHighlightFileInput:a,sameRectIoUThreshold:i,actionIntent:s,domTreeRoot:this.domTreeRoot};Ee.debug(`\u{1F527} Starting JavaScript DOM analysis for ${t.url().slice(0,50)}...`);let c,p=null;if(this.useDomTreeTs&&e)try{let m={...l,phase:"boxes",grayscaleImage:null},g=await t.evaluate(({code:V,argsObj:X})=>new Function("return "+V)()(X),{code:this.jsCode,argsObj:m});Ee.debug(`\u{1F4E6} Phase 1: Drew ${g.elementData?.length||0} bounding boxes`);let T=await t.screenshot({type:"png",fullPage:!1});Ee.debug("\u{1F4F8} Captured screenshot with bounding boxes");let y=performance.now(),b=await $h(T);p=b.pixels;let _=Math.round(performance.now()-y);Ee.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${b.width}x${b.height}) in ${_}ms`);let D={...l,phase:"labels",grayscaleImage:p,elementData:g.elementData};c=await t.evaluate(({code:V,argsObj:X})=>new Function("return "+V)()(X),{code:this.jsCode,argsObj:D}),c.map=g.map,c.rootId=g.rootId,c.highlightCount=g.highlightCount,c.perfMetrics=g.perfMetrics,Ee.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(m){Ee.warn("Two-phase rendering failed, falling back to legacy mode:",m.message),p=null;let g={...l,grayscaleImage:null};c=await t.evaluate(({code:T,argsObj:y})=>new Function("return "+T)()(y),{code:this.jsCode,argsObj:g}),Ee.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{c=await t.evaluate(({code:m,argsObj:g})=>new Function("return "+m)()(g),{code:this.jsCode,argsObj:l}),Ee.debug("\u2705 JavaScript DOM analysis completed")}catch(m){throw Ee.error("Error evaluating JavaScript:",m.message),m}if(!c||typeof c!="object")throw Ee.error("JavaScript returned invalid result:",c),new Error("JavaScript DOM analysis returned invalid result");if(!c.map||!c.rootId)throw Ee.error("JavaScript result missing map or rootId:",JSON.stringify(c,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(s!=="all"&&c.highlightCount===0){Ee.debug(`\u26A0\uFE0F No elements matched intent '${s}', falling back to 'all'`);let m={...l,actionIntent:"all"};c=await t.evaluate(({code:g,argsObj:T})=>new Function("return "+g)()(T),{code:this.jsCode,argsObj:m})}if(c&&c.perfMetrics){let m=c.perfMetrics.nodeMetrics?.totalNodes??0,g=0;if(c.map)for(let y of Object.values(c.map))typeof y=="object"&&y!==null&&y.isInteractive&&g++;let T=t.url().length>50?t.url().slice(0,50)+"...":t.url();Ee.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${T} interactive=${g}/${m}`)}Ee.debug("\u{1F504} Starting TypeScript DOM tree construction...");let h=await this.constructDomTree(c);return Ee.debug("\u2705 TypeScript DOM tree construction completed"),h}async constructDomTree(t){let e=t.map,r=t.rootId,n=new Map,o=new Map;for(let[i,s]of Object.entries(e)){let[l,c]=this.parseNode(s);if(l!==null&&(o.set(i,l),l instanceof ar&&l.highlightIndex!==null&&n.set(l.highlightIndex,l),l instanceof ar))for(let p of c){let h=o.get(p);h&&(h.parent=l,l.children.push(h))}}let a=o.get(r);if(!a||!(a instanceof ar))throw new Error("Failed to parse HTML to dictionary");return[a,n]}parseNode(t){if(!t)return[null,[]];if(t.type==="TEXT_NODE")return[new ao(t.text,t.isVisible,null),[]];let e=null;t.viewport&&(e={width:t.viewport.width,height:t.viewport.height,scrollX:t.viewport.scrollX,scrollY:t.viewport.scrollY});let r=t.shadowHostXPaths??[],n=new ar(t.tagName,t.xpath,t.attributes||{},[],t.isVisible??!1,t.isInteractive??!1,t.isScrollable??!1,t.markAsClickable??!1,t.isTopElement??!1,t.isInViewport??!1,t.shadowRoot??!1,t.highlightIndex??null,t.viewportCoordinates??null,t.pageCoordinates??null,e,r,null),o=t.children||[];return[n,o]}};import{createHash as ul}from"crypto";var yO=class{static convertDomElementToHistoryElement(t){let e=this.getParentBranchPath(t),r=this.generateCssSelector(t);return{tagName:t.tagName,xpath:t.xpath,highlightIndex:t.highlightIndex,entireParentBranchPath:e,attributes:t.attributes,shadowRoot:t.shadowRoot,cssSelector:r,pageCoordinates:t.pageCoordinates,viewportCoordinates:t.viewportCoordinates,viewportInfo:t.viewportInfo}}static findHistoryElementInTree(t,e){let r=this.hashDomHistoryElement(t),n=o=>{if(o.highlightIndex!==null){let a=this.hashDomElement(o);if(this.compareHashes(a,r))return o}for(let a of o.children)if(a instanceof ar){let i=n(a);if(i!==null)return i}return null};return n(e)}static compareHistoryElementAndDomElement(t,e){let r=this.hashDomHistoryElement(t),n=this.hashDomElement(e);return this.compareHashes(r,n)}static hashDomHistoryElement(t){let e=this.parentBranchPathHash(t.entireParentBranchPath),r=this.attributesHash(t.attributes),n=this.xpathHash(t.xpath);return{branchPathHash:e,attributesHash:r,xpathHash:n}}static hashDomElement(t){let e=this.getParentBranchPath(t),r=this.parentBranchPathHash(e),n=this.attributesHash(t.attributes),o=this.xpathHash(t.xpath);return{branchPathHash:r,attributesHash:n,xpathHash:o}}static getParentBranchPath(t){let e=[],r=t;for(;r!==null&&r.parent!==null;)e.push(r),r=r.parent;return e.reverse(),e.map(n=>n.tagName)}static parentBranchPathHash(t){let e=t.join("/");return ul("sha256").update(e).digest("hex")}static attributesHash(t){let e=Object.entries(t).map(([r,n])=>`${r}=${n}`).join("");return ul("sha256").update(e).digest("hex")}static xpathHash(t){return ul("sha256").update(t).digest("hex")}static compareHashes(t,e){return t.branchPathHash===e.branchPathHash&&t.attributesHash===e.attributesHash&&t.xpathHash===e.xpathHash}static generateCssSelector(t){let e=t.attributes.id;if(e)return`#${e}`;let r=t.attributes.class;if(r){let n=r.split(/\s+/).filter(o=>o.trim());if(n.length>0)return`${t.tagName}.${n.join(".")}`}return t.tagName}};import{z as Or}from"zod/v4";import{z as yf}from"zod/v4";import{z as vl}from"zod/v4";import{z as We}from"zod/v4";import{z as Sa}from"zod/v4";import{z as Nt}from"zod/v4";import{z as ht}from"zod/v4";var Hf=Ua(gl(),1),qf=Ua(gl(),1);import{z as Re}from"zod";var x0="vercel.ai.gateway.error",yl=Symbol.for(x0),af,sf,Tt=class Of extends(sf=Error,af=yl,sf){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[af]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return Of.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&yl in e&&e[yl]===!0}},Nf="GatewayAuthenticationError",S0=`vercel.ai.gateway.error.${Nf}`,lf=Symbol.for(S0),cf,uf,Ca=class Mf extends(uf=Tt,cf=lf,uf){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[cf]=!0,this.name=Nf,this.type="authentication_error"}static isInstance(e){return Tt.hasMarker(e)&&lf in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a}){let i;return e?i=`AI Gateway authentication failed: Invalid API key.
|
|
3953
|
+
}`,returnByValue:!0});l.value&&r.push({axNode:i,...l.value})}catch(l){ce.debug(`Failed to resolve element: ${l}`)}}return r}async getElementsWithEventListeners(t,e=Vh){let r=[];try{let{root:n}=await t.send("DOM.getDocument",{depth:0}),o=Bh.join(","),{nodeIds:a}=await t.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:o});ce.debug(`\u{1F50D} Checking ${Math.min(a.length,e)} elements for event listeners`);for(let i of a.slice(0,e))try{let{object:s}=await t.send("DOM.resolveNode",{nodeId:i});if(!s.objectId)continue;let{listeners:l}=await t.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(p=>Ta.has(p.type));if(c.length>0){let{node:p}=await t.send("DOM.describeNode",{nodeId:i});r.push({backendNodeId:p.backendNodeId,eventTypes:c.map(h=>h.type)})}await t.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}ce.debug(`\u2705 Found ${r.length} elements with interaction event listeners`)}catch(n){ce.warn("Failed to get elements with event listeners:",n)}return r}async buildDomStateFromAXTree(t){let e=new Map,r=new ar("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let o of t){let a=o.axNode.role?.value||"",i=o.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(a),l=new ar(o.tagName,o.xpath,o.attributes,[],o.isVisible,!0,a==="scrollbar",s,o.isTopElement,o.isInViewport,!1,n,o.boundingRect?{topLeft:{x:o.boundingRect.x,y:o.boundingRect.y},topRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y},bottomLeft:{x:o.boundingRect.x,y:o.boundingRect.y+o.boundingRect.height},bottomRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y+o.boundingRect.height},center:{x:o.boundingRect.x+o.boundingRect.width/2,y:o.boundingRect.y+o.boundingRect.height/2},width:o.boundingRect.width,height:o.boundingRect.height}:null,null,null,[],r);if(i){let c=new ao(i,!0,l);l.children.push(c)}r.children.push(l),e.set(n,l),n++}return{domState:{elementTree:r,selectorMap:e},highlightIndex:n}}async renderHighlightsForAXElements(t,e){let r=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await t.evaluate(({elements:n,colors:o})=>{let a="playwright-highlight-container",i=document.getElementById(a);i||(i=document.createElement("div"),i.id=a,i.style.position="fixed",i.style.pointerEvents="none",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.zIndex="2147483647",i.style.backgroundColor="transparent",document.body.appendChild(i)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=o[l%o.length],p=s.boundingRect,h=document.createElement("div");h.style.position="fixed",h.style.border=`1px solid ${c}`,h.style.backgroundColor="transparent",h.style.pointerEvents="none",h.style.boxSizing="border-box",h.style.top=`${p.y}px`,h.style.left=`${p.x}px`,h.style.width=`${p.width}px`,h.style.height=`${p.height}px`,i.appendChild(h);let g=document.createElement("div");g.style.position="fixed",g.style.background=c,g.style.color="white",g.style.padding="1px 4px",g.style.borderRadius="4px",g.style.fontSize=l>=100?"8px":"12px",g.textContent=String(l);let y=Math.max(0,p.y-16),S=Math.max(0,Math.min(p.x+p.width-20,window.innerWidth-25));g.style.top=`${y}px`,g.style.left=`${S}px`,i.appendChild(g)})},{elements:e,colors:r})}async removeHighlights(t){let e=()=>{let r=document.getElementById("playwright-highlight-container");r&&r.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(n=>n()),window._highlightCleanupFunctions=[])};try{await t.evaluate(e),ce.debug("\u2705 Highlights removed from page")}catch(r){ce.warn("Failed to remove highlights:",r.message)}for(let r of t.frames())if(r.url().startsWith("chrome-extension://"))try{await r.evaluate(e)}catch{}}async getCrossOriginIframes(t){let e=await t.locator("iframe").filter({hasNot:t.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),r=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=t.url(),o=new URL(n).hostname,a=t.frames(),i=[];for(let s of a){let l=s.url();try{let c=new URL(l).hostname;c&&c!==o&&!e.includes(l)&&!r(l)&&i.push(l)}catch{continue}}return i}async buildDomTree(t,e,r,n,o,a,i,s="all"){if(await t.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(e0(t.url()))return[new ar("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let l={doHighlightElements:e,focusHighlightIndex:r,viewportExpansion:n,debugMode:!1,interactiveClassNames:o,alwaysHighlightFileInput:a,sameRectIoUThreshold:i,actionIntent:s,domTreeRoot:this.domTreeRoot};ce.debug(`\u{1F527} Starting JavaScript DOM analysis for ${t.url().slice(0,50)}...`);let c,p=null;if(this.useDomTreeTs&&e)try{let f={...l,phase:"boxes",grayscaleImage:null},b=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:f});ce.debug(`\u{1F4E6} Phase 1: Drew ${b.elementData?.length||0} bounding boxes`);let _=await t.screenshot({type:"png",fullPage:!1});ce.debug("\u{1F4F8} Captured screenshot with bounding boxes");let M=performance.now(),B=await Gh(_);p=B.pixels;let Z=Math.round(performance.now()-M);ce.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${B.width}x${B.height}) in ${Z}ms`);let N={...l,phase:"labels",grayscaleImage:p,elementData:b.elementData};c=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:N}),c.map=b.map,c.rootId=b.rootId,c.highlightCount=b.highlightCount,c.perfMetrics=b.perfMetrics,ce.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(f){ce.warn("Two-phase rendering failed, falling back to legacy mode:",f.message),p=null;let b={...l,grayscaleImage:null};c=await t.evaluate(({code:_,argsObj:M})=>new Function("return "+_)()(M),{code:this.jsCode,argsObj:b}),ce.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{c=await t.evaluate(({code:f,argsObj:b})=>new Function("return "+f)()(b),{code:this.jsCode,argsObj:l}),ce.debug("\u2705 JavaScript DOM analysis completed")}catch(f){throw ce.error("Error evaluating JavaScript:",f.message),f}if(!c||typeof c!="object")throw ce.error("JavaScript returned invalid result:",c),new Error("JavaScript DOM analysis returned invalid result");if(!c.map||!c.rootId)throw ce.error("JavaScript result missing map or rootId:",JSON.stringify(c,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(s!=="all"&&c.highlightCount===0){ce.debug(`\u26A0\uFE0F No elements matched intent '${s}', falling back to 'all'`);let f={...l,actionIntent:"all"};c=await t.evaluate(({code:b,argsObj:_})=>new Function("return "+b)()(_),{code:this.jsCode,argsObj:f})}let h=Object.entries(c.map).filter(([,f])=>f.tagName==="iframe");ce.debug(`\u{1F50D} [ext-iframe] Total iframe nodes in map: ${h.length}`);for(let[f,b]of h){let _=b;ce.debug(`\u{1F50D} [ext-iframe] iframe node id=${f} src=${_.attributes?.src} inaccessibleFrame=${_.inaccessibleFrame}`)}let g=t.frames();ce.debug(`\u{1F50D} [ext-iframe] Playwright frames count: ${g.length}`);for(let f of g)ce.debug(`\u{1F50D} [ext-iframe] Playwright frame url=${f.url()}`);let y=[];for(let[f,b]of Object.entries(c.map)){let _=b;_.inaccessibleFrame&&_.attributes?.src?.startsWith("chrome-extension://")&&y.push({nodeId:f,src:_.attributes.src})}if(ce.debug(`\u{1F50D} [ext-iframe] Inaccessible extension iframes found: ${y.length}`),y.length>0){ce.debug(`\u{1F50C} Found ${y.length} inaccessible extension iframe(s), processing via Playwright frames`);let f=-1;for(let b of Object.values(c.map)){let _=b;_.highlightIndex!=null&&(f=Math.max(f,_.highlightIndex))}ce.debug(`\u{1F50D} [ext-iframe] Main page max highlight index: ${f}`);for(let b=0;b<y.length;b++){let{nodeId:_,src:M}=y[b];ce.debug(`\u{1F50D} [ext-iframe] Processing extension iframe [${b}]: ${M}`);let B=(()=>{try{return new URL(M).origin}catch{return null}})(),Z=t.frames().find(N=>{if(N.url()===M)return!0;if(B)try{return new URL(N.url()).origin===B}catch{return!1}return!1});if(!Z){ce.debug(`\u26A0\uFE0F [ext-iframe] No Playwright frame found for extension iframe: ${M}`),ce.debug(`\u26A0\uFE0F [ext-iframe] Available frame URLs: ${t.frames().map(N=>N.url()).join(", ")}`);continue}ce.debug(`\u{1F50D} [ext-iframe] Found matching Playwright frame for: ${M} (frame url: ${Z.url()})`);try{let N={...l,initialHighlightIndex:f+1,domTreeRoot:"body"};ce.debug(`\u{1F50D} [ext-iframe] Running dom-tree in extension frame with initialHighlightIndex=${N.initialHighlightIndex}`);let R=await Z.evaluate(({code:Q,argsObj:X})=>new Function("return "+Q)()(X),{code:this.jsCode,argsObj:N});if(ce.debug(`\u{1F50D} [ext-iframe] frameEval result: map size=${Object.keys(R?.map??{}).length} rootId=${R?.rootId}`),!R?.map||!R.rootId){ce.debug("\u26A0\uFE0F [ext-iframe] frameEval missing map or rootId, skipping");continue}let O=Object.values(R.map).filter(Q=>Q.highlightIndex!=null);ce.debug(`\u{1F50D} [ext-iframe] Interactive elements in extension frame: ${O.length}`);for(let Q of O){let X=Q;ce.debug(`\u{1F50D} [ext-iframe] - <${X.tagName}> highlightIndex=${X.highlightIndex} text="${X.children?.length?"...":""}"`)}for(let Q of Object.values(R.map)){let X=Q;X.highlightIndex!=null&&(f=Math.max(f,X.highlightIndex))}let ee=`ext_${b}_`;for(let[Q,X]of Object.entries(R.map)){let W={...X};W.children&&(W.children=W.children.map(ue=>`${ee}${ue}`)),c.map[`${ee}${Q}`]=W}let E=c.map[_];E?(E.children=[...E.children||[],`${ee}${R.rootId}`],ce.debug(`\u{1F50D} [ext-iframe] Attached frame root to iframe node ${_}`)):ce.debug(`\u26A0\uFE0F [ext-iframe] iframe node ${_} not found in map`),ce.debug(`\u2705 Merged extension iframe content from: ${M}`)}catch(N){ce.warn(`Failed to process extension iframe ${M}:`,N)}}}if(c&&c.perfMetrics){let f=c.perfMetrics.nodeMetrics?.totalNodes??0,b=0;if(c.map)for(let M of Object.values(c.map))typeof M=="object"&&M!==null&&M.isInteractive&&b++;let _=t.url().length>50?t.url().slice(0,50)+"...":t.url();ce.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${_} interactive=${b}/${f}`)}ce.debug("\u{1F504} Starting TypeScript DOM tree construction...");let S=await this.constructDomTree(c);return ce.debug("\u2705 TypeScript DOM tree construction completed"),S}async constructDomTree(t){let e=t.map,r=t.rootId,n=new Map,o=new Map,a=new Map;for(let[s,l]of Object.entries(e)){let[c,p]=this.parseNode(l);c!==null&&(o.set(s,c),a.set(s,p),c instanceof ar&&c.highlightIndex!==null&&n.set(c.highlightIndex,c))}for(let[s,l]of a){let c=o.get(s);if(c instanceof ar)for(let p of l){let h=o.get(p);h&&(h.parent=c,c.children.push(h))}}let i=o.get(r);if(!i||!(i instanceof ar))throw new Error("Failed to parse HTML to dictionary");return[i,n]}parseNode(t){if(!t)return[null,[]];if(t.type==="TEXT_NODE")return[new ao(t.text,t.isVisible,null),[]];let e=null;t.viewport&&(e={width:t.viewport.width,height:t.viewport.height,scrollX:t.viewport.scrollX,scrollY:t.viewport.scrollY});let r=t.shadowHostXPaths??[],n=new ar(t.tagName,t.xpath,t.attributes||{},[],t.isVisible??!1,t.isInteractive??!1,t.isScrollable??!1,t.markAsClickable??!1,t.isTopElement??!1,t.isInViewport??!1,t.shadowRoot??!1,t.highlightIndex??null,t.viewportCoordinates??null,t.pageCoordinates??null,e,r,null),o=t.children||[];return[n,o]}};import{createHash as ul}from"crypto";var yO=class{static convertDomElementToHistoryElement(t){let e=this.getParentBranchPath(t),r=this.generateCssSelector(t);return{tagName:t.tagName,xpath:t.xpath,highlightIndex:t.highlightIndex,entireParentBranchPath:e,attributes:t.attributes,shadowRoot:t.shadowRoot,cssSelector:r,pageCoordinates:t.pageCoordinates,viewportCoordinates:t.viewportCoordinates,viewportInfo:t.viewportInfo}}static findHistoryElementInTree(t,e){let r=this.hashDomHistoryElement(t),n=o=>{if(o.highlightIndex!==null){let a=this.hashDomElement(o);if(this.compareHashes(a,r))return o}for(let a of o.children)if(a instanceof ar){let i=n(a);if(i!==null)return i}return null};return n(e)}static compareHistoryElementAndDomElement(t,e){let r=this.hashDomHistoryElement(t),n=this.hashDomElement(e);return this.compareHashes(r,n)}static hashDomHistoryElement(t){let e=this.parentBranchPathHash(t.entireParentBranchPath),r=this.attributesHash(t.attributes),n=this.xpathHash(t.xpath);return{branchPathHash:e,attributesHash:r,xpathHash:n}}static hashDomElement(t){let e=this.getParentBranchPath(t),r=this.parentBranchPathHash(e),n=this.attributesHash(t.attributes),o=this.xpathHash(t.xpath);return{branchPathHash:r,attributesHash:n,xpathHash:o}}static getParentBranchPath(t){let e=[],r=t;for(;r!==null&&r.parent!==null;)e.push(r),r=r.parent;return e.reverse(),e.map(n=>n.tagName)}static parentBranchPathHash(t){let e=t.join("/");return ul("sha256").update(e).digest("hex")}static attributesHash(t){let e=Object.entries(t).map(([r,n])=>`${r}=${n}`).join("");return ul("sha256").update(e).digest("hex")}static xpathHash(t){return ul("sha256").update(t).digest("hex")}static compareHashes(t,e){return t.branchPathHash===e.branchPathHash&&t.attributesHash===e.attributesHash&&t.xpathHash===e.xpathHash}static generateCssSelector(t){let e=t.attributes.id;if(e)return`#${e}`;let r=t.attributes.class;if(r){let n=r.split(/\s+/).filter(o=>o.trim());if(n.length>0)return`${t.tagName}.${n.join(".")}`}return t.tagName}};import{z as Or}from"zod/v4";import{z as yf}from"zod/v4";import{z as vl}from"zod/v4";import{z as We}from"zod/v4";import{z as Sa}from"zod/v4";import{z as Nt}from"zod/v4";import{z as ht}from"zod/v4";var Hf=Fa(gl(),1),qf=Fa(gl(),1);import{z as Re}from"zod";var x0="vercel.ai.gateway.error",yl=Symbol.for(x0),af,sf,Tt=class Of extends(sf=Error,af=yl,sf){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[af]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return Of.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&yl in e&&e[yl]===!0}},Nf="GatewayAuthenticationError",S0=`vercel.ai.gateway.error.${Nf}`,lf=Symbol.for(S0),cf,uf,Ca=class Mf extends(uf=Tt,cf=lf,uf){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[cf]=!0,this.name=Nf,this.type="authentication_error"}static isInstance(e){return Tt.hasMarker(e)&&lf in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a}){let i;return e?i=`AI Gateway authentication failed: Invalid API key.
|
|
3951
3954
|
|
|
3952
3955
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
3953
3956
|
|
|
@@ -3962,7 +3965,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
3962
3965
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
3963
3966
|
|
|
3964
3967
|
Option 2 - OIDC token:
|
|
3965
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Mf({message:i,statusCode:o,cause:a})}},Pf="GatewayInvalidRequestError",C0=`vercel.ai.gateway.error.${Pf}`,df=Symbol.for(C0),pf,hf,I0=class extends(hf=Tt,pf=df,hf){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[pf]=!0,this.name=Pf,this.type="invalid_request_error"}static isInstance(t){return Tt.hasMarker(t)&&df in t}},Df="GatewayRateLimitError",A0=`vercel.ai.gateway.error.${Df}`,ff=Symbol.for(A0),mf,gf,k0=class extends(gf=Tt,mf=ff,gf){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[mf]=!0,this.name=Df,this.type="rate_limit_exceeded"}static isInstance(t){return Tt.hasMarker(t)&&ff in t}},jf="GatewayModelNotFoundError",R0=`vercel.ai.gateway.error.${jf}`,vf=Symbol.for(R0),O0=q(()=>H(yf.object({modelId:yf.string()}))),bf,_f,N0=class extends(_f=Tt,bf=vf,_f){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[bf]=!0,this.name=jf,this.type="model_not_found",this.modelId=r}static isInstance(t){return Tt.hasMarker(t)&&vf in t}},Lf="GatewayInternalServerError",M0=`vercel.ai.gateway.error.${Lf}`,wf=Symbol.for(M0),Ef,Tf,xf=class extends(Tf=Tt,Ef=wf,Tf){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Ef]=!0,this.name=Lf,this.type="internal_server_error"}static isInstance(t){return Tt.hasMarker(t)&&wf in t}},Uf="GatewayResponseError",P0=`vercel.ai.gateway.error.${Uf}`,Sf=Symbol.for(P0),Cf,If,D0=class extends(If=Tt,Cf=Sf,If){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:o}={}){super({message:t,statusCode:e,cause:o}),this[Cf]=!0,this.name=Uf,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return Tt.hasMarker(t)&&Sf in t}};async function Af({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){let a=await nt({value:t,schema:j0});if(!a.success)return new D0({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:a.error,cause:n});let i=a.value,s=i.error.type,l=i.error.message;switch(s){case"authentication_error":return Ca.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new I0({message:l,statusCode:e,cause:n});case"rate_limit_exceeded":return new k0({message:l,statusCode:e,cause:n});case"model_not_found":{let c=await nt({value:i.error.param,schema:O0});return new N0({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new xf({message:l,statusCode:e,cause:n});default:return new xf({message:l,statusCode:e,cause:n})}}var j0=q(()=>H(Or.object({error:Or.object({message:Or.string(),type:Or.string().nullish(),param:Or.unknown().nullish(),code:Or.union([Or.string(),Or.number()]).nullish()})})));function Nr(t,e){var r;return Tt.isInstance(t)?t:Ge.isInstance(t)?Af({response:L0(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):Af({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function L0(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var Ff="ai-gateway-auth-method";async function vn(t){let e=await nt({value:t[Ff],schema:U0});return e.success?e.value:void 0}var U0=q(()=>H(vl.union([vl.literal("api-key"),vl.literal("oidc")]))),kf=class{constructor(t){this.config=t}async getAvailableModels(){try{let{value:t}=await za({url:`${this.config.baseURL}/config`,headers:await Te(this.config.headers()),successfulResponseHandler:qe(F0),failedResponseHandler:Qe({errorSchema:We.any(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Nr(t)}}async getCredits(){try{let t=new URL(this.config.baseURL),{value:e}=await za({url:`${t.origin}/v1/credits`,headers:await Te(this.config.headers()),successfulResponseHandler:qe(H0),failedResponseHandler:Qe({errorSchema:We.any(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Nr(t)}}},F0=q(()=>H(We.object({models:We.array(We.object({id:We.string(),name:We.string(),description:We.string().nullish(),pricing:We.object({input:We.string(),output:We.string(),input_cache_read:We.string().nullish(),input_cache_write:We.string().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:We.object({specificationVersion:We.literal("v3"),provider:We.string(),modelId:We.string()}),modelType:We.enum(["language","embedding","image"]).nullish()}))}))),H0=q(()=>H(We.object({balance:We.string(),total_used:We.string()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),q0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){let{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){let{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,o=await Te(this.config.headers());try{let{responseHeaders:a,value:i,rawValue:s}=await Fe({url:this.getUrl(),headers:$e(o,t.headers,this.getModelConfigHeaders(this.modelId,!1),await Te(this.config.o11yHeaders)),body:e,successfulResponseHandler:qe(Sa.any()),failedResponseHandler:Qe({errorSchema:Sa.any(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:e},response:{headers:a,body:s},warnings:r}}catch(a){throw await Nr(a,await vn(o))}}async doStream(t){let{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,o=await Te(this.config.headers());try{let{value:a,responseHeaders:i}=await Fe({url:this.getUrl(),headers:$e(o,t.headers,this.getModelConfigHeaders(this.modelId,!0),await Te(this.config.o11yHeaders)),body:e,successfulResponseHandler:Sr(Sa.any()),failedResponseHandler:Qe({errorSchema:Sa.any(),errorToMessage:s=>s}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(s){r.length>0&&s.enqueue({type:"stream-start",warnings:r})},transform(s,l){if(s.success){let c=s.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(s.error)}})),request:{body:e},response:{headers:i}}}catch(a){throw await Nr(a,await vn(o))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(let e of t.prompt)for(let r of e.content)if(this.isFilePart(r)){let n=r;if(n.data instanceof Uint8Array){let o=Uint8Array.from(n.data),a=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},G0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var o;let a=await Te(this.config.headers());try{let{responseHeaders:i,value:s,rawValue:l}=await Fe({url:this.getUrl(),headers:$e(a,e??{},this.getModelConfigHeaders(),await Te(this.config.o11yHeaders)),body:{values:t,...n?{providerOptions:n}:{}},successfulResponseHandler:qe($0),failedResponseHandler:Qe({errorSchema:Nt.any(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(o=s.usage)!=null?o:void 0,providerMetadata:s.providerMetadata,response:{headers:i,body:l},warnings:[]}}catch(i){throw await Nr(i,await vn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},$0=q(()=>H(Nt.object({embeddings:Nt.array(Nt.array(Nt.number())),usage:Nt.object({tokens:Nt.number()}).nullish(),providerMetadata:Nt.record(Nt.string(),Nt.record(Nt.string(),Nt.unknown())).optional()}))),B0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,files:a,mask:i,providerOptions:s,headers:l,abortSignal:c}){var p;let h=await Te(this.config.headers());try{let{responseHeaders:m,value:g,rawValue:T}=await Fe({url:this.getUrl(),headers:$e(h,l??{},this.getModelConfigHeaders(),await Te(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s},...a&&{files:a.map(y=>Rf(y))},...i&&{mask:Rf(i)}},successfulResponseHandler:qe(z0),failedResponseHandler:Qe({errorSchema:ht.any(),errorToMessage:y=>y}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:g.images,warnings:(p=g.warnings)!=null?p:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:m}}}catch(m){throw Nr(m,await vn(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function Rf(t){return t.type==="file"&&t.data instanceof Uint8Array?{...t,data:Jt(t.data)}:t}var V0=ht.object({images:ht.array(ht.unknown()).optional()}).catchall(ht.unknown()),z0=ht.object({images:ht.array(ht.string()),warnings:ht.array(ht.object({type:ht.literal("other"),message:ht.string()})).optional(),providerMetadata:ht.record(ht.string(),V0).optional()}),W0=q(()=>H(Re.object({query:Re.union([Re.string(),Re.array(Re.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Re.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Re.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Re.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Re.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Re.array(Re.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Re.array(Re.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Re.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Re.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Re.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Re.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Re.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),J0=q(()=>H(Re.union([Re.object({results:Re.array(Re.object({title:Re.string(),url:Re.string(),snippet:Re.string(),date:Re.string().optional(),lastUpdated:Re.string().optional()})),id:Re.string()}),Re.object({error:Re.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Re.number().optional(),message:Re.string()})]))),K0=Ze({id:"gateway.perplexity_search",inputSchema:W0,outputSchema:J0}),Y0=(t={})=>K0(t),X0={perplexitySearch:Y0};async function Z0(){var t;return(t=(0,Hf.getContext)().headers)==null?void 0:t["x-vercel-id"]}var Q0="3.0.14",ex="0.0.1";function tx(t={}){var e,r;let n=null,o=null,a=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5,i=0,s=(r=dr(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{let y=await rx(t);return lt({Authorization:`Bearer ${y.token}`,"ai-gateway-protocol-version":ex,[Ff]:y.authMethod,...t.headers},`ai-sdk/gateway/${Q0}`)}catch(y){throw Ca.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:y})}},c=()=>{let y=Lt({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),b=Lt({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=Lt({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let D=await Z0();return{...y&&{"ai-o11y-deployment-id":y},...b&&{"ai-o11y-environment":b},..._&&{"ai-o11y-region":_},...D&&{"ai-o11y-request-id":D}}}},p=y=>new q0(y,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()}),h=async()=>{var y,b,_;let D=(_=(b=(y=t._internal)==null?void 0:y.currentDate)==null?void 0:b.call(y).getTime())!=null?_:Date.now();return(!n||D-i>a)&&(i=D,n=new kf({baseURL:s,headers:l,fetch:t.fetch}).getAvailableModels().then(V=>(o=V,V)).catch(async V=>{throw await Nr(V,await vn(await l()))})),o?Promise.resolve(o):n},m=async()=>new kf({baseURL:s,headers:l,fetch:t.fetch}).getCredits().catch(async y=>{throw await Nr(y,await vn(await l()))}),g=function(y){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(y)};g.specificationVersion="v3",g.getAvailableModels=h,g.getCredits=m,g.imageModel=y=>new B0(y,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()}),g.languageModel=p;let T=y=>new G0(y,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()});return g.embeddingModel=T,g.textEmbeddingModel=T,g.tools=X0,g}var Gf=tx();async function rx(t){let e=Lt({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return e?{token:e,authMethod:"api-key"}:{token:await(0,qf.getVercelOidcToken)(),authMethod:"oidc"}}import{z as uo}from"zod/v4";import{z as AS}from"zod/v4";import{z as Ke}from"zod/v4";import{z as Ma}from"zod/v4";import{z as Er}from"zod/v4";import{z as W}from"zod/v4";var $f=typeof globalThis=="object"?globalThis:global;var _r="1.9.0";var Bf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function nx(t){var e=new Set([t]),r=new Set,n=t.match(Bf);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===t};function a(s){return r.add(s),!1}function i(s){return e.add(s),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(Bf);if(!c)return a(l);var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||o.major!==p.major?a(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?i(l):a(l):o.minor<=p.minor?i(l):a(l)}}var Vf=nx(_r);var ox=_r.split(".")[0],io=Symbol.for("opentelemetry.js.api."+ox),so=$f;function bn(t,e,r,n){var o;n===void 0&&(n=!1);var a=so[io]=(o=so[io])!==null&&o!==void 0?o:{version:_r};if(!n&&a[t]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(i.stack||i.message),!1}if(a.version!==_r){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+_r);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+_r+"."),!0}function wr(t){var e,r,n=(e=so[io])===null||e===void 0?void 0:e.version;if(!(!n||!Vf(n)))return(r=so[io])===null||r===void 0?void 0:r[t]}function _n(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+_r+".");var r=so[io];r&&delete r[t]}var ax=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},ix=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},zf=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("verbose",this._namespace,e)},t}();function lo(t,e,r){var n=wr("diag");if(n)return r.unshift(e),n[t].apply(n,ix([],ax(r),!1))}var ut;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ut||(ut={}));function Wf(t,e){t<ut.NONE?t=ut.NONE:t>ut.ALL&&(t=ut.ALL),e=e||{};function r(n,o){var a=e[n];return typeof a=="function"&&t>=o?a.bind(e):function(){}}return{error:r("error",ut.ERROR),warn:r("warn",ut.WARN),info:r("info",ut.INFO),debug:r("debug",ut.DEBUG),verbose:r("verbose",ut.VERBOSE)}}var sx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},lx=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},cx="diag",wn=function(){function t(){function e(o){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var s=wr("diag");if(s)return s[o].apply(s,lx([],sx(a),!1))}}var r=this,n=function(o,a){var i,s,l;if(a===void 0&&(a={logLevel:ut.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof a=="number"&&(a={logLevel:a});var p=wr("diag"),h=Wf((s=a.logLevel)!==null&&s!==void 0?s:ut.INFO,o);if(p&&!a.suppressOverrideMessage){var m=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+m),h.warn("Current logger will overwrite one already registered from "+m)}return bn("diag",h,r,!0)};r.setLogger=n,r.disable=function(){_n(cx,r)},r.createComponentLogger=function(o){return new zf(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}();function Jf(t){return Symbol.for(t)}var ux=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var a=new t(r._currentContext);return a._currentContext.set(n,o),a},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),Kf=new ux;var dx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},px=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Yf=function(){function t(){}return t.prototype.active=function(){return Kf},t.prototype.with=function(e,r,n){for(var o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return r.call.apply(r,px([n],dx(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}();var hx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},fx=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},bl="context",mx=new Yf,Ia=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return bn(bl,e,wn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,fx([e,r,n],hx(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return wr(bl)||mx},t.prototype.disable=function(){this._getContextManager().disable(),_n(bl,wn.instance())},t}();var Aa;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Aa||(Aa={}));var _l="0000000000000000",wl="00000000000000000000000000000000",Xf={traceId:wl,spanId:_l,traceFlags:Aa.NONE};var Mr=function(){function t(e){e===void 0&&(e=Xf),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}();var El=Jf("OpenTelemetry Context Key SPAN");function ka(t){return t.getValue(El)||void 0}function Zf(){return ka(Ia.getInstance().active())}function co(t,e){return t.setValue(El,e)}function Qf(t){return t.deleteValue(El)}function em(t,e){return co(t,new Mr(e))}function Ra(t){var e;return(e=ka(t))===null||e===void 0?void 0:e.spanContext()}var gx=/^([0-9a-f]{32})$/i,yx=/^[0-9a-f]{16}$/i;function vx(t){return gx.test(t)&&t!==wl}function bx(t){return yx.test(t)&&t!==_l}function Oa(t){return vx(t.traceId)&&bx(t.spanId)}function tm(t){return new Mr(t)}var Tl=Ia.getInstance(),Na=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Tl.active());var o=!!r?.root;if(o)return new Mr;var a=n&&Ra(n);return _x(a)&&Oa(a)?new Mr(a):new Mr},t.prototype.startActiveSpan=function(e,r,n,o){var a,i,s;if(!(arguments.length<2)){arguments.length===2?s=r:arguments.length===3?(a=r,s=n):(a=r,i=n,s=o);var l=i??Tl.active(),c=this.startSpan(e,a,l),p=co(l,c);return Tl.with(p,s,void 0,c)}},t}();function _x(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var wx=new Na,rm=function(){function t(e,r,n,o){this._provider=e,this.name=r,this.version=n,this.options=o}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,o){var a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):wx},t}();var nm=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new Na},t}();var Ex=new nm,xl=function(){function t(){}return t.prototype.getTracer=function(e,r,n){var o;return(o=this.getDelegateTracer(e,r,n))!==null&&o!==void 0?o:new rm(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Ex},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,r,n)},t}();var En;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(En||(En={}));var Sl="trace",om=function(){function t(){this._proxyTracerProvider=new xl,this.wrapSpanContext=tm,this.isSpanContextValid=Oa,this.deleteSpan=Qf,this.getSpan=ka,this.getActiveSpan=Zf,this.getSpanContext=Ra,this.setSpan=co,this.setSpanContext=em}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=bn(Sl,this._proxyTracerProvider,wn.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return wr(Sl)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){_n(Sl,wn.instance()),this._proxyTracerProvider=new xl},t}();var Cl=om.getInstance();import{z as L}from"zod/v4";import{z as w}from"zod/v4";var xx=Object.defineProperty,Sx=(t,e)=>{for(var r in e)xx(t,r,{get:e[r],enumerable:!0})},mm="AI_InvalidArgumentError",gm=`vercel.ai.error.${mm}`,Cx=Symbol.for(gm),ym,ir=class extends oe{constructor({parameter:t,value:e,message:r}){super({name:mm,message:`Invalid argument for parameter ${t}: ${r}`}),this[ym]=!0,this.parameter=t,this.value=e}static isInstance(t){return oe.hasMarker(t,gm)}};ym=Cx;var Ix="AI_InvalidStreamPartError",Ax=`vercel.ai.error.${Ix}`,kx=Symbol.for(Ax),Rx;Rx=kx;var vm="AI_InvalidToolApprovalError",bm=`vercel.ai.error.${vm}`,Ox=Symbol.for(bm),_m,Nx=class extends oe{constructor({approvalId:t}){super({name:vm,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[_m]=!0,this.approvalId=t}static isInstance(t){return oe.hasMarker(t,bm)}};_m=Ox;var wm="AI_InvalidToolInputError",Em=`vercel.ai.error.${wm}`,Mx=Symbol.for(Em),Tm,Rl=class extends oe{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Tr(r)}`}){super({name:wm,message:n,cause:r}),this[Tm]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return oe.hasMarker(t,Em)}};Tm=Mx;var xm="AI_ToolCallNotFoundForApprovalError",Sm=`vercel.ai.error.${xm}`,Px=Symbol.for(Sm),Cm,Im=class extends oe{constructor({toolCallId:t,approvalId:e}){super({name:xm,message:`Tool call "${t}" not found for approval request "${e}".`}),this[Cm]=!0,this.toolCallId=t,this.approvalId=e}static isInstance(t){return oe.hasMarker(t,Sm)}};Cm=Px;var Dx="AI_NoImageGeneratedError",jx=`vercel.ai.error.${Dx}`,Lx=Symbol.for(jx),Ux;Ux=Lx;var Am="AI_NoObjectGeneratedError",km=`vercel.ai.error.${Am}`,Fx=Symbol.for(km),Rm,Pr=class extends oe{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:o,finishReason:a}){super({name:Am,message:t,cause:e}),this[Rm]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=a}static isInstance(t){return oe.hasMarker(t,km)}};Rm=Fx;var Om="AI_NoOutputGeneratedError",Nm=`vercel.ai.error.${Om}`,Hx=Symbol.for(Nm),Mm,qx=class extends oe{constructor({message:t="No output generated.",cause:e}={}){super({name:Om,message:t,cause:e}),this[Mm]=!0}static isInstance(t){return oe.hasMarker(t,Nm)}};Mm=Hx;var Pm="AI_NoSuchToolError",Dm=`vercel.ai.error.${Pm}`,Gx=Symbol.for(Dm),jm,Il=class extends oe{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:Pm,message:r}),this[jm]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return oe.hasMarker(t,Dm)}};jm=Gx;var Lm="AI_ToolCallRepairError",Um=`vercel.ai.error.${Lm}`,$x=Symbol.for(Um),Fm,Bx=class extends oe{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Tr(t)}`}){super({name:Lm,message:r,cause:t}),this[Fm]=!0,this.originalError=e}static isInstance(t){return oe.hasMarker(t,Um)}};Fm=$x;var Vx=class extends oe{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},zx="AI_UIMessageStreamError",Wx=`vercel.ai.error.${zx}`,Jx=Symbol.for(Wx),Kx;Kx=Jx;var Yx="AI_InvalidDataContentError",Xx=`vercel.ai.error.${Yx}`,Zx=Symbol.for(Xx),Qx;Qx=Zx;var Hm="AI_InvalidMessageRoleError",qm=`vercel.ai.error.${Hm}`,eS=Symbol.for(qm),Gm,tS=class extends oe{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Hm,message:e}),this[Gm]=!0,this.role=t}static isInstance(t){return oe.hasMarker(t,qm)}};Gm=eS;var rS="AI_MessageConversionError",nS=`vercel.ai.error.${rS}`,oS=Symbol.for(nS),aS;aS=oS;var $m="AI_RetryError",Bm=`vercel.ai.error.${$m}`,iS=Symbol.for(Bm),Vm,am=class extends oe{constructor({message:t,reason:e,errors:r}){super({name:$m,message:t}),this[Vm]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return oe.hasMarker(t,Bm)}};Vm=iS;function sS({warning:t,provider:e,model:r}){let n=`AI SDK Warning (${e} / ${r}):`;switch(t.type){case"unsupported":{let o=`${n} The feature "${t.feature}" is not supported.`;return t.details&&(o+=` ${t.details}`),o}case"compatibility":{let o=`${n} The feature "${t.feature}" is used in a compatibility mode.`;return t.details&&(o+=` ${t.details}`),o}case"other":return`${n} ${t.message}`;default:return`${n} ${JSON.stringify(t,null,2)}`}}var lS="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",im=!1,zm=t=>{if(t.warnings.length===0)return;let e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}im||(im=!0,console.info(lS));for(let r of t.warnings)console.warn(sS({warning:r,provider:t.provider,model:t.model}))}};function cS({provider:t,modelId:e}){zm({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:t,model:e})}function uS(t){return t.specificationVersion==="v3"?t:(cS({provider:t.provider,modelId:t.modelId}),new Proxy(t,{get(e,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{let o=await e.doGenerate(...n);return{...o,finishReason:Wm(o.finishReason),usage:Jm(o.usage)}};case"doStream":return async(...n)=>{let o=await e.doStream(...n);return{...o,stream:dS(o.stream)}};default:return e[r]}}}))}function dS(t){return t.pipeThrough(new TransformStream({transform(e,r){switch(e.type){case"finish":r.enqueue({...e,finishReason:Wm(e.finishReason),usage:Jm(e.usage)});break;default:r.enqueue(e);break}}}))}function Wm(t){return{unified:t==="unknown"?"other":t,raw:void 0}}function Jm(t){return{inputTokens:{total:t.inputTokens,noCache:void 0,cacheRead:t.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:t.outputTokens,text:void 0,reasoning:t.reasoningTokens}}}function sm(t){if(typeof t!="string"){if(t.specificationVersion!=="v3"&&t.specificationVersion!=="v2"){let e=t;throw new Vx({version:e.specificationVersion,provider:e.provider,modelId:e.modelId})}return uS(t)}return pS().languageModel(t)}function pS(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:Gf}function Km(t){if(t!=null)return typeof t=="number"?t:t.totalMs}function hS(t){if(!(t==null||typeof t=="number"))return t.stepMs}var fS=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var mS=t=>{let e=typeof t=="string"?Jr(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function gS(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?mS(t):t}function yS({data:t,signatures:e}){let r=gS(t),n=typeof r=="string"?Jr(r.substring(0,Math.min(r.length,24))):r;for(let o of e)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((a,i)=>a===null||n[i]===a))return o.mediaType}var Ym="6.0.35",vS=async({url:t})=>{var e;let r=t.toString();try{let n=await fetch(r,{headers:lt({},`ai-sdk/${Ym}`,_o())});if(!n.ok)throw new vo({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw vo.isInstance(n)?n:new vo({url:r,cause:n})}},bS=(t=vS)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function _S(t){try{let[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Xm=uo.union([uo.string(),uo.instanceof(Uint8Array),uo.instanceof(ArrayBuffer),uo.custom(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Zm(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){let{mediaType:e,base64Content:r}=_S(t.toString());if(e==null||r==null)throw new oe({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function wS(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Jt(new Uint8Array(t)):Jt(t)}function Ol(t){return t===void 0?[]:Array.isArray(t)?t:[t]}async function ES({prompt:t,supportedUrls:e,download:r=bS()}){let n=await xS(t.messages,r,e),o=[...t.system!=null?typeof t.system=="string"?[{role:"system",content:t.system}]:Ol(t.system).map(i=>({role:"system",content:i.content,providerOptions:i.providerOptions})):[],...t.messages.map(i=>TS({message:i,downloadedAssets:n}))],a=[];for(let i of o){if(i.role!=="tool"){a.push(i);continue}let s=a.at(-1);s?.role==="tool"?s.content.push(...i.content):a.push(i)}return a}function TS({message:t,downloadedAssets:e}){let r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>SS(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{let o=n.providerOptions;switch(n.type){case"file":{let{data:a,mediaType:i}=Zm(n.data);return{type:"file",data:a,filename:n.filename,mediaType:i??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:lm(n.output),providerOptions:o}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:lm(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:t.providerOptions};default:{let n=r;throw new tS({role:n})}}}async function xS(t,e,r){let n=t.filter(a=>a.role==="user").map(a=>a.content).filter(a=>Array.isArray(a)).flat().filter(a=>a.type==="image"||a.type==="file").map(a=>{var i;let s=(i=a.mediaType)!=null?i:a.type==="image"?"image/*":void 0,l=a.type==="image"?a.image:a.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:s,data:l}}).filter(a=>a.data instanceof URL).map(a=>({url:a.data,isUrlSupportedByModel:a.mediaType!=null&&ou({url:a.data.toString(),mediaType:a.mediaType,supportedUrls:r})})),o=await e(n);return Object.fromEntries(o.map((a,i)=>a==null?null:[n[i].url.toString(),{data:a.data,mediaType:a.mediaType}]).filter(a=>a!=null))}function SS(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n,o=t.type;switch(o){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${o}`)}let{data:a,mediaType:i}=Zm(n),s=i??t.mediaType,l=a;if(l instanceof URL){let c=e[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(r=yS({data:l,signatures:fS}))!=null?r:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function lm(t){return t.type!=="content"?t:{type:"content",value:t.value.map(e=>e.type!=="media"?e:e.mediaType.startsWith("image/")?{type:"image-data",data:e.data,mediaType:e.mediaType}:{type:"file-data",data:e.data,mediaType:e.mediaType})}}async function Da({toolCallId:t,input:e,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Tr(r)}:o==="json"?{type:"error-json",value:cm(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:t,input:e,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:cm(r)}}function cm(t){return t===void 0?null:t}function um({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,seed:i,stopSequences:s}){if(t!=null){if(!Number.isInteger(t))throw new ir({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new ir({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new ir({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new ir({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new ir({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new ir({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new ir({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new ir({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,stopSequences:s,seed:i}}function CS(t){return t!=null&&Object.keys(t).length>0}async function IS({tools:t,toolChoice:e,activeTools:r}){if(!CS(t))return{tools:void 0,toolChoice:void 0};let n=r!=null?Object.entries(t).filter(([a])=>r.includes(a)):Object.entries(t),o=[];for(let[a,i]of n){let s=i.type;switch(s){case void 0:case"dynamic":case"function":o.push({type:"function",name:a,description:i.description,inputSchema:await ur(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:a,id:i.id,args:i.args});break;default:{let l=s;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}}var po=Er.lazy(()=>Er.union([Er.null(),Er.string(),Er.number(),Er.boolean(),Er.record(Er.string(),po.optional()),Er.array(po)])),pe=Ma.record(Ma.string(),Ma.record(Ma.string(),po.optional())),Qm=W.object({type:W.literal("text"),text:W.string(),providerOptions:pe.optional()}),kS=W.object({type:W.literal("image"),image:W.union([Xm,W.instanceof(URL)]),mediaType:W.string().optional(),providerOptions:pe.optional()}),eg=W.object({type:W.literal("file"),data:W.union([Xm,W.instanceof(URL)]),filename:W.string().optional(),mediaType:W.string(),providerOptions:pe.optional()}),RS=W.object({type:W.literal("reasoning"),text:W.string(),providerOptions:pe.optional()}),OS=W.object({type:W.literal("tool-call"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerOptions:pe.optional(),providerExecuted:W.boolean().optional()}),NS=W.discriminatedUnion("type",[W.object({type:W.literal("text"),value:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("json"),value:po,providerOptions:pe.optional()}),W.object({type:W.literal("execution-denied"),reason:W.string().optional(),providerOptions:pe.optional()}),W.object({type:W.literal("error-text"),value:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("error-json"),value:po,providerOptions:pe.optional()}),W.object({type:W.literal("content"),value:W.array(W.union([W.object({type:W.literal("text"),text:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("media"),data:W.string(),mediaType:W.string()}),W.object({type:W.literal("file-data"),data:W.string(),mediaType:W.string(),filename:W.string().optional(),providerOptions:pe.optional()}),W.object({type:W.literal("file-url"),url:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("file-id"),fileId:W.union([W.string(),W.record(W.string(),W.string())]),providerOptions:pe.optional()}),W.object({type:W.literal("image-data"),data:W.string(),mediaType:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("image-url"),url:W.string(),providerOptions:pe.optional()}),W.object({type:W.literal("image-file-id"),fileId:W.union([W.string(),W.record(W.string(),W.string())]),providerOptions:pe.optional()}),W.object({type:W.literal("custom"),providerOptions:pe.optional()})]))})]),tg=W.object({type:W.literal("tool-result"),toolCallId:W.string(),toolName:W.string(),output:NS,providerOptions:pe.optional()}),MS=W.object({type:W.literal("tool-approval-request"),approvalId:W.string(),toolCallId:W.string()}),PS=W.object({type:W.literal("tool-approval-response"),approvalId:W.string(),approved:W.boolean(),reason:W.string().optional()}),DS=Ke.object({role:Ke.literal("system"),content:Ke.string(),providerOptions:pe.optional()}),jS=Ke.object({role:Ke.literal("user"),content:Ke.union([Ke.string(),Ke.array(Ke.union([Qm,kS,eg]))]),providerOptions:pe.optional()}),LS=Ke.object({role:Ke.literal("assistant"),content:Ke.union([Ke.string(),Ke.array(Ke.union([Qm,eg,RS,OS,tg,MS]))]),providerOptions:pe.optional()}),US=Ke.object({role:Ke.literal("tool"),content:Ke.array(Ke.union([tg,PS])),providerOptions:pe.optional()}),FS=Ke.union([DS,jS,LS,US]);async function HS(t){if(t.prompt==null&&t.messages==null)throw new Dr({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Dr({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string"&&!Ol(t.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Dr({prompt:t,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Dr({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Dr({prompt:t,message:"messages must not be empty"});let r=await nt({value:e,schema:AS.array(FS)});if(!r.success)throw new Dr({prompt:t,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:e,system:t.system}}function qS(t){if(!Ca.isInstance(t))return t;let e=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return e?new oe({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
3968
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Mf({message:i,statusCode:o,cause:a})}},Pf="GatewayInvalidRequestError",C0=`vercel.ai.gateway.error.${Pf}`,df=Symbol.for(C0),pf,hf,I0=class extends(hf=Tt,pf=df,hf){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[pf]=!0,this.name=Pf,this.type="invalid_request_error"}static isInstance(t){return Tt.hasMarker(t)&&df in t}},Df="GatewayRateLimitError",A0=`vercel.ai.gateway.error.${Df}`,ff=Symbol.for(A0),mf,gf,k0=class extends(gf=Tt,mf=ff,gf){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[mf]=!0,this.name=Df,this.type="rate_limit_exceeded"}static isInstance(t){return Tt.hasMarker(t)&&ff in t}},jf="GatewayModelNotFoundError",R0=`vercel.ai.gateway.error.${jf}`,vf=Symbol.for(R0),O0=q(()=>H(yf.object({modelId:yf.string()}))),bf,_f,N0=class extends(_f=Tt,bf=vf,_f){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[bf]=!0,this.name=jf,this.type="model_not_found",this.modelId=r}static isInstance(t){return Tt.hasMarker(t)&&vf in t}},Lf="GatewayInternalServerError",M0=`vercel.ai.gateway.error.${Lf}`,wf=Symbol.for(M0),Ef,Tf,xf=class extends(Tf=Tt,Ef=wf,Tf){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Ef]=!0,this.name=Lf,this.type="internal_server_error"}static isInstance(t){return Tt.hasMarker(t)&&wf in t}},Ff="GatewayResponseError",P0=`vercel.ai.gateway.error.${Ff}`,Sf=Symbol.for(P0),Cf,If,D0=class extends(If=Tt,Cf=Sf,If){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:o}={}){super({message:t,statusCode:e,cause:o}),this[Cf]=!0,this.name=Ff,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return Tt.hasMarker(t)&&Sf in t}};async function Af({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){let a=await nt({value:t,schema:j0});if(!a.success)return new D0({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:a.error,cause:n});let i=a.value,s=i.error.type,l=i.error.message;switch(s){case"authentication_error":return Ca.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new I0({message:l,statusCode:e,cause:n});case"rate_limit_exceeded":return new k0({message:l,statusCode:e,cause:n});case"model_not_found":{let c=await nt({value:i.error.param,schema:O0});return new N0({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new xf({message:l,statusCode:e,cause:n});default:return new xf({message:l,statusCode:e,cause:n})}}var j0=q(()=>H(Or.object({error:Or.object({message:Or.string(),type:Or.string().nullish(),param:Or.unknown().nullish(),code:Or.union([Or.string(),Or.number()]).nullish()})})));function Nr(t,e){var r;return Tt.isInstance(t)?t:$e.isInstance(t)?Af({response:L0(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):Af({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function L0(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var Uf="ai-gateway-auth-method";async function vn(t){let e=await nt({value:t[Uf],schema:F0});return e.success?e.value:void 0}var F0=q(()=>H(vl.union([vl.literal("api-key"),vl.literal("oidc")]))),kf=class{constructor(t){this.config=t}async getAvailableModels(){try{let{value:t}=await za({url:`${this.config.baseURL}/config`,headers:await Te(this.config.headers()),successfulResponseHandler:qe(U0),failedResponseHandler:Qe({errorSchema:We.any(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Nr(t)}}async getCredits(){try{let t=new URL(this.config.baseURL),{value:e}=await za({url:`${t.origin}/v1/credits`,headers:await Te(this.config.headers()),successfulResponseHandler:qe(H0),failedResponseHandler:Qe({errorSchema:We.any(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Nr(t)}}},U0=q(()=>H(We.object({models:We.array(We.object({id:We.string(),name:We.string(),description:We.string().nullish(),pricing:We.object({input:We.string(),output:We.string(),input_cache_read:We.string().nullish(),input_cache_write:We.string().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:We.object({specificationVersion:We.literal("v3"),provider:We.string(),modelId:We.string()}),modelType:We.enum(["language","embedding","image"]).nullish()}))}))),H0=q(()=>H(We.object({balance:We.string(),total_used:We.string()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),q0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){let{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){let{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,o=await Te(this.config.headers());try{let{responseHeaders:a,value:i,rawValue:s}=await Ue({url:this.getUrl(),headers:Ge(o,t.headers,this.getModelConfigHeaders(this.modelId,!1),await Te(this.config.o11yHeaders)),body:e,successfulResponseHandler:qe(Sa.any()),failedResponseHandler:Qe({errorSchema:Sa.any(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:e},response:{headers:a,body:s},warnings:r}}catch(a){throw await Nr(a,await vn(o))}}async doStream(t){let{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,o=await Te(this.config.headers());try{let{value:a,responseHeaders:i}=await Ue({url:this.getUrl(),headers:Ge(o,t.headers,this.getModelConfigHeaders(this.modelId,!0),await Te(this.config.o11yHeaders)),body:e,successfulResponseHandler:Sr(Sa.any()),failedResponseHandler:Qe({errorSchema:Sa.any(),errorToMessage:s=>s}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(s){r.length>0&&s.enqueue({type:"stream-start",warnings:r})},transform(s,l){if(s.success){let c=s.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(s.error)}})),request:{body:e},response:{headers:i}}}catch(a){throw await Nr(a,await vn(o))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(let e of t.prompt)for(let r of e.content)if(this.isFilePart(r)){let n=r;if(n.data instanceof Uint8Array){let o=Uint8Array.from(n.data),a=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},$0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var o;let a=await Te(this.config.headers());try{let{responseHeaders:i,value:s,rawValue:l}=await Ue({url:this.getUrl(),headers:Ge(a,e??{},this.getModelConfigHeaders(),await Te(this.config.o11yHeaders)),body:{values:t,...n?{providerOptions:n}:{}},successfulResponseHandler:qe(G0),failedResponseHandler:Qe({errorSchema:Nt.any(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(o=s.usage)!=null?o:void 0,providerMetadata:s.providerMetadata,response:{headers:i,body:l},warnings:[]}}catch(i){throw await Nr(i,await vn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},G0=q(()=>H(Nt.object({embeddings:Nt.array(Nt.array(Nt.number())),usage:Nt.object({tokens:Nt.number()}).nullish(),providerMetadata:Nt.record(Nt.string(),Nt.record(Nt.string(),Nt.unknown())).optional()}))),B0=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,files:a,mask:i,providerOptions:s,headers:l,abortSignal:c}){var p;let h=await Te(this.config.headers());try{let{responseHeaders:g,value:y,rawValue:S}=await Ue({url:this.getUrl(),headers:Ge(h,l??{},this.getModelConfigHeaders(),await Te(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s},...a&&{files:a.map(f=>Rf(f))},...i&&{mask:Rf(i)}},successfulResponseHandler:qe(z0),failedResponseHandler:Qe({errorSchema:ht.any(),errorToMessage:f=>f}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(p=y.warnings)!=null?p:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:g}}}catch(g){throw Nr(g,await vn(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function Rf(t){return t.type==="file"&&t.data instanceof Uint8Array?{...t,data:Jt(t.data)}:t}var V0=ht.object({images:ht.array(ht.unknown()).optional()}).catchall(ht.unknown()),z0=ht.object({images:ht.array(ht.string()),warnings:ht.array(ht.object({type:ht.literal("other"),message:ht.string()})).optional(),providerMetadata:ht.record(ht.string(),V0).optional()}),W0=q(()=>H(Re.object({query:Re.union([Re.string(),Re.array(Re.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Re.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Re.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Re.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Re.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Re.array(Re.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Re.array(Re.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Re.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Re.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Re.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Re.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Re.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),J0=q(()=>H(Re.union([Re.object({results:Re.array(Re.object({title:Re.string(),url:Re.string(),snippet:Re.string(),date:Re.string().optional(),lastUpdated:Re.string().optional()})),id:Re.string()}),Re.object({error:Re.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Re.number().optional(),message:Re.string()})]))),K0=Ze({id:"gateway.perplexity_search",inputSchema:W0,outputSchema:J0}),Y0=(t={})=>K0(t),X0={perplexitySearch:Y0};async function Z0(){var t;return(t=(0,Hf.getContext)().headers)==null?void 0:t["x-vercel-id"]}var Q0="3.0.14",ex="0.0.1";function tx(t={}){var e,r;let n=null,o=null,a=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5,i=0,s=(r=dr(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{let f=await rx(t);return lt({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":ex,[Uf]:f.authMethod,...t.headers},`ai-sdk/gateway/${Q0}`)}catch(f){throw Ca.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:f})}},c=()=>{let f=Lt({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),b=Lt({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=Lt({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let M=await Z0();return{...f&&{"ai-o11y-deployment-id":f},...b&&{"ai-o11y-environment":b},..._&&{"ai-o11y-region":_},...M&&{"ai-o11y-request-id":M}}}},p=f=>new q0(f,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()}),h=async()=>{var f,b,_;let M=(_=(b=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:b.call(f).getTime())!=null?_:Date.now();return(!n||M-i>a)&&(i=M,n=new kf({baseURL:s,headers:l,fetch:t.fetch}).getAvailableModels().then(B=>(o=B,B)).catch(async B=>{throw await Nr(B,await vn(await l()))})),o?Promise.resolve(o):n},g=async()=>new kf({baseURL:s,headers:l,fetch:t.fetch}).getCredits().catch(async f=>{throw await Nr(f,await vn(await l()))}),y=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(f)};y.specificationVersion="v3",y.getAvailableModels=h,y.getCredits=g,y.imageModel=f=>new B0(f,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()}),y.languageModel=p;let S=f=>new $0(f,{provider:"gateway",baseURL:s,headers:l,fetch:t.fetch,o11yHeaders:c()});return y.embeddingModel=S,y.textEmbeddingModel=S,y.tools=X0,y}var $f=tx();async function rx(t){let e=Lt({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return e?{token:e,authMethod:"api-key"}:{token:await(0,qf.getVercelOidcToken)(),authMethod:"oidc"}}import{z as uo}from"zod/v4";import{z as AS}from"zod/v4";import{z as Ke}from"zod/v4";import{z as Ma}from"zod/v4";import{z as Er}from"zod/v4";import{z as J}from"zod/v4";var Gf=typeof globalThis=="object"?globalThis:global;var _r="1.9.0";var Bf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function nx(t){var e=new Set([t]),r=new Set,n=t.match(Bf);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===t};function a(s){return r.add(s),!1}function i(s){return e.add(s),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(Bf);if(!c)return a(l);var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||o.major!==p.major?a(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?i(l):a(l):o.minor<=p.minor?i(l):a(l)}}var Vf=nx(_r);var ox=_r.split(".")[0],io=Symbol.for("opentelemetry.js.api."+ox),so=Gf;function bn(t,e,r,n){var o;n===void 0&&(n=!1);var a=so[io]=(o=so[io])!==null&&o!==void 0?o:{version:_r};if(!n&&a[t]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(i.stack||i.message),!1}if(a.version!==_r){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+_r);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+_r+"."),!0}function wr(t){var e,r,n=(e=so[io])===null||e===void 0?void 0:e.version;if(!(!n||!Vf(n)))return(r=so[io])===null||r===void 0?void 0:r[t]}function _n(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+_r+".");var r=so[io];r&&delete r[t]}var ax=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},ix=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},zf=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return lo("verbose",this._namespace,e)},t}();function lo(t,e,r){var n=wr("diag");if(n)return r.unshift(e),n[t].apply(n,ix([],ax(r),!1))}var ut;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ut||(ut={}));function Wf(t,e){t<ut.NONE?t=ut.NONE:t>ut.ALL&&(t=ut.ALL),e=e||{};function r(n,o){var a=e[n];return typeof a=="function"&&t>=o?a.bind(e):function(){}}return{error:r("error",ut.ERROR),warn:r("warn",ut.WARN),info:r("info",ut.INFO),debug:r("debug",ut.DEBUG),verbose:r("verbose",ut.VERBOSE)}}var sx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},lx=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},cx="diag",wn=function(){function t(){function e(o){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var s=wr("diag");if(s)return s[o].apply(s,lx([],sx(a),!1))}}var r=this,n=function(o,a){var i,s,l;if(a===void 0&&(a={logLevel:ut.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof a=="number"&&(a={logLevel:a});var p=wr("diag"),h=Wf((s=a.logLevel)!==null&&s!==void 0?s:ut.INFO,o);if(p&&!a.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+g),h.warn("Current logger will overwrite one already registered from "+g)}return bn("diag",h,r,!0)};r.setLogger=n,r.disable=function(){_n(cx,r)},r.createComponentLogger=function(o){return new zf(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}();function Jf(t){return Symbol.for(t)}var ux=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var a=new t(r._currentContext);return a._currentContext.set(n,o),a},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),Kf=new ux;var dx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},px=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Yf=function(){function t(){}return t.prototype.active=function(){return Kf},t.prototype.with=function(e,r,n){for(var o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return r.call.apply(r,px([n],dx(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}();var hx=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,a=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},fx=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,a;n<o;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},bl="context",mx=new Yf,Ia=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return bn(bl,e,wn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,fx([e,r,n],hx(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return wr(bl)||mx},t.prototype.disable=function(){this._getContextManager().disable(),_n(bl,wn.instance())},t}();var Aa;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Aa||(Aa={}));var _l="0000000000000000",wl="00000000000000000000000000000000",Xf={traceId:wl,spanId:_l,traceFlags:Aa.NONE};var Mr=function(){function t(e){e===void 0&&(e=Xf),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}();var El=Jf("OpenTelemetry Context Key SPAN");function ka(t){return t.getValue(El)||void 0}function Zf(){return ka(Ia.getInstance().active())}function co(t,e){return t.setValue(El,e)}function Qf(t){return t.deleteValue(El)}function em(t,e){return co(t,new Mr(e))}function Ra(t){var e;return(e=ka(t))===null||e===void 0?void 0:e.spanContext()}var gx=/^([0-9a-f]{32})$/i,yx=/^[0-9a-f]{16}$/i;function vx(t){return gx.test(t)&&t!==wl}function bx(t){return yx.test(t)&&t!==_l}function Oa(t){return vx(t.traceId)&&bx(t.spanId)}function tm(t){return new Mr(t)}var Tl=Ia.getInstance(),Na=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Tl.active());var o=!!r?.root;if(o)return new Mr;var a=n&&Ra(n);return _x(a)&&Oa(a)?new Mr(a):new Mr},t.prototype.startActiveSpan=function(e,r,n,o){var a,i,s;if(!(arguments.length<2)){arguments.length===2?s=r:arguments.length===3?(a=r,s=n):(a=r,i=n,s=o);var l=i??Tl.active(),c=this.startSpan(e,a,l),p=co(l,c);return Tl.with(p,s,void 0,c)}},t}();function _x(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var wx=new Na,rm=function(){function t(e,r,n,o){this._provider=e,this.name=r,this.version=n,this.options=o}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,o){var a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):wx},t}();var nm=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new Na},t}();var Ex=new nm,xl=function(){function t(){}return t.prototype.getTracer=function(e,r,n){var o;return(o=this.getDelegateTracer(e,r,n))!==null&&o!==void 0?o:new rm(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Ex},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,r,n)},t}();var En;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(En||(En={}));var Sl="trace",om=function(){function t(){this._proxyTracerProvider=new xl,this.wrapSpanContext=tm,this.isSpanContextValid=Oa,this.deleteSpan=Qf,this.getSpan=ka,this.getActiveSpan=Zf,this.getSpanContext=Ra,this.setSpan=co,this.setSpanContext=em}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=bn(Sl,this._proxyTracerProvider,wn.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return wr(Sl)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){_n(Sl,wn.instance()),this._proxyTracerProvider=new xl},t}();var Cl=om.getInstance();import{z as L}from"zod/v4";import{z as w}from"zod/v4";var xx=Object.defineProperty,Sx=(t,e)=>{for(var r in e)xx(t,r,{get:e[r],enumerable:!0})},mm="AI_InvalidArgumentError",gm=`vercel.ai.error.${mm}`,Cx=Symbol.for(gm),ym,ir=class extends oe{constructor({parameter:t,value:e,message:r}){super({name:mm,message:`Invalid argument for parameter ${t}: ${r}`}),this[ym]=!0,this.parameter=t,this.value=e}static isInstance(t){return oe.hasMarker(t,gm)}};ym=Cx;var Ix="AI_InvalidStreamPartError",Ax=`vercel.ai.error.${Ix}`,kx=Symbol.for(Ax),Rx;Rx=kx;var vm="AI_InvalidToolApprovalError",bm=`vercel.ai.error.${vm}`,Ox=Symbol.for(bm),_m,Nx=class extends oe{constructor({approvalId:t}){super({name:vm,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[_m]=!0,this.approvalId=t}static isInstance(t){return oe.hasMarker(t,bm)}};_m=Ox;var wm="AI_InvalidToolInputError",Em=`vercel.ai.error.${wm}`,Mx=Symbol.for(Em),Tm,Rl=class extends oe{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Tr(r)}`}){super({name:wm,message:n,cause:r}),this[Tm]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return oe.hasMarker(t,Em)}};Tm=Mx;var xm="AI_ToolCallNotFoundForApprovalError",Sm=`vercel.ai.error.${xm}`,Px=Symbol.for(Sm),Cm,Im=class extends oe{constructor({toolCallId:t,approvalId:e}){super({name:xm,message:`Tool call "${t}" not found for approval request "${e}".`}),this[Cm]=!0,this.toolCallId=t,this.approvalId=e}static isInstance(t){return oe.hasMarker(t,Sm)}};Cm=Px;var Dx="AI_NoImageGeneratedError",jx=`vercel.ai.error.${Dx}`,Lx=Symbol.for(jx),Fx;Fx=Lx;var Am="AI_NoObjectGeneratedError",km=`vercel.ai.error.${Am}`,Ux=Symbol.for(km),Rm,Pr=class extends oe{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:o,finishReason:a}){super({name:Am,message:t,cause:e}),this[Rm]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=a}static isInstance(t){return oe.hasMarker(t,km)}};Rm=Ux;var Om="AI_NoOutputGeneratedError",Nm=`vercel.ai.error.${Om}`,Hx=Symbol.for(Nm),Mm,qx=class extends oe{constructor({message:t="No output generated.",cause:e}={}){super({name:Om,message:t,cause:e}),this[Mm]=!0}static isInstance(t){return oe.hasMarker(t,Nm)}};Mm=Hx;var Pm="AI_NoSuchToolError",Dm=`vercel.ai.error.${Pm}`,$x=Symbol.for(Dm),jm,Il=class extends oe{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:Pm,message:r}),this[jm]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return oe.hasMarker(t,Dm)}};jm=$x;var Lm="AI_ToolCallRepairError",Fm=`vercel.ai.error.${Lm}`,Gx=Symbol.for(Fm),Um,Bx=class extends oe{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Tr(t)}`}){super({name:Lm,message:r,cause:t}),this[Um]=!0,this.originalError=e}static isInstance(t){return oe.hasMarker(t,Fm)}};Um=Gx;var Vx=class extends oe{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},zx="AI_UIMessageStreamError",Wx=`vercel.ai.error.${zx}`,Jx=Symbol.for(Wx),Kx;Kx=Jx;var Yx="AI_InvalidDataContentError",Xx=`vercel.ai.error.${Yx}`,Zx=Symbol.for(Xx),Qx;Qx=Zx;var Hm="AI_InvalidMessageRoleError",qm=`vercel.ai.error.${Hm}`,eS=Symbol.for(qm),$m,tS=class extends oe{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Hm,message:e}),this[$m]=!0,this.role=t}static isInstance(t){return oe.hasMarker(t,qm)}};$m=eS;var rS="AI_MessageConversionError",nS=`vercel.ai.error.${rS}`,oS=Symbol.for(nS),aS;aS=oS;var Gm="AI_RetryError",Bm=`vercel.ai.error.${Gm}`,iS=Symbol.for(Bm),Vm,am=class extends oe{constructor({message:t,reason:e,errors:r}){super({name:Gm,message:t}),this[Vm]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return oe.hasMarker(t,Bm)}};Vm=iS;function sS({warning:t,provider:e,model:r}){let n=`AI SDK Warning (${e} / ${r}):`;switch(t.type){case"unsupported":{let o=`${n} The feature "${t.feature}" is not supported.`;return t.details&&(o+=` ${t.details}`),o}case"compatibility":{let o=`${n} The feature "${t.feature}" is used in a compatibility mode.`;return t.details&&(o+=` ${t.details}`),o}case"other":return`${n} ${t.message}`;default:return`${n} ${JSON.stringify(t,null,2)}`}}var lS="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",im=!1,zm=t=>{if(t.warnings.length===0)return;let e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}im||(im=!0,console.info(lS));for(let r of t.warnings)console.warn(sS({warning:r,provider:t.provider,model:t.model}))}};function cS({provider:t,modelId:e}){zm({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:t,model:e})}function uS(t){return t.specificationVersion==="v3"?t:(cS({provider:t.provider,modelId:t.modelId}),new Proxy(t,{get(e,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{let o=await e.doGenerate(...n);return{...o,finishReason:Wm(o.finishReason),usage:Jm(o.usage)}};case"doStream":return async(...n)=>{let o=await e.doStream(...n);return{...o,stream:dS(o.stream)}};default:return e[r]}}}))}function dS(t){return t.pipeThrough(new TransformStream({transform(e,r){switch(e.type){case"finish":r.enqueue({...e,finishReason:Wm(e.finishReason),usage:Jm(e.usage)});break;default:r.enqueue(e);break}}}))}function Wm(t){return{unified:t==="unknown"?"other":t,raw:void 0}}function Jm(t){return{inputTokens:{total:t.inputTokens,noCache:void 0,cacheRead:t.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:t.outputTokens,text:void 0,reasoning:t.reasoningTokens}}}function sm(t){if(typeof t!="string"){if(t.specificationVersion!=="v3"&&t.specificationVersion!=="v2"){let e=t;throw new Vx({version:e.specificationVersion,provider:e.provider,modelId:e.modelId})}return uS(t)}return pS().languageModel(t)}function pS(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:$f}function Km(t){if(t!=null)return typeof t=="number"?t:t.totalMs}function hS(t){if(!(t==null||typeof t=="number"))return t.stepMs}var fS=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var mS=t=>{let e=typeof t=="string"?Jr(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function gS(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?mS(t):t}function yS({data:t,signatures:e}){let r=gS(t),n=typeof r=="string"?Jr(r.substring(0,Math.min(r.length,24))):r;for(let o of e)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((a,i)=>a===null||n[i]===a))return o.mediaType}var Ym="6.0.35",vS=async({url:t})=>{var e;let r=t.toString();try{let n=await fetch(r,{headers:lt({},`ai-sdk/${Ym}`,_o())});if(!n.ok)throw new vo({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw vo.isInstance(n)?n:new vo({url:r,cause:n})}},bS=(t=vS)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function _S(t){try{let[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Xm=uo.union([uo.string(),uo.instanceof(Uint8Array),uo.instanceof(ArrayBuffer),uo.custom(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Zm(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){let{mediaType:e,base64Content:r}=_S(t.toString());if(e==null||r==null)throw new oe({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function wS(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Jt(new Uint8Array(t)):Jt(t)}function Ol(t){return t===void 0?[]:Array.isArray(t)?t:[t]}async function ES({prompt:t,supportedUrls:e,download:r=bS()}){let n=await xS(t.messages,r,e),o=[...t.system!=null?typeof t.system=="string"?[{role:"system",content:t.system}]:Ol(t.system).map(i=>({role:"system",content:i.content,providerOptions:i.providerOptions})):[],...t.messages.map(i=>TS({message:i,downloadedAssets:n}))],a=[];for(let i of o){if(i.role!=="tool"){a.push(i);continue}let s=a.at(-1);s?.role==="tool"?s.content.push(...i.content):a.push(i)}return a}function TS({message:t,downloadedAssets:e}){let r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>SS(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{let o=n.providerOptions;switch(n.type){case"file":{let{data:a,mediaType:i}=Zm(n.data);return{type:"file",data:a,filename:n.filename,mediaType:i??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:lm(n.output),providerOptions:o}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:lm(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:t.providerOptions};default:{let n=r;throw new tS({role:n})}}}async function xS(t,e,r){let n=t.filter(a=>a.role==="user").map(a=>a.content).filter(a=>Array.isArray(a)).flat().filter(a=>a.type==="image"||a.type==="file").map(a=>{var i;let s=(i=a.mediaType)!=null?i:a.type==="image"?"image/*":void 0,l=a.type==="image"?a.image:a.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:s,data:l}}).filter(a=>a.data instanceof URL).map(a=>({url:a.data,isUrlSupportedByModel:a.mediaType!=null&&ou({url:a.data.toString(),mediaType:a.mediaType,supportedUrls:r})})),o=await e(n);return Object.fromEntries(o.map((a,i)=>a==null?null:[n[i].url.toString(),{data:a.data,mediaType:a.mediaType}]).filter(a=>a!=null))}function SS(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n,o=t.type;switch(o){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${o}`)}let{data:a,mediaType:i}=Zm(n),s=i??t.mediaType,l=a;if(l instanceof URL){let c=e[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(r=yS({data:l,signatures:fS}))!=null?r:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function lm(t){return t.type!=="content"?t:{type:"content",value:t.value.map(e=>e.type!=="media"?e:e.mediaType.startsWith("image/")?{type:"image-data",data:e.data,mediaType:e.mediaType}:{type:"file-data",data:e.data,mediaType:e.mediaType})}}async function Da({toolCallId:t,input:e,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Tr(r)}:o==="json"?{type:"error-json",value:cm(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:t,input:e,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:cm(r)}}function cm(t){return t===void 0?null:t}function um({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,seed:i,stopSequences:s}){if(t!=null){if(!Number.isInteger(t))throw new ir({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new ir({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new ir({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new ir({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new ir({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new ir({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new ir({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new ir({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,stopSequences:s,seed:i}}function CS(t){return t!=null&&Object.keys(t).length>0}async function IS({tools:t,toolChoice:e,activeTools:r}){if(!CS(t))return{tools:void 0,toolChoice:void 0};let n=r!=null?Object.entries(t).filter(([a])=>r.includes(a)):Object.entries(t),o=[];for(let[a,i]of n){let s=i.type;switch(s){case void 0:case"dynamic":case"function":o.push({type:"function",name:a,description:i.description,inputSchema:await ur(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:a,id:i.id,args:i.args});break;default:{let l=s;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}}var po=Er.lazy(()=>Er.union([Er.null(),Er.string(),Er.number(),Er.boolean(),Er.record(Er.string(),po.optional()),Er.array(po)])),he=Ma.record(Ma.string(),Ma.record(Ma.string(),po.optional())),Qm=J.object({type:J.literal("text"),text:J.string(),providerOptions:he.optional()}),kS=J.object({type:J.literal("image"),image:J.union([Xm,J.instanceof(URL)]),mediaType:J.string().optional(),providerOptions:he.optional()}),eg=J.object({type:J.literal("file"),data:J.union([Xm,J.instanceof(URL)]),filename:J.string().optional(),mediaType:J.string(),providerOptions:he.optional()}),RS=J.object({type:J.literal("reasoning"),text:J.string(),providerOptions:he.optional()}),OS=J.object({type:J.literal("tool-call"),toolCallId:J.string(),toolName:J.string(),input:J.unknown(),providerOptions:he.optional(),providerExecuted:J.boolean().optional()}),NS=J.discriminatedUnion("type",[J.object({type:J.literal("text"),value:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("json"),value:po,providerOptions:he.optional()}),J.object({type:J.literal("execution-denied"),reason:J.string().optional(),providerOptions:he.optional()}),J.object({type:J.literal("error-text"),value:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("error-json"),value:po,providerOptions:he.optional()}),J.object({type:J.literal("content"),value:J.array(J.union([J.object({type:J.literal("text"),text:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("media"),data:J.string(),mediaType:J.string()}),J.object({type:J.literal("file-data"),data:J.string(),mediaType:J.string(),filename:J.string().optional(),providerOptions:he.optional()}),J.object({type:J.literal("file-url"),url:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("file-id"),fileId:J.union([J.string(),J.record(J.string(),J.string())]),providerOptions:he.optional()}),J.object({type:J.literal("image-data"),data:J.string(),mediaType:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("image-url"),url:J.string(),providerOptions:he.optional()}),J.object({type:J.literal("image-file-id"),fileId:J.union([J.string(),J.record(J.string(),J.string())]),providerOptions:he.optional()}),J.object({type:J.literal("custom"),providerOptions:he.optional()})]))})]),tg=J.object({type:J.literal("tool-result"),toolCallId:J.string(),toolName:J.string(),output:NS,providerOptions:he.optional()}),MS=J.object({type:J.literal("tool-approval-request"),approvalId:J.string(),toolCallId:J.string()}),PS=J.object({type:J.literal("tool-approval-response"),approvalId:J.string(),approved:J.boolean(),reason:J.string().optional()}),DS=Ke.object({role:Ke.literal("system"),content:Ke.string(),providerOptions:he.optional()}),jS=Ke.object({role:Ke.literal("user"),content:Ke.union([Ke.string(),Ke.array(Ke.union([Qm,kS,eg]))]),providerOptions:he.optional()}),LS=Ke.object({role:Ke.literal("assistant"),content:Ke.union([Ke.string(),Ke.array(Ke.union([Qm,eg,RS,OS,tg,MS]))]),providerOptions:he.optional()}),FS=Ke.object({role:Ke.literal("tool"),content:Ke.array(Ke.union([tg,PS])),providerOptions:he.optional()}),US=Ke.union([DS,jS,LS,FS]);async function HS(t){if(t.prompt==null&&t.messages==null)throw new Dr({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Dr({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string"&&!Ol(t.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Dr({prompt:t,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Dr({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Dr({prompt:t,message:"messages must not be empty"});let r=await nt({value:e,schema:AS.array(US)});if(!r.success)throw new Dr({prompt:t,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:e,system:t.system}}function qS(t){if(!Ca.isInstance(t))return t;let e=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return e?new oe({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
3966
3969
|
|
|
3967
3970
|
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
3968
3971
|
|
|
@@ -3970,11 +3973,11 @@ Alternatively, you can use a provider module instead of the AI Gateway.
|
|
|
3970
3973
|
|
|
3971
3974
|
Learn more: \x1B[34m${r}\x1B[0m
|
|
3972
3975
|
|
|
3973
|
-
`),{name:"GatewayAuthenticationError"})}function Al({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function GS({model:t,settings:e,telemetry:r,headers:n}){var o;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((a,[i,s])=>{if(i==="timeout"){let l=Km(s);l!=null&&(a[`ai.settings.${i}`]=l)}else a[`ai.settings.${i}`]=s;return a},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((a,[i,s])=>(a[`ai.telemetry.metadata.${i}`]=s,a),{}),...Object.entries(n??{}).reduce((a,[i,s])=>(s!==void 0&&(a[`ai.request.headers.${i}`]=s),a),{})}}var $S={startSpan(){return Pa},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Pa);if(typeof r=="function")return r(Pa);if(typeof n=="function")return n(Pa)}},Pa={spanContext(){return BS},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},BS={traceId:"",spanId:"",traceFlags:0};function VS({isEnabled:t=!1,tracer:e}={}){return t?e||Cl.getTracer("ai"):$S}async function kl({name:t,tracer:e,attributes:r,fn:n,endWhenDone:o=!0}){return e.startActiveSpan(t,{attributes:await r},async a=>{try{let i=await n(a);return o&&a.end(),i}catch(i){try{rg(a,i)}finally{a.end()}throw i}})}function rg(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:En.ERROR,message:e.message})):t.setStatus({code:En.ERROR})}async function Tn({telemetry:t,attributes:e}){if(t?.isEnabled!==!0)return{};let r={};for(let[n,o]of Object.entries(e))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(t?.recordInputs===!1)continue;let a=await o.input();a!=null&&(r[n]=a);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(t?.recordOutputs===!1)continue;let a=await o.output();a!=null&&(r[n]=a);continue}r[n]=o}return r}function zS(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?wS(r.data):r.data}:r)})))}function WS(t){return{inputTokens:t.inputTokens.total,inputTokenDetails:{noCacheTokens:t.inputTokens.noCache,cacheReadTokens:t.inputTokens.cacheRead,cacheWriteTokens:t.inputTokens.cacheWrite},outputTokens:t.outputTokens.total,outputTokenDetails:{textTokens:t.outputTokens.text,reasoningTokens:t.outputTokens.reasoning},totalTokens:Wt(t.inputTokens.total,t.outputTokens.total),raw:t.raw,reasoningTokens:t.outputTokens.reasoning,cachedInputTokens:t.inputTokens.cacheRead}}function JS(t,e){var r,n,o,a,i,s,l,c,p,h;return{inputTokens:Wt(t.inputTokens,e.inputTokens),inputTokenDetails:{noCacheTokens:Wt((r=t.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=e.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Wt((o=t.inputTokenDetails)==null?void 0:o.cacheReadTokens,(a=e.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:Wt((i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(s=e.inputTokenDetails)==null?void 0:s.cacheWriteTokens)},outputTokens:Wt(t.outputTokens,e.outputTokens),outputTokenDetails:{textTokens:Wt((l=t.outputTokenDetails)==null?void 0:l.textTokens,(c=e.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Wt((p=t.outputTokenDetails)==null?void 0:p.reasoningTokens,(h=e.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Wt(t.totalTokens,e.totalTokens),reasoningTokens:Wt(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:Wt(t.cachedInputTokens,e.cachedInputTokens)}}function Wt(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function ng(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;let r={...t};for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];if(o===void 0)continue;let a=n in t?t[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),s=a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);i&&s?r[n]=ng(a,o):r[n]=o}return r}function KS({error:t,exponentialBackoffDelay:e}){let r=t.responseHeaders;if(!r)return e;let n,o=r["retry-after-ms"];if(o){let i=parseFloat(o);Number.isNaN(i)||(n=i)}let a=r["retry-after"];if(a&&n===void 0){let i=parseFloat(a);Number.isNaN(i)?n=Date.parse(a)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var YS=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>og(o,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function og(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:o},a=[]){try{return await t()}catch(i){if(xr(i)||e===0)throw i;let s=bo(i),l=[...a,i],c=l.length;if(c>e)throw new am({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&Ge.isInstance(i)&&i.isRetryable===!0&&c<=e)return await Zc(KS({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),og(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new am({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function XS({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new ir({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new ir({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}let r=t??2;return{maxRetries:r,retry:YS({maxRetries:r,abortSignal:e})}}function ZS({messages:t}){let e=t.at(-1);if(e?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let r={};for(let l of t)if(l.role==="assistant"&&typeof l.content!="string"){let c=l.content;for(let p of c)p.type==="tool-call"&&(r[p.toolCallId]=p)}let n={};for(let l of t)if(l.role==="assistant"&&typeof l.content!="string"){let c=l.content;for(let p of c)p.type==="tool-approval-request"&&(n[p.approvalId]=p)}let o={};for(let l of e.content)l.type==="tool-result"&&(o[l.toolCallId]=l);let a=[],i=[],s=e.content.filter(l=>l.type==="tool-approval-response");for(let l of s){let c=n[l.approvalId];if(c==null)throw new Nx({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;let p=r[c.toolCallId];if(p==null)throw new Im({toolCallId:c.toolCallId,approvalId:c.approvalId});let h={approvalRequest:c,approvalResponse:l,toolCall:p};l.approved?a.push(h):i.push(h)}return{approvedToolApprovals:a,deniedToolApprovals:i}}async function QS({toolCall:t,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,onPreliminaryToolResult:s}){let{toolName:l,toolCallId:c,input:p}=t,h=e?.[l];if(h?.execute!=null)return kl({name:"ai.toolCall",attributes:Tn({telemetry:n,attributes:{...Al({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(p)}}}),tracer:r,fn:async m=>{let g;try{let T=uu({execute:h.execute.bind(h),input:p,options:{toolCallId:c,messages:o,abortSignal:a,experimental_context:i}});for await(let y of T)y.type==="preliminary"?s?.({...t,type:"tool-result",output:y.output,preliminary:!0}):g=y.output}catch(T){return rg(m,T),{type:"tool-error",toolCallId:c,toolName:l,input:p,error:T,dynamic:h.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{}}}try{m.setAttributes(await Tn({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(g)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:p,output:g,dynamic:h.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{}}}})}function dm(t){let e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var eC=class{constructor({data:t,mediaType:e}){let r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Jt(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Jr(this.base64Data)),this.uint8ArrayData}};async function tC({tool:t,toolCall:e,messages:r,experimental_context:n}){return t.needsApproval==null?!1:typeof t.needsApproval=="boolean"?t.needsApproval:await t.needsApproval(e.input,{toolCallId:e.toolCallId,messages:r,experimental_context:n})}var rC={};Sx(rC,{array:()=>aC,choice:()=>iC,json:()=>sC,object:()=>oC,text:()=>ag});function nC(t){let e=["ROOT"],r=-1,n=null;function o(l,c,p){switch(l){case'"':{r=c,e.pop(),e.push(p),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(p),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(p),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(p),e.push("INSIDE_ARRAY_START");break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function i(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){let c=t[l];switch(e[e.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{a(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{let h=t.substring(n,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?a(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let s=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{s+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{let p=t.substring(n,t.length);"true".startsWith(p)?s+="true".slice(p.length):"false".startsWith(p)?s+="false".slice(p.length):"null".startsWith(p)&&(s+="null".slice(p.length))}}return s}async function ja(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await pt({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await pt({text:nC(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ag=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:t}){return t},async parsePartialOutput({text:t}){return{partial:t}},createElementStreamTransform(){}}),oC=({schema:t,name:e,description:r})=>{let n=ur(t);return{name:"object",responseFormat:Te(n.jsonSchema).then(o=>({type:"json",schema:o,...e!=null&&{name:e},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},a){let i=await pt({text:o});if(!i.success)throw new Pr({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});let s=await nt({value:i.value,schema:n});if(!s.success)throw new Pr({message:"No object generated: response did not match schema.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value},async parsePartialOutput({text:o}){let a=await ja(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){}}},aC=({element:t,name:e,description:r})=>{let n=ur(t);return{name:"array",responseFormat:Te(n.jsonSchema).then(o=>{let{$schema:a,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...e!=null&&{name:e},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},a){let i=await pt({text:o});if(!i.success)throw new Pr({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});let s=i.value;if(s==null||typeof s!="object"||!("elements"in s)||!Array.isArray(s.elements))throw new Pr({message:"No object generated: response did not match schema.",cause:new Pt({value:s,cause:"response must be an object with an elements array"}),text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});for(let l of s.elements){let c=await nt({value:l,schema:n});if(!c.success)throw new Pr({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason})}return s.elements},async parsePartialOutput({text:o}){let a=await ja(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;let s=a.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(let c of s){let p=await nt({value:c,schema:n});p.success&&l.push(p.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:a},i){if(a!=null)for(;o<a.length;o++)i.enqueue(a[o])}})}}},iC=({options:t,name:e,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...e!=null&&{name:e},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){let a=await pt({text:n});if(!a.success)throw new Pr({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});let i=a.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!t.includes(i.result))throw new Pr({message:"No object generated: response did not match schema.",cause:new Pt({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){let o=await ja(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let a=o.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string")return;let i=t.filter(s=>s.startsWith(a.result));return o.state==="successful-parse"?i.includes(a.result)?{partial:a.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),sC=({name:t,description:e}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...t!=null&&{name:t},...e!=null&&{description:e}}),async parseCompleteOutput({text:r},n){let o=await pt({text:r});if(!o.success)throw new Pr({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){let n=await ja(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function lC({toolCall:t,tools:e,repairToolCall:r,system:n,messages:o}){var a;try{if(e==null){if(t.providerExecuted&&t.dynamic)return await ig(t);throw new Il({toolName:t.toolName})}try{return await pm({toolCall:t,tools:e})}catch(i){if(r==null||!(Il.isInstance(i)||Rl.isInstance(i)))throw i;let s=null;try{s=await r({toolCall:t,tools:e,inputSchema:async({toolName:l})=>{let{inputSchema:c}=e[l];return await ur(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new Bx({cause:l,originalError:i})}if(s==null)throw i;return await pm({toolCall:s,tools:e})}}catch(i){let s=await pt({text:t.input}),l=s.success?s.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:l,dynamic:!0,invalid:!0,error:i,title:(a=e?.[t.toolName])==null?void 0:a.title,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}}async function ig(t){let e=t.input.trim()===""?{success:!0,value:{}}:await pt({text:t.input});if(e.success===!1)throw new Rl({toolName:t.toolName,toolInput:t.input,cause:e.error});return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:e.value,providerExecuted:!0,dynamic:!0,providerMetadata:t.providerMetadata}}async function pm({toolCall:t,tools:e}){let r=t.toolName,n=e[r];if(n==null){if(t.providerExecuted&&t.dynamic)return await ig(t);throw new Il({toolName:t.toolName,availableTools:Object.keys(e)})}let o=ur(n.inputSchema),a=t.input.trim()===""?await nt({value:{},schema:o}):await pt({text:t.input,schema:o});if(a.success===!1)throw new Rl({toolName:r,toolInput:t.input,cause:a.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:a.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:a.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:n.title}}var cC=class{constructor({content:t,finishReason:e,rawFinishReason:r,usage:n,warnings:o,request:a,response:i,providerMetadata:s}){this.content=t,this.finishReason=e,this.rawFinishReason=r,this.usage=n,this.warnings=o,this.request=a,this.response=i,this.providerMetadata=s}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function uC(t){return({steps:e})=>e.length===t}async function dC({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}async function pC({content:t,tools:e}){let r=[],n=[];for(let a of t)if(a.type!=="source"&&!((a.type==="tool-result"||a.type==="tool-error")&&!a.providerExecuted)&&!(a.type==="text"&&a.text.length===0))switch(a.type){case"text":n.push({type:"text",text:a.text,providerOptions:a.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:a.text,providerOptions:a.providerMetadata});break;case"file":n.push({type:"file",data:a.file.base64,mediaType:a.file.mediaType,providerOptions:a.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":{let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-error":{let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:a.approvalId,toolCallId:a.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});let o=[];for(let a of t){if(!(a.type==="tool-result"||a.type==="tool-error")||a.providerExecuted)continue;let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.type==="tool-result"?a.output:a.error,errorMode:a.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,...a.providerMetadata!=null?{providerOptions:a.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function hC(...t){let e=t.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let r=new AbortController;for(let n of e){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var fC=cr({prefix:"aitxt",size:24});async function zM({model:t,tools:e,toolChoice:r,system:n,prompt:o,messages:a,maxRetries:i,abortSignal:s,timeout:l,headers:c,stopWhen:p=uC(1),experimental_output:h,output:m=h,experimental_telemetry:g,providerOptions:T,experimental_activeTools:y,activeTools:b=y,experimental_prepareStep:_,prepareStep:D=_,experimental_repairToolCall:V,experimental_download:X,experimental_context:P,_internal:{generateId:N=fC}={},onStepFinish:R,onFinish:Q,...E}){let re=sm(t),Z=Ol(p),Y=Km(l),ce=hS(l),B=ce!=null?new AbortController:void 0,J=hC(s,Y!=null?AbortSignal.timeout(Y):void 0,B?.signal),{maxRetries:fe,retry:j}=XS({maxRetries:i,abortSignal:J}),ye=um(E),Se=lt(c??{},`ai/${Ym}`),he=GS({model:re,telemetry:g,headers:Se,settings:{...ye,maxRetries:fe}}),Ue=await HS({system:n,prompt:o,messages:a}),z=VS(g);try{return await kl({name:"ai.generateText",attributes:Tn({telemetry:g,attributes:{...Al({operationId:"ai.generateText",telemetry:g}),...he,"ai.model.provider":re.provider,"ai.model.id":re.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:a})}}}),tracer:z,fn:async F=>{var ve,_e,ue,ae,K,d,f,v;let C=Ue.messages,S=[],{approvedToolApprovals:k,deniedToolApprovals:M}=ZS({messages:C}),x=k.filter(ge=>!ge.toolCall.providerExecuted);if(M.length>0||x.length>0){let ge=await hm({toolCalls:x.map(xe=>xe.toolCall),tools:e,tracer:z,telemetry:g,messages:C,abortSignal:J,experimental_context:P}),Oe=[];for(let xe of ge){let at=await Da({toolCallId:xe.toolCallId,input:xe.input,tool:e?.[xe.toolName],output:xe.type==="tool-result"?xe.output:xe.error,errorMode:xe.type==="tool-error"?"json":"none"});Oe.push({type:"tool-result",toolCallId:xe.toolCallId,toolName:xe.toolName,output:at})}for(let xe of M)Oe.push({type:"tool-result",toolCallId:xe.toolCall.toolCallId,toolName:xe.toolCall.toolName,output:{type:"execution-denied",reason:xe.approvalResponse.reason,...xe.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:xe.approvalResponse.approvalId}}}}});S.push({role:"tool",content:Oe})}let A=[...k,...M].filter(ge=>ge.toolCall.providerExecuted);A.length>0&&S.push({role:"tool",content:A.map(ge=>({type:"tool-approval-response",approvalId:ge.approvalResponse.approvalId,approved:ge.approvalResponse.approved,reason:ge.approvalResponse.reason,providerExecuted:!0}))});let O=um(E),I,U=[],se=[],ie=[],Ce=new Map;do{let ge=ce!=null?setTimeout(()=>B.abort(),ce):void 0;try{let Oe=[...C,...S],xe=await D?.({model:re,steps:ie,stepNumber:ie.length,messages:Oe,experimental_context:P}),at=sm((ve=xe?.model)!=null?ve:re),zr=await ES({prompt:{system:(_e=xe?.system)!=null?_e:Ue.system,messages:(ue=xe?.messages)!=null?ue:Oe},supportedUrls:await at.supportedUrls,download:X});P=(ae=xe?.experimental_context)!=null?ae:P;let{toolChoice:dt,tools:sr}=await IS({tools:e,toolChoice:(K=xe?.toolChoice)!=null?K:r,activeTools:(d=xe?.activeTools)!=null?d:b});I=await j(()=>{var Ae;return kl({name:"ai.generateText.doGenerate",attributes:Tn({telemetry:g,attributes:{...Al({operationId:"ai.generateText.doGenerate",telemetry:g}),...he,"ai.model.provider":at.provider,"ai.model.id":at.modelId,"ai.prompt.messages":{input:()=>zS(zr)},"ai.prompt.tools":{input:()=>sr?.map(ft=>JSON.stringify(ft))},"ai.prompt.toolChoice":{input:()=>dt!=null?JSON.stringify(dt):void 0},"gen_ai.system":at.provider,"gen_ai.request.model":at.modelId,"gen_ai.request.frequency_penalty":E.frequencyPenalty,"gen_ai.request.max_tokens":E.maxOutputTokens,"gen_ai.request.presence_penalty":E.presencePenalty,"gen_ai.request.stop_sequences":E.stopSequences,"gen_ai.request.temperature":(Ae=E.temperature)!=null?Ae:void 0,"gen_ai.request.top_k":E.topK,"gen_ai.request.top_p":E.topP}}),tracer:z,fn:async ft=>{var La,xn,Pl,Dl,jl,Ll,Ul,Fl;let sg=ng(T,xe?.providerOptions),it=await at.doGenerate({...O,tools:sr,toolChoice:dt,responseFormat:await m?.responseFormat,prompt:zr,providerOptions:sg,abortSignal:J,headers:Se}),Wr={id:(xn=(La=it.response)==null?void 0:La.id)!=null?xn:N(),timestamp:(Dl=(Pl=it.response)==null?void 0:Pl.timestamp)!=null?Dl:new Date,modelId:(Ll=(jl=it.response)==null?void 0:jl.modelId)!=null?Ll:at.modelId,headers:(Ul=it.response)==null?void 0:Ul.headers,body:(Fl=it.response)==null?void 0:Fl.body};return ft.setAttributes(await Tn({telemetry:g,attributes:{"ai.response.finishReason":it.finishReason.unified,"ai.response.text":{output:()=>dm(it.content)},"ai.response.toolCalls":{output:()=>{let Hl=fm(it.content);return Hl==null?void 0:JSON.stringify(Hl)}},"ai.response.id":Wr.id,"ai.response.model":Wr.modelId,"ai.response.timestamp":Wr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(it.providerMetadata),"ai.usage.promptTokens":it.usage.inputTokens.total,"ai.usage.completionTokens":it.usage.outputTokens.total,"gen_ai.response.finish_reasons":[it.finishReason.unified],"gen_ai.response.id":Wr.id,"gen_ai.response.model":Wr.modelId,"gen_ai.usage.input_tokens":it.usage.inputTokens.total,"gen_ai.usage.output_tokens":it.usage.outputTokens.total}})),{...it,response:Wr}}})});let Xe=await Promise.all(I.content.filter(Ae=>Ae.type==="tool-call").map(Ae=>lC({toolCall:Ae,tools:e,repairToolCall:V,system:n,messages:Oe}))),Ye={};for(let Ae of Xe){if(Ae.invalid)continue;let ft=e?.[Ae.toolName];ft!=null&&(ft?.onInputAvailable!=null&&await ft.onInputAvailable({input:Ae.input,toolCallId:Ae.toolCallId,messages:Oe,abortSignal:J,experimental_context:P}),await tC({tool:ft,toolCall:Ae,messages:Oe,experimental_context:P})&&(Ye[Ae.toolCallId]={type:"tool-approval-request",approvalId:N(),toolCall:Ae}))}let He=Xe.filter(Ae=>Ae.invalid&&Ae.dynamic);se=[];for(let Ae of He)se.push({type:"tool-error",toolCallId:Ae.toolCallId,toolName:Ae.toolName,input:Ae.input,error:bo(Ae.error),dynamic:!0});U=Xe.filter(Ae=>!Ae.providerExecuted),e!=null&&se.push(...await hm({toolCalls:U.filter(Ae=>!Ae.invalid&&Ye[Ae.toolCallId]==null),tools:e,tracer:z,telemetry:g,messages:Oe,abortSignal:J,experimental_context:P}));for(let Ae of Xe){if(!Ae.providerExecuted)continue;let ft=e?.[Ae.toolName];ft?.type==="provider"&&ft.supportsDeferredResults&&(I.content.some(xn=>xn.type==="tool-result"&&xn.toolCallId===Ae.toolCallId)||Ce.set(Ae.toolCallId,{toolName:Ae.toolName}))}for(let Ae of I.content)Ae.type==="tool-result"&&Ce.delete(Ae.toolCallId);let Nl=gC({content:I.content,toolCalls:Xe,toolOutputs:se,toolApprovalRequests:Object.values(Ye),tools:e});S.push(...await pC({content:Nl,tools:e}));let Ml=new cC({content:Nl,finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:WS(I.usage),warnings:I.warnings,providerMetadata:I.providerMetadata,request:(f=I.request)!=null?f:{},response:{...I.response,messages:structuredClone(S)}});zm({warnings:(v=I.warnings)!=null?v:[],provider:at.provider,model:at.modelId}),ie.push(Ml),await R?.(Ml)}finally{ge!=null&&clearTimeout(ge)}}while((U.length>0&&se.length===U.length||Ce.size>0)&&!await dC({stopConditions:Z,steps:ie}));F.setAttributes(await Tn({telemetry:g,attributes:{"ai.response.finishReason":I.finishReason.unified,"ai.response.text":{output:()=>dm(I.content)},"ai.response.toolCalls":{output:()=>{let ge=fm(I.content);return ge==null?void 0:JSON.stringify(ge)}},"ai.response.providerMetadata":JSON.stringify(I.providerMetadata),"ai.usage.promptTokens":I.usage.inputTokens.total,"ai.usage.completionTokens":I.usage.outputTokens.total}}));let me=ie[ie.length-1],Be=ie.reduce((ge,Oe)=>JS(ge,Oe.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await Q?.({finishReason:me.finishReason,rawFinishReason:me.rawFinishReason,usage:me.usage,content:me.content,text:me.text,reasoningText:me.reasoningText,reasoning:me.reasoning,files:me.files,sources:me.sources,toolCalls:me.toolCalls,staticToolCalls:me.staticToolCalls,dynamicToolCalls:me.dynamicToolCalls,toolResults:me.toolResults,staticToolResults:me.staticToolResults,dynamicToolResults:me.dynamicToolResults,request:me.request,response:me.response,warnings:me.warnings,providerMetadata:me.providerMetadata,steps:ie,totalUsage:Be,experimental_context:P});let Ie;return me.finishReason==="stop"&&(Ie=await(m??ag()).parseCompleteOutput({text:me.text},{response:me.response,usage:me.usage,finishReason:me.finishReason})),new mC({steps:ie,totalUsage:Be,output:Ie})}})}catch(F){throw qS(F)}}async function hm({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i}){return(await Promise.all(t.map(async l=>QS({toolCall:l,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i})))).filter(l=>l!=null)}var mC=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new qx;return this._output}};function fm(t){let e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function gC({content:t,toolCalls:e,toolOutputs:r,toolApprovalRequests:n,tools:o}){let a=[];for(let i of t)switch(i.type){case"text":case"reasoning":case"source":a.push(i);break;case"file":{a.push({type:"file",file:new eC(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{a.push(e.find(s=>s.toolCallId===i.toolCallId));break}case"tool-result":{let s=e.find(l=>l.toolCallId===i.toolCallId);if(s==null){let l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic});break}i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,error:i.result,providerExecuted:!0,dynamic:s.dynamic}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,output:i.result,providerExecuted:!0,dynamic:s.dynamic});break}case"tool-approval-request":{let s=e.find(l=>l.toolCallId===i.toolCallId);if(s==null)throw new Im({toolCallId:i.toolCallId,approvalId:i.approvalId});a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:s});break}}return[...a,...r,...n]}var JM=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
|
|
3976
|
+
`),{name:"GatewayAuthenticationError"})}function Al({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function $S({model:t,settings:e,telemetry:r,headers:n}){var o;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((a,[i,s])=>{if(i==="timeout"){let l=Km(s);l!=null&&(a[`ai.settings.${i}`]=l)}else a[`ai.settings.${i}`]=s;return a},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((a,[i,s])=>(a[`ai.telemetry.metadata.${i}`]=s,a),{}),...Object.entries(n??{}).reduce((a,[i,s])=>(s!==void 0&&(a[`ai.request.headers.${i}`]=s),a),{})}}var GS={startSpan(){return Pa},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Pa);if(typeof r=="function")return r(Pa);if(typeof n=="function")return n(Pa)}},Pa={spanContext(){return BS},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},BS={traceId:"",spanId:"",traceFlags:0};function VS({isEnabled:t=!1,tracer:e}={}){return t?e||Cl.getTracer("ai"):GS}async function kl({name:t,tracer:e,attributes:r,fn:n,endWhenDone:o=!0}){return e.startActiveSpan(t,{attributes:await r},async a=>{try{let i=await n(a);return o&&a.end(),i}catch(i){try{rg(a,i)}finally{a.end()}throw i}})}function rg(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:En.ERROR,message:e.message})):t.setStatus({code:En.ERROR})}async function Tn({telemetry:t,attributes:e}){if(t?.isEnabled!==!0)return{};let r={};for(let[n,o]of Object.entries(e))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(t?.recordInputs===!1)continue;let a=await o.input();a!=null&&(r[n]=a);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(t?.recordOutputs===!1)continue;let a=await o.output();a!=null&&(r[n]=a);continue}r[n]=o}return r}function zS(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?wS(r.data):r.data}:r)})))}function WS(t){return{inputTokens:t.inputTokens.total,inputTokenDetails:{noCacheTokens:t.inputTokens.noCache,cacheReadTokens:t.inputTokens.cacheRead,cacheWriteTokens:t.inputTokens.cacheWrite},outputTokens:t.outputTokens.total,outputTokenDetails:{textTokens:t.outputTokens.text,reasoningTokens:t.outputTokens.reasoning},totalTokens:Wt(t.inputTokens.total,t.outputTokens.total),raw:t.raw,reasoningTokens:t.outputTokens.reasoning,cachedInputTokens:t.inputTokens.cacheRead}}function JS(t,e){var r,n,o,a,i,s,l,c,p,h;return{inputTokens:Wt(t.inputTokens,e.inputTokens),inputTokenDetails:{noCacheTokens:Wt((r=t.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=e.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Wt((o=t.inputTokenDetails)==null?void 0:o.cacheReadTokens,(a=e.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:Wt((i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(s=e.inputTokenDetails)==null?void 0:s.cacheWriteTokens)},outputTokens:Wt(t.outputTokens,e.outputTokens),outputTokenDetails:{textTokens:Wt((l=t.outputTokenDetails)==null?void 0:l.textTokens,(c=e.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Wt((p=t.outputTokenDetails)==null?void 0:p.reasoningTokens,(h=e.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Wt(t.totalTokens,e.totalTokens),reasoningTokens:Wt(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:Wt(t.cachedInputTokens,e.cachedInputTokens)}}function Wt(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function ng(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;let r={...t};for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];if(o===void 0)continue;let a=n in t?t[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),s=a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);i&&s?r[n]=ng(a,o):r[n]=o}return r}function KS({error:t,exponentialBackoffDelay:e}){let r=t.responseHeaders;if(!r)return e;let n,o=r["retry-after-ms"];if(o){let i=parseFloat(o);Number.isNaN(i)||(n=i)}let a=r["retry-after"];if(a&&n===void 0){let i=parseFloat(a);Number.isNaN(i)?n=Date.parse(a)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var YS=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>og(o,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function og(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:o},a=[]){try{return await t()}catch(i){if(xr(i)||e===0)throw i;let s=bo(i),l=[...a,i],c=l.length;if(c>e)throw new am({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&$e.isInstance(i)&&i.isRetryable===!0&&c<=e)return await Zc(KS({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),og(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new am({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function XS({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new ir({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new ir({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}let r=t??2;return{maxRetries:r,retry:YS({maxRetries:r,abortSignal:e})}}function ZS({messages:t}){let e=t.at(-1);if(e?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let r={};for(let l of t)if(l.role==="assistant"&&typeof l.content!="string"){let c=l.content;for(let p of c)p.type==="tool-call"&&(r[p.toolCallId]=p)}let n={};for(let l of t)if(l.role==="assistant"&&typeof l.content!="string"){let c=l.content;for(let p of c)p.type==="tool-approval-request"&&(n[p.approvalId]=p)}let o={};for(let l of e.content)l.type==="tool-result"&&(o[l.toolCallId]=l);let a=[],i=[],s=e.content.filter(l=>l.type==="tool-approval-response");for(let l of s){let c=n[l.approvalId];if(c==null)throw new Nx({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;let p=r[c.toolCallId];if(p==null)throw new Im({toolCallId:c.toolCallId,approvalId:c.approvalId});let h={approvalRequest:c,approvalResponse:l,toolCall:p};l.approved?a.push(h):i.push(h)}return{approvedToolApprovals:a,deniedToolApprovals:i}}async function QS({toolCall:t,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,onPreliminaryToolResult:s}){let{toolName:l,toolCallId:c,input:p}=t,h=e?.[l];if(h?.execute!=null)return kl({name:"ai.toolCall",attributes:Tn({telemetry:n,attributes:{...Al({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(p)}}}),tracer:r,fn:async g=>{let y;try{let S=uu({execute:h.execute.bind(h),input:p,options:{toolCallId:c,messages:o,abortSignal:a,experimental_context:i}});for await(let f of S)f.type==="preliminary"?s?.({...t,type:"tool-result",output:f.output,preliminary:!0}):y=f.output}catch(S){return rg(g,S),{type:"tool-error",toolCallId:c,toolName:l,input:p,error:S,dynamic:h.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{}}}try{g.setAttributes(await Tn({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(y)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:p,output:y,dynamic:h.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{}}}})}function dm(t){let e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var eC=class{constructor({data:t,mediaType:e}){let r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Jt(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Jr(this.base64Data)),this.uint8ArrayData}};async function tC({tool:t,toolCall:e,messages:r,experimental_context:n}){return t.needsApproval==null?!1:typeof t.needsApproval=="boolean"?t.needsApproval:await t.needsApproval(e.input,{toolCallId:e.toolCallId,messages:r,experimental_context:n})}var rC={};Sx(rC,{array:()=>aC,choice:()=>iC,json:()=>sC,object:()=>oC,text:()=>ag});function nC(t){let e=["ROOT"],r=-1,n=null;function o(l,c,p){switch(l){case'"':{r=c,e.pop(),e.push(p),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(p),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(p),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(p),e.push("INSIDE_ARRAY_START");break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function i(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){let c=t[l];switch(e[e.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{a(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{let h=t.substring(n,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?a(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let s=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{s+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{let p=t.substring(n,t.length);"true".startsWith(p)?s+="true".slice(p.length):"false".startsWith(p)?s+="false".slice(p.length):"null".startsWith(p)&&(s+="null".slice(p.length))}}return s}async function ja(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await pt({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await pt({text:nC(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ag=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:t}){return t},async parsePartialOutput({text:t}){return{partial:t}},createElementStreamTransform(){}}),oC=({schema:t,name:e,description:r})=>{let n=ur(t);return{name:"object",responseFormat:Te(n.jsonSchema).then(o=>({type:"json",schema:o,...e!=null&&{name:e},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},a){let i=await pt({text:o});if(!i.success)throw new Pr({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});let s=await nt({value:i.value,schema:n});if(!s.success)throw new Pr({message:"No object generated: response did not match schema.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value},async parsePartialOutput({text:o}){let a=await ja(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){}}},aC=({element:t,name:e,description:r})=>{let n=ur(t);return{name:"array",responseFormat:Te(n.jsonSchema).then(o=>{let{$schema:a,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...e!=null&&{name:e},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},a){let i=await pt({text:o});if(!i.success)throw new Pr({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});let s=i.value;if(s==null||typeof s!="object"||!("elements"in s)||!Array.isArray(s.elements))throw new Pr({message:"No object generated: response did not match schema.",cause:new Pt({value:s,cause:"response must be an object with an elements array"}),text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});for(let l of s.elements){let c=await nt({value:l,schema:n});if(!c.success)throw new Pr({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason})}return s.elements},async parsePartialOutput({text:o}){let a=await ja(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;let s=a.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(let c of s){let p=await nt({value:c,schema:n});p.success&&l.push(p.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:a},i){if(a!=null)for(;o<a.length;o++)i.enqueue(a[o])}})}}},iC=({options:t,name:e,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...e!=null&&{name:e},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){let a=await pt({text:n});if(!a.success)throw new Pr({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});let i=a.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!t.includes(i.result))throw new Pr({message:"No object generated: response did not match schema.",cause:new Pt({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){let o=await ja(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let a=o.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string")return;let i=t.filter(s=>s.startsWith(a.result));return o.state==="successful-parse"?i.includes(a.result)?{partial:a.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),sC=({name:t,description:e}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...t!=null&&{name:t},...e!=null&&{description:e}}),async parseCompleteOutput({text:r},n){let o=await pt({text:r});if(!o.success)throw new Pr({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){let n=await ja(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function lC({toolCall:t,tools:e,repairToolCall:r,system:n,messages:o}){var a;try{if(e==null){if(t.providerExecuted&&t.dynamic)return await ig(t);throw new Il({toolName:t.toolName})}try{return await pm({toolCall:t,tools:e})}catch(i){if(r==null||!(Il.isInstance(i)||Rl.isInstance(i)))throw i;let s=null;try{s=await r({toolCall:t,tools:e,inputSchema:async({toolName:l})=>{let{inputSchema:c}=e[l];return await ur(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new Bx({cause:l,originalError:i})}if(s==null)throw i;return await pm({toolCall:s,tools:e})}}catch(i){let s=await pt({text:t.input}),l=s.success?s.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:l,dynamic:!0,invalid:!0,error:i,title:(a=e?.[t.toolName])==null?void 0:a.title,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}}async function ig(t){let e=t.input.trim()===""?{success:!0,value:{}}:await pt({text:t.input});if(e.success===!1)throw new Rl({toolName:t.toolName,toolInput:t.input,cause:e.error});return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:e.value,providerExecuted:!0,dynamic:!0,providerMetadata:t.providerMetadata}}async function pm({toolCall:t,tools:e}){let r=t.toolName,n=e[r];if(n==null){if(t.providerExecuted&&t.dynamic)return await ig(t);throw new Il({toolName:t.toolName,availableTools:Object.keys(e)})}let o=ur(n.inputSchema),a=t.input.trim()===""?await nt({value:{},schema:o}):await pt({text:t.input,schema:o});if(a.success===!1)throw new Rl({toolName:r,toolInput:t.input,cause:a.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:a.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:a.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,title:n.title}}var cC=class{constructor({content:t,finishReason:e,rawFinishReason:r,usage:n,warnings:o,request:a,response:i,providerMetadata:s}){this.content=t,this.finishReason=e,this.rawFinishReason=r,this.usage=n,this.warnings=o,this.request=a,this.response=i,this.providerMetadata=s}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function uC(t){return({steps:e})=>e.length===t}async function dC({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}async function pC({content:t,tools:e}){let r=[],n=[];for(let a of t)if(a.type!=="source"&&!((a.type==="tool-result"||a.type==="tool-error")&&!a.providerExecuted)&&!(a.type==="text"&&a.text.length===0))switch(a.type){case"text":n.push({type:"text",text:a.text,providerOptions:a.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:a.text,providerOptions:a.providerMetadata});break;case"file":n.push({type:"file",data:a.file.base64,mediaType:a.file.mediaType,providerOptions:a.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":{let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-error":{let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:a.approvalId,toolCallId:a.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});let o=[];for(let a of t){if(!(a.type==="tool-result"||a.type==="tool-error")||a.providerExecuted)continue;let i=await Da({toolCallId:a.toolCallId,input:a.input,tool:e?.[a.toolName],output:a.type==="tool-result"?a.output:a.error,errorMode:a.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,...a.providerMetadata!=null?{providerOptions:a.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function hC(...t){let e=t.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let r=new AbortController;for(let n of e){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var fC=cr({prefix:"aitxt",size:24});async function zM({model:t,tools:e,toolChoice:r,system:n,prompt:o,messages:a,maxRetries:i,abortSignal:s,timeout:l,headers:c,stopWhen:p=uC(1),experimental_output:h,output:g=h,experimental_telemetry:y,providerOptions:S,experimental_activeTools:f,activeTools:b=f,experimental_prepareStep:_,prepareStep:M=_,experimental_repairToolCall:B,experimental_download:Z,experimental_context:N,_internal:{generateId:R=fC}={},onStepFinish:O,onFinish:ee,...E}){let Q=sm(t),X=Ol(p),W=Km(l),ue=hS(l),V=ue!=null?new AbortController:void 0,K=hC(s,W!=null?AbortSignal.timeout(W):void 0,V?.signal),{maxRetries:me,retry:j}=XS({maxRetries:i,abortSignal:K}),ve=um(E),Se=lt(c??{},`ai/${Ym}`),fe=$S({model:Q,telemetry:y,headers:Se,settings:{...ve,maxRetries:me}}),Fe=await HS({system:n,prompt:o,messages:a}),z=VS(y);try{return await kl({name:"ai.generateText",attributes:Tn({telemetry:y,attributes:{...Al({operationId:"ai.generateText",telemetry:y}),...fe,"ai.model.provider":Q.provider,"ai.model.id":Q.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:a})}}}),tracer:z,fn:async U=>{var be,we,de,ae,Y,d,m,v;let C=Fe.messages,x=[],{approvedToolApprovals:k,deniedToolApprovals:D}=ZS({messages:C}),T=k.filter(ye=>!ye.toolCall.providerExecuted);if(D.length>0||T.length>0){let ye=await hm({toolCalls:T.map(xe=>xe.toolCall),tools:e,tracer:z,telemetry:y,messages:C,abortSignal:K,experimental_context:N}),Oe=[];for(let xe of ye){let at=await Da({toolCallId:xe.toolCallId,input:xe.input,tool:e?.[xe.toolName],output:xe.type==="tool-result"?xe.output:xe.error,errorMode:xe.type==="tool-error"?"json":"none"});Oe.push({type:"tool-result",toolCallId:xe.toolCallId,toolName:xe.toolName,output:at})}for(let xe of D)Oe.push({type:"tool-result",toolCallId:xe.toolCall.toolCallId,toolName:xe.toolCall.toolName,output:{type:"execution-denied",reason:xe.approvalResponse.reason,...xe.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:xe.approvalResponse.approvalId}}}}});x.push({role:"tool",content:Oe})}let A=[...k,...D].filter(ye=>ye.toolCall.providerExecuted);A.length>0&&x.push({role:"tool",content:A.map(ye=>({type:"tool-approval-response",approvalId:ye.approvalResponse.approvalId,approved:ye.approvalResponse.approved,reason:ye.approvalResponse.reason,providerExecuted:!0}))});let P=um(E),I,F=[],se=[],ie=[],Ce=new Map;do{let ye=ue!=null?setTimeout(()=>V.abort(),ue):void 0;try{let Oe=[...C,...x],xe=await M?.({model:Q,steps:ie,stepNumber:ie.length,messages:Oe,experimental_context:N}),at=sm((be=xe?.model)!=null?be:Q),zr=await ES({prompt:{system:(we=xe?.system)!=null?we:Fe.system,messages:(de=xe?.messages)!=null?de:Oe},supportedUrls:await at.supportedUrls,download:Z});N=(ae=xe?.experimental_context)!=null?ae:N;let{toolChoice:dt,tools:sr}=await IS({tools:e,toolChoice:(Y=xe?.toolChoice)!=null?Y:r,activeTools:(d=xe?.activeTools)!=null?d:b});I=await j(()=>{var Ae;return kl({name:"ai.generateText.doGenerate",attributes:Tn({telemetry:y,attributes:{...Al({operationId:"ai.generateText.doGenerate",telemetry:y}),...fe,"ai.model.provider":at.provider,"ai.model.id":at.modelId,"ai.prompt.messages":{input:()=>zS(zr)},"ai.prompt.tools":{input:()=>sr?.map(ft=>JSON.stringify(ft))},"ai.prompt.toolChoice":{input:()=>dt!=null?JSON.stringify(dt):void 0},"gen_ai.system":at.provider,"gen_ai.request.model":at.modelId,"gen_ai.request.frequency_penalty":E.frequencyPenalty,"gen_ai.request.max_tokens":E.maxOutputTokens,"gen_ai.request.presence_penalty":E.presencePenalty,"gen_ai.request.stop_sequences":E.stopSequences,"gen_ai.request.temperature":(Ae=E.temperature)!=null?Ae:void 0,"gen_ai.request.top_k":E.topK,"gen_ai.request.top_p":E.topP}}),tracer:z,fn:async ft=>{var La,xn,Pl,Dl,jl,Ll,Fl,Ul;let sg=ng(S,xe?.providerOptions),it=await at.doGenerate({...P,tools:sr,toolChoice:dt,responseFormat:await g?.responseFormat,prompt:zr,providerOptions:sg,abortSignal:K,headers:Se}),Wr={id:(xn=(La=it.response)==null?void 0:La.id)!=null?xn:R(),timestamp:(Dl=(Pl=it.response)==null?void 0:Pl.timestamp)!=null?Dl:new Date,modelId:(Ll=(jl=it.response)==null?void 0:jl.modelId)!=null?Ll:at.modelId,headers:(Fl=it.response)==null?void 0:Fl.headers,body:(Ul=it.response)==null?void 0:Ul.body};return ft.setAttributes(await Tn({telemetry:y,attributes:{"ai.response.finishReason":it.finishReason.unified,"ai.response.text":{output:()=>dm(it.content)},"ai.response.toolCalls":{output:()=>{let Hl=fm(it.content);return Hl==null?void 0:JSON.stringify(Hl)}},"ai.response.id":Wr.id,"ai.response.model":Wr.modelId,"ai.response.timestamp":Wr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(it.providerMetadata),"ai.usage.promptTokens":it.usage.inputTokens.total,"ai.usage.completionTokens":it.usage.outputTokens.total,"gen_ai.response.finish_reasons":[it.finishReason.unified],"gen_ai.response.id":Wr.id,"gen_ai.response.model":Wr.modelId,"gen_ai.usage.input_tokens":it.usage.inputTokens.total,"gen_ai.usage.output_tokens":it.usage.outputTokens.total}})),{...it,response:Wr}}})});let Xe=await Promise.all(I.content.filter(Ae=>Ae.type==="tool-call").map(Ae=>lC({toolCall:Ae,tools:e,repairToolCall:B,system:n,messages:Oe}))),Ye={};for(let Ae of Xe){if(Ae.invalid)continue;let ft=e?.[Ae.toolName];ft!=null&&(ft?.onInputAvailable!=null&&await ft.onInputAvailable({input:Ae.input,toolCallId:Ae.toolCallId,messages:Oe,abortSignal:K,experimental_context:N}),await tC({tool:ft,toolCall:Ae,messages:Oe,experimental_context:N})&&(Ye[Ae.toolCallId]={type:"tool-approval-request",approvalId:R(),toolCall:Ae}))}let He=Xe.filter(Ae=>Ae.invalid&&Ae.dynamic);se=[];for(let Ae of He)se.push({type:"tool-error",toolCallId:Ae.toolCallId,toolName:Ae.toolName,input:Ae.input,error:bo(Ae.error),dynamic:!0});F=Xe.filter(Ae=>!Ae.providerExecuted),e!=null&&se.push(...await hm({toolCalls:F.filter(Ae=>!Ae.invalid&&Ye[Ae.toolCallId]==null),tools:e,tracer:z,telemetry:y,messages:Oe,abortSignal:K,experimental_context:N}));for(let Ae of Xe){if(!Ae.providerExecuted)continue;let ft=e?.[Ae.toolName];ft?.type==="provider"&&ft.supportsDeferredResults&&(I.content.some(xn=>xn.type==="tool-result"&&xn.toolCallId===Ae.toolCallId)||Ce.set(Ae.toolCallId,{toolName:Ae.toolName}))}for(let Ae of I.content)Ae.type==="tool-result"&&Ce.delete(Ae.toolCallId);let Nl=gC({content:I.content,toolCalls:Xe,toolOutputs:se,toolApprovalRequests:Object.values(Ye),tools:e});x.push(...await pC({content:Nl,tools:e}));let Ml=new cC({content:Nl,finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:WS(I.usage),warnings:I.warnings,providerMetadata:I.providerMetadata,request:(m=I.request)!=null?m:{},response:{...I.response,messages:structuredClone(x)}});zm({warnings:(v=I.warnings)!=null?v:[],provider:at.provider,model:at.modelId}),ie.push(Ml),await O?.(Ml)}finally{ye!=null&&clearTimeout(ye)}}while((F.length>0&&se.length===F.length||Ce.size>0)&&!await dC({stopConditions:X,steps:ie}));U.setAttributes(await Tn({telemetry:y,attributes:{"ai.response.finishReason":I.finishReason.unified,"ai.response.text":{output:()=>dm(I.content)},"ai.response.toolCalls":{output:()=>{let ye=fm(I.content);return ye==null?void 0:JSON.stringify(ye)}},"ai.response.providerMetadata":JSON.stringify(I.providerMetadata),"ai.usage.promptTokens":I.usage.inputTokens.total,"ai.usage.completionTokens":I.usage.outputTokens.total}}));let ge=ie[ie.length-1],Be=ie.reduce((ye,Oe)=>JS(ye,Oe.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await ee?.({finishReason:ge.finishReason,rawFinishReason:ge.rawFinishReason,usage:ge.usage,content:ge.content,text:ge.text,reasoningText:ge.reasoningText,reasoning:ge.reasoning,files:ge.files,sources:ge.sources,toolCalls:ge.toolCalls,staticToolCalls:ge.staticToolCalls,dynamicToolCalls:ge.dynamicToolCalls,toolResults:ge.toolResults,staticToolResults:ge.staticToolResults,dynamicToolResults:ge.dynamicToolResults,request:ge.request,response:ge.response,warnings:ge.warnings,providerMetadata:ge.providerMetadata,steps:ie,totalUsage:Be,experimental_context:N});let Ie;return ge.finishReason==="stop"&&(Ie=await(g??ag()).parseCompleteOutput({text:ge.text},{response:ge.response,usage:ge.usage,finishReason:ge.finishReason})),new mC({steps:ie,totalUsage:Be,output:Ie})}})}catch(U){throw qS(U)}}async function hm({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i}){return(await Promise.all(t.map(async l=>QS({toolCall:l,tools:e,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i})))).filter(l=>l!=null)}var mC=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new qx;return this._output}};function fm(t){let e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function gC({content:t,toolCalls:e,toolOutputs:r,toolApprovalRequests:n,tools:o}){let a=[];for(let i of t)switch(i.type){case"text":case"reasoning":case"source":a.push(i);break;case"file":{a.push({type:"file",file:new eC(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{a.push(e.find(s=>s.toolCallId===i.toolCallId));break}case"tool-result":{let s=e.find(l=>l.toolCallId===i.toolCallId);if(s==null){let l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic});break}i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,error:i.result,providerExecuted:!0,dynamic:s.dynamic}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,output:i.result,providerExecuted:!0,dynamic:s.dynamic});break}case"tool-approval-request":{let s=e.find(l=>l.toolCallId===i.toolCallId);if(s==null)throw new Im({toolCallId:i.toolCallId,approvalId:i.approvalId});a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:s});break}}return[...a,...r,...n]}var JM=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
|
|
3974
3977
|
|
|
3975
3978
|
`)},flush(t){t.enqueue(`data: [DONE]
|
|
3976
3979
|
|
|
3977
|
-
`)}})}};var XM=q(()=>H(L.union([L.strictObject({type:L.literal("text-start"),id:L.string(),providerMetadata:
|
|
3980
|
+
`)}})}};var XM=q(()=>H(L.union([L.strictObject({type:L.literal("text-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("error"),errorText:L.string()}),L.strictObject({type:L.literal("tool-input-start"),toolCallId:L.string(),toolName:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-delta"),toolCallId:L.string(),inputTextDelta:L.string()}),L.strictObject({type:L.literal("tool-input-available"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-error"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),errorText:L.string(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-approval-request"),approvalId:L.string(),toolCallId:L.string()}),L.strictObject({type:L.literal("tool-output-available"),toolCallId:L.string(),output:L.unknown(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),preliminary:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-error"),toolCallId:L.string(),errorText:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-denied"),toolCallId:L.string()}),L.strictObject({type:L.literal("reasoning-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-url"),sourceId:L.string(),url:L.string(),title:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-document"),sourceId:L.string(),mediaType:L.string(),title:L.string(),filename:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("file"),url:L.string(),mediaType:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.custom(t=>typeof t=="string"&&t.startsWith("data-"),{message:'Type must start with "data-"'}),id:L.string().optional(),data:L.unknown(),transient:L.boolean().optional()}),L.strictObject({type:L.literal("start-step")}),L.strictObject({type:L.literal("finish-step")}),L.strictObject({type:L.literal("start"),messageId:L.string().optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("finish"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("abort"),reason:L.string().optional()}),L.strictObject({type:L.literal("message-metadata"),messageMetadata:L.unknown()})])));var ZM=cr({prefix:"aitxt",size:24});var t1=q(()=>H(w.array(w.object({id:w.string(),role:w.enum(["system","user","assistant"]),metadata:w.unknown().optional(),parts:w.array(w.union([w.object({type:w.literal("text"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("reasoning"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-url"),sourceId:w.string(),url:w.string(),title:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-document"),sourceId:w.string(),mediaType:w.string(),title:w.string(),filename:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("file"),mediaType:w.string(),filename:w.string().optional(),url:w.string(),providerMetadata:he.optional()}),w.object({type:w.literal("step-start")}),w.object({type:w.string().startsWith("data-"),id:w.string().optional(),data:w.unknown()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-streaming"),input:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-error"),input:w.unknown(),rawInput:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-denied"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-streaming"),providerExecuted:w.boolean().optional(),input:w.unknown().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-error"),providerExecuted:w.boolean().optional(),input:w.unknown(),rawInput:w.unknown().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-denied"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var n1=cr({prefix:"aiobj",size:24});var a1=cr({prefix:"aiobj",size:24});var yC="AI_NoSuchProviderError",vC=`vercel.ai.error.${yC}`,bC=Symbol.for(vC),_C;_C=bC;export{cg as a,EC as b,WR as c,JR as d,rC as e,zM as f,cl as g,Ta as h,Bh as i,Vh as j,XR as k,ZR as l,QR as m,pO as n,yO as o};
|
|
3978
3981
|
/*! Bundled license information:
|
|
3979
3982
|
|
|
3980
3983
|
safe-buffer/index.js:
|