@visa/cli 2.0.0-rc.41 → 2.0.0-rc.42

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/cli.js CHANGED
@@ -1,18 +1,8 @@
1
- "use strict";var cQ=Object.create;var Mp=Object.defineProperty;var uQ=Object.getOwnPropertyDescriptor;var lQ=Object.getOwnPropertyNames;var dQ=Object.getPrototypeOf,pQ=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(t&&(e=t(t=0)),e);var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Lp=(t,e)=>{for(var n in e)Mp(t,n,{get:e[n],enumerable:!0})},yv=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lQ(e))!pQ.call(t,o)&&o!==n&&Mp(t,o,{get:()=>e[o],enumerable:!(r=uQ(e,o))||r.enumerable});return t};var v=(t,e,n)=>(n=t!=null?cQ(dQ(t)):{},yv(e||!t||!t.__esModule?Mp(n,"default",{value:t,enumerable:!0}):n,t)),b=t=>yv(Mp({},"__esModule",{value:!0}),t);var kp=m((sFe,NQ)=>{NQ.exports={name:"@visa/cli",version:"2.0.0-rc.41",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.2","@typescript-eslint/parser":"^8.59.1","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var nT=m(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.micros=Ete;ft.fromCents=Ste;ft.fromUsdc=gte;ft.fromUsd=hte;ft.toCents=Tte;ft.toCentsForAcquirer=Ate;ft.toUsdc=Rte;ft.toWire=yte;ft.fromWire=Ote;ft.toDisplay=Nte;ft.toUsdRounded2dp=Cte;ft.add=vte;ft.sub=Ite;ft.clampNonNegative=Pte;ft.isNonNegative=bte;ft.max=Mte;ft.min=Lte;var bo=10000n,AP=1000000n;function Ete(t){return t}function Ste(t){if(!Number.isFinite(t)||!Number.isInteger(t)||!Number.isSafeInteger(t))throw new TypeError(`fromCents: expected safe integer, got ${t}`);return BigInt(t)*bo}function gte(t){return t}function hte(t){if(!Number.isFinite(t))throw new TypeError(`fromUsd: expected finite number, got ${t}`);return BigInt(Math.round(t*1e6))}function Tte(t){if(t>=0n)return Number(t/bo);let e=t/bo,n=t%bo;return Number(n===0n?e:e-1n)}function Ate(t){if(t<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${t}); card charges are non-negative`);return Number(t/bo)}function Rte(t){return t}function yte(t){return t.toString()}function Ote(t){if(typeof t!="string"||t.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof t} ${JSON.stringify(t)}`);if(!/^-?\d+$/.test(t))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(t)}`);return BigInt(t)}function Nte(t,e={}){let n=e.decimals??2,r=e.symbol??"$",o=t<0n,s=o?-t:t,i=s/AP,a=s%AP,c=o?"-":"";if(n===0)return`${c}${r}${i.toString()}`;let u=a.toString().padStart(6,"0").slice(0,n);return`${c}${r}${i.toString()}.${u}`}function Cte(t){let e=t<0n,n=e?-t:t,r=n/bo,s=n%bo*2n,i;s<bo?i=r:s>bo?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return e?-a:a}function vte(t,e){return t+e}function Ite(t,e){return t-e}function Pte(t){return t<0n?0n:t}function bte(t){return t>=0n}function Mte(t,e){return t>e?t:e}function Lte(t,e){return t<e?t:e}});var Lo,ET=$(()=>{Lo="1.9.1"});function hre(t){let e=new Set([t]),n=new Set,r=t.match(ab);if(!r)return()=>!1;let o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(c){return c===t};function s(a){return n.add(a),!1}function i(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(n.has(c))return!1;let u=c.match(ab);if(!u)return s(c);let l={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return l.prerelease!=null||o.major!==l.major?s(c):o.major===0?o.minor===l.minor&&o.patch<=l.patch?i(c):s(c):o.minor<=l.minor?i(c):s(c)}}var ab,cb,ub=$(()=>{ET();ab=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;cb=hre(Lo)});function jr(t,e,n,r=!1){var o;let s=Nl[Ol]=(o=Nl[Ol])!==null&&o!==void 0?o:{version:Lo};if(!r&&s[t]){let i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return n.error(i.stack||i.message),!1}if(s.version!==Lo){let i=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${Lo}`);return n.error(i.stack||i.message),!1}return s[t]=e,n.debug(`@opentelemetry/api: Registered a global for ${t} v${Lo}.`),!0}function bn(t){var e,n;let r=(e=Nl[Ol])===null||e===void 0?void 0:e.version;if(!(!r||!cb(r)))return(n=Nl[Ol])===null||n===void 0?void 0:n[t]}function qr(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Lo}.`);let n=Nl[Ol];n&&delete n[t]}var Tre,Ol,Nl,Ki=$(()=>{ET();ub();Tre=Lo.split(".")[0],Ol=Symbol.for(`opentelemetry.js.api.${Tre}`),Nl=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function Cl(t,e,n){let r=bn("diag");if(r)return r[t](e,...n)}var D_,lb=$(()=>{Ki();D_=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Cl("debug",this._namespace,e)}error(...e){return Cl("error",this._namespace,e)}info(...e){return Cl("info",this._namespace,e)}warn(...e){return Cl("warn",this._namespace,e)}verbose(...e){return Cl("verbose",this._namespace,e)}}});var mt,U_=$(()=>{(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"})(mt||(mt={}))});function db(t,e){t<mt.NONE?t=mt.NONE:t>mt.ALL&&(t=mt.ALL),e=e||{};function n(r,o){let s=e[r];return typeof s=="function"&&t>=o?s.bind(e):function(){}}return{error:n("error",mt.ERROR),warn:n("warn",mt.WARN),info:n("info",mt.INFO),debug:n("debug",mt.DEBUG),verbose:n("verbose",mt.VERBOSE)}}var pb=$(()=>{U_()});var Are,At,Wi=$(()=>{lb();pb();U_();Ki();Are="diag",At=class t{static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(o){return function(...s){let i=bn("diag");if(i)return i[o](...s)}}let n=this,r=(o,s={logLevel:mt.INFO})=>{var i,a,c;if(o===n){let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((i=d.stack)!==null&&i!==void 0?i:d.message),!1}typeof s=="number"&&(s={logLevel:s});let u=bn("diag"),l=db((a=s.logLevel)!==null&&a!==void 0?a:mt.INFO,o);if(u&&!s.suppressOverrideMessage){let d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn(`Current logger will be overwritten from ${d}`),l.warn(`Current logger will overwrite one already registered from ${d}`)}return jr("diag",l,n,!0)};n.setLogger=r,n.disable=()=>{qr(Are,n)},n.createComponentLogger=o=>new D_(o),n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}}});var w_,_b=$(()=>{w_=class t{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let n=this._entries.get(e);if(n)return Object.assign({},n)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,n){let r=new t(this._entries);return r._entries.set(e,n),r}removeEntry(e){let n=new t(this._entries);return n._entries.delete(e),n}removeEntries(...e){let n=new t(this._entries);for(let r of e)n._entries.delete(r);return n}clear(){return new t}}});var fb,mb=$(()=>{fb=Symbol("BaggageEntryMetadata")});function Eb(t={}){return new w_(new Map(Object.entries(t)))}function Sb(t){return typeof t!="string"&&(Rre.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:fb,toString(){return t}}}var Rre,ST=$(()=>{Wi();_b();mb();Rre=At.instance()});function gr(t){return Symbol.for(t)}var gT,sc,vl=$(()=>{gT=class t{constructor(e){let n=this;n._currentContext=e?new Map(e):new Map,n.getValue=r=>n._currentContext.get(r),n.setValue=(r,o)=>{let s=new t(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=r=>{let o=new t(n._currentContext);return o._currentContext.delete(r),o}}},sc=new gT});var hT,TT,k_,gb=$(()=>{hT=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],TT={};if(typeof console<"u"){let t=["error","warn","info","debug","trace","log"];for(let e of t)typeof console[e]=="function"&&(TT[e]=console[e])}k_=class{constructor(){function e(n){return function(...r){let o=TT[n];if(typeof o!="function"&&(o=TT.log),typeof o!="function"&&console&&(o=console[n],typeof o!="function"&&(o=console.log)),typeof o=="function")return o.apply(console,r)}}for(let n=0;n<hT.length;n++)this[hT[n].n]=e(hT[n].c)}}});function hb(){return PT}var AT,ic,RT,yT,OT,NT,Il,CT,vT,IT,PT,yre,Ore,Nre,Cre,vre,Ire,Pre,bT=$(()=>{AT=class{constructor(){}createGauge(e,n){return Ore}createHistogram(e,n){return Nre}createCounter(e,n){return yre}createUpDownCounter(e,n){return Cre}createObservableGauge(e,n){return Ire}createObservableCounter(e,n){return vre}createObservableUpDownCounter(e,n){return Pre}addBatchObservableCallback(e,n){}removeBatchObservableCallback(e){}},ic=class{},RT=class extends ic{add(e,n){}},yT=class extends ic{add(e,n){}},OT=class extends ic{record(e,n){}},NT=class extends ic{record(e,n){}},Il=class{addCallback(e){}removeCallback(e){}},CT=class extends Il{},vT=class extends Il{},IT=class extends Il{},PT=new AT,yre=new RT,Ore=new OT,Nre=new NT,Cre=new yT,vre=new CT,Ire=new vT,Pre=new IT});var V_,Tb=$(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(V_||(V_={}))});var B_,G_,MT=$(()=>{B_={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},G_={set(t,e,n){t!=null&&(t[e]=n)}}});var H_,Ab=$(()=>{vl();H_=class{active(){return sc}with(e,n,r,...o){return n.call(r,...o)}bind(e,n){return n}enable(){return this}disable(){return this}}});var LT,bre,Yr,Pl=$(()=>{Ab();Ki();Wi();LT="context",bre=new H_,Yr=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return jr(LT,e,At.instance())}active(){return this._getContextManager().active()}with(e,n,r,...o){return this._getContextManager().with(e,n,r,...o)}bind(e,n){return this._getContextManager().bind(e,n)}_getContextManager(){return bn(LT)||bre}disable(){this._getContextManager().disable(),qr(LT,At.instance())}}});var Kn,xT=$(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Kn||(Kn={}))});var bl,zi,$_,F_=$(()=>{xT();bl="0000000000000000",zi="00000000000000000000000000000000",$_={traceId:zi,spanId:bl,traceFlags:Kn.NONE}});var Kr,j_=$(()=>{F_();Kr=class{constructor(e=$_){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,n){return this}setAttributes(e){return this}addEvent(e,n){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,n){}}});function q_(t){return t.getValue(DT)||void 0}function Rb(){return q_(Yr.getInstance().active())}function Ml(t,e){return t.setValue(DT,e)}function yb(t){return t.deleteValue(DT)}function Ob(t,e){return Ml(t,new Kr(e))}function Y_(t){var e;return(e=q_(t))===null||e===void 0?void 0:e.spanContext()}var DT,UT=$(()=>{vl();j_();Pl();DT=gr("OpenTelemetry Context Key SPAN")});function Nb(t,e){if(typeof t!="string"||t.length!==e)return!1;let n=0;for(let r=0;r<t.length;r+=4)n+=(K_[t.charCodeAt(r)]|0)+(K_[t.charCodeAt(r+1)]|0)+(K_[t.charCodeAt(r+2)]|0)+(K_[t.charCodeAt(r+3)]|0);return n===e}function wT(t){return Nb(t,32)&&t!==zi}function kT(t){return Nb(t,16)&&t!==bl}function xo(t){return wT(t.traceId)&&kT(t.spanId)}function Cb(t){return new Kr(t)}var K_,W_=$(()=>{F_();j_();K_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});function Mre(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var VT,ac,BT=$(()=>{Pl();UT();j_();W_();VT=Yr.getInstance(),ac=class{startSpan(e,n,r=VT.active()){if(!!n?.root)return new Kr;let s=r&&Y_(r);return Mre(s)&&xo(s)?new Kr(s):new Kr}startActiveSpan(e,n,r,o){let s,i,a;if(arguments.length<2)return;arguments.length===2?a=n:arguments.length===3?(s=n,a=r):(s=n,i=r,a=o);let c=i??VT.active(),u=this.startSpan(e,s,c),l=Ml(c,u);return VT.with(l,a,void 0,u)}}});var Lre,cc,GT=$(()=>{BT();Lre=new ac,cc=class{constructor(e,n,r,o){this._provider=e,this.name=n,this.version=r,this.options=o}startSpan(e,n,r){return this._getTracer().startSpan(e,n,r)}startActiveSpan(e,n,r,o){let s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Lre}}});var z_,vb=$(()=>{BT();z_=class{getTracer(e,n,r){return new ac}}});var xre,Xi,HT=$(()=>{GT();vb();xre=new z_,Xi=class{getTracer(e,n,r){var o;return(o=this.getDelegateTracer(e,n,r))!==null&&o!==void 0?o:new cc(this,e,n,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:xre}setDelegate(e){this._delegate=e}getDelegateTracer(e,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,n,r)}}});var X_,Ib=$(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(X_||(X_={}))});var Dt,Pb=$(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Dt||(Dt={}))});var Me,bb=$(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Me||(Me={}))});function Mb(t){return wre.test(t)}function Lb(t){return kre.test(t)&&!Vre.test(t)}var $T,Dre,Ure,wre,kre,Vre,xb=$(()=>{$T="[_0-9a-z-*/]",Dre=`[a-z]${$T}{0,255}`,Ure=`[a-z0-9]${$T}{0,240}@[a-z]${$T}{0,13}`,wre=new RegExp(`^(?:${Dre}|${Ure})$`),kre=/^[ -~]{0,255}[!-~]$/,Vre=/,|=/});var Db,Bre,Ub,wb,J_,kb=$(()=>{xb();Db=32,Bre=512,Ub=",",wb="=",J_=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,n){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,n),r}unset(e){let n=this._clone();return n._internalState.delete(e),n}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,n)=>(e.push(n+wb+this.get(n)),e),[]).join(Ub)}_parse(e){e.length>Bre||(this._internalState=e.split(Ub).reduceRight((n,r)=>{let o=r.trim(),s=o.indexOf(wb);if(s!==-1){let i=o.slice(0,s),a=o.slice(s+1,r.length);Mb(i)&&Lb(a)&&n.set(i,a)}return n},new Map),this._internalState.size>Db&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Db))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function Vb(t){return new J_(t)}var Bb=$(()=>{kb()});var X,Gb=$(()=>{Pl();X=Yr.getInstance()});var Mn,Hb=$(()=>{Wi();Mn=At.instance()});var FT,$b,Fb=$(()=>{bT();FT=class{getMeter(e,n,r){return PT}},$b=new FT});var jT,Z_,jb=$(()=>{Fb();Ki();Wi();jT="metrics",Z_=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return jr(jT,e,At.instance())}getMeterProvider(){return bn(jT)||$b}getMeter(e,n,r){return this.getMeterProvider().getMeter(e,n,r)}disable(){qr(jT,At.instance())}}});var qT,qb=$(()=>{jb();qT=Z_.getInstance()});var Q_,Yb=$(()=>{Q_=class{inject(e,n){}extract(e,n){return e}fields(){return[]}}});function KT(t){return t.getValue(YT)||void 0}function Kb(){return KT(Yr.getInstance().active())}function Wb(t,e){return t.setValue(YT,e)}function zb(t){return t.deleteValue(YT)}var YT,Xb=$(()=>{Pl();vl();YT=gr("OpenTelemetry Baggage Key")});var WT,Gre,ef,Jb=$(()=>{Ki();Yb();MT();Xb();ST();Wi();WT="propagation",Gre=new Q_,ef=class t{constructor(){this.createBaggage=Eb,this.getBaggage=KT,this.getActiveBaggage=Kb,this.setBaggage=Wb,this.deleteBaggage=zb}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalPropagator(e){return jr(WT,e,At.instance())}inject(e,n,r=G_){return this._getGlobalPropagator().inject(e,n,r)}extract(e,n,r=B_){return this._getGlobalPropagator().extract(e,n,r)}fields(){return this._getGlobalPropagator().fields()}disable(){qr(WT,At.instance())}_getGlobalPropagator(){return bn(WT)||Gre}}});var rn,Zb=$(()=>{Jb();rn=ef.getInstance()});var zT,tf,Qb=$(()=>{Ki();HT();W_();UT();Wi();zT="trace",tf=class t{constructor(){this._proxyTracerProvider=new Xi,this.wrapSpanContext=Cb,this.isSpanContextValid=xo,this.deleteSpan=yb,this.getSpan=q_,this.getActiveSpan=Rb,this.getSpanContext=Y_,this.setSpan=Ml,this.setSpanContext=Ob}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let n=jr(zT,this._proxyTracerProvider,At.instance());return n&&this._proxyTracerProvider.setDelegate(e),n}getTracerProvider(){return bn(zT)||this._proxyTracerProvider}getTracer(e,n){return this.getTracerProvider().getTracer(e,n)}disable(){qr(zT,At.instance()),this._proxyTracerProvider=new Xi}}});var oe,eM=$(()=>{Qb();oe=tf.getInstance()});var B={};Lp(B,{DiagConsoleLogger:()=>k_,DiagLogLevel:()=>mt,INVALID_SPANID:()=>bl,INVALID_SPAN_CONTEXT:()=>$_,INVALID_TRACEID:()=>zi,ProxyTracer:()=>cc,ProxyTracerProvider:()=>Xi,ROOT_CONTEXT:()=>sc,SamplingDecision:()=>X_,SpanKind:()=>Dt,SpanStatusCode:()=>Me,TraceFlags:()=>Kn,ValueType:()=>V_,baggageEntryMetadataFromString:()=>Sb,context:()=>X,createContextKey:()=>gr,createNoopMeter:()=>hb,createTraceState:()=>Vb,default:()=>Hre,defaultTextMapGetter:()=>B_,defaultTextMapSetter:()=>G_,diag:()=>Mn,isSpanContextValid:()=>xo,isValidSpanId:()=>kT,isValidTraceId:()=>wT,metrics:()=>qT,propagation:()=>rn,trace:()=>oe});var Hre,x=$(()=>{ST();vl();gb();U_();bT();Tb();MT();GT();HT();Ib();Pb();bb();xT();Bb();W_();F_();Gb();Hb();qb();Zb();eM();Hre={context:X,diag:Mn,metrics:qT,propagation:rn,trace:oe}});var Ll=m(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.isTracingSuppressed=Ns.unsuppressTracing=Ns.suppressTracing=void 0;var $re=(x(),b(B)),XT=(0,$re.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function Fre(t){return t.setValue(XT,!0)}Ns.suppressTracing=Fre;function jre(t){return t.deleteValue(XT)}Ns.unsuppressTracing=jre;function qre(t){return t.getValue(XT)===!0}Ns.isTracingSuppressed=qre});var JT=m(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.BAGGAGE_MAX_TOTAL_LENGTH=Ft.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=Ft.BAGGAGE_MAX_NAME_VALUE_PAIRS=Ft.BAGGAGE_HEADER=Ft.BAGGAGE_ITEMS_SEPARATOR=Ft.BAGGAGE_PROPERTIES_SEPARATOR=Ft.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;Ft.BAGGAGE_KEY_PAIR_SEPARATOR="=";Ft.BAGGAGE_PROPERTIES_SEPARATOR=";";Ft.BAGGAGE_ITEMS_SEPARATOR=",";Ft.BAGGAGE_HEADER="baggage";Ft.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;Ft.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;Ft.BAGGAGE_MAX_TOTAL_LENGTH=8192});var ZT=m(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.parseKeyPairsIntoRecord=Wr.parsePairKeyValue=Wr.getKeyPairs=Wr.serializeKeyPairs=void 0;var Yre=(x(),b(B)),Ji=JT();function Kre(t){return t.reduce((e,n)=>{let r=`${e}${e!==""?Ji.BAGGAGE_ITEMS_SEPARATOR:""}${n}`;return r.length>Ji.BAGGAGE_MAX_TOTAL_LENGTH?e:r},"")}Wr.serializeKeyPairs=Kre;function Wre(t){return t.getAllEntries().map(([e,n])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(n.value)}`;return n.metadata!==void 0&&(r+=Ji.BAGGAGE_PROPERTIES_SEPARATOR+n.metadata.toString()),r})}Wr.getKeyPairs=Wre;function tM(t){let e=t.split(Ji.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let n=e.shift();if(!n)return;let r=n.indexOf(Ji.BAGGAGE_KEY_PAIR_SEPARATOR);if(r<=0)return;let o=decodeURIComponent(n.substring(0,r).trim()),s=decodeURIComponent(n.substring(r+1).trim()),i;return e.length>0&&(i=(0,Yre.baggageEntryMetadataFromString)(e.join(Ji.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:i}}Wr.parsePairKeyValue=tM;function zre(t){return typeof t!="string"||t.length===0?{}:t.split(Ji.BAGGAGE_ITEMS_SEPARATOR).map(e=>tM(e)).filter(e=>e!==void 0&&e.value.length>0).reduce((e,n)=>(e[n.key]=n.value,e),{})}Wr.parseKeyPairsIntoRecord=zre});var nM=m(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});nf.W3CBaggagePropagator=void 0;var QT=(x(),b(B)),Xre=Ll(),Zi=JT(),eA=ZT(),tA=class{inject(e,n,r){let o=QT.propagation.getBaggage(e);if(!o||(0,Xre.isTracingSuppressed)(e))return;let s=(0,eA.getKeyPairs)(o).filter(a=>a.length<=Zi.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,Zi.BAGGAGE_MAX_NAME_VALUE_PAIRS),i=(0,eA.serializeKeyPairs)(s);i.length>0&&r.set(n,Zi.BAGGAGE_HEADER,i)}extract(e,n,r){let o=r.get(n,Zi.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(Zi.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let i={};return s.length===0||(s.split(Zi.BAGGAGE_ITEMS_SEPARATOR).forEach(c=>{let u=(0,eA.parsePairKeyValue)(c);if(u){let l={value:u.value};u.metadata&&(l.metadata=u.metadata),i[u.key]=l}}),Object.entries(i).length===0)?e:QT.propagation.setBaggage(e,QT.propagation.createBaggage(i))}fields(){return[Zi.BAGGAGE_HEADER]}};nf.W3CBaggagePropagator=tA});var rM=m(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.AnchoredClock=void 0;var nA=class{constructor(e,n){this._monotonicClock=n,this._epochMillis=e.now(),this._performanceMillis=n.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};rf.AnchoredClock=nA});var cM=m(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.isAttributeValue=Cs.isAttributeKey=Cs.sanitizeAttributes=void 0;var oM=(x(),b(B));function Jre(t){let e={};if(typeof t!="object"||t==null)return e;for(let[n,r]of Object.entries(t)){if(!sM(n)){oM.diag.warn(`Invalid attribute key: ${n}`);continue}if(!iM(r)){oM.diag.warn(`Invalid attribute value set for key: ${n}`);continue}Array.isArray(r)?e[n]=r.slice():e[n]=r}return e}Cs.sanitizeAttributes=Jre;function sM(t){return typeof t=="string"&&t.length>0}Cs.isAttributeKey=sM;function iM(t){return t==null?!0:Array.isArray(t)?Zre(t):aM(t)}Cs.isAttributeValue=iM;function Zre(t){let e;for(let n of t)if(n!=null){if(!e){if(aM(n)){e=typeof n;continue}return!1}if(typeof n!==e)return!1}return!0}function aM(t){switch(typeof t){case"number":case"boolean":case"string":return!0}return!1}});var rA=m(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});of.loggingErrorHandler=void 0;var Qre=(x(),b(B));function eoe(){return t=>{Qre.diag.error(toe(t))}}of.loggingErrorHandler=eoe;function toe(t){return typeof t=="string"?t:JSON.stringify(noe(t))}function noe(t){let e={},n=t;for(;n!==null;)Object.getOwnPropertyNames(n).forEach(r=>{if(e[r])return;let o=n[r];o&&(e[r]=String(o))}),n=Object.getPrototypeOf(n);return e}});var oA=m(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.globalErrorHandler=uc.setGlobalErrorHandler=void 0;var roe=rA(),uM=(0,roe.loggingErrorHandler)();function ooe(t){uM=t}uc.setGlobalErrorHandler=ooe;function soe(t){try{uM(t)}catch{}}uc.globalErrorHandler=soe});var sA=m(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.TracesSamplerValues=void 0;var ioe;(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(ioe=xl.TracesSamplerValues||(xl.TracesSamplerValues={}))});var iA=m(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.parseEnvironment=Ve.DEFAULT_ENVIRONMENT=Ve.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT=Ve.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT=Ve.DEFAULT_ATTRIBUTE_COUNT_LIMIT=Ve.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=void 0;var vs=(x(),b(B)),aoe=sA(),coe=",",uoe=["OTEL_SDK_DISABLED"];function loe(t){return uoe.indexOf(t)>-1}var doe=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function poe(t){return doe.indexOf(t)>-1}var _oe=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function foe(t){return _oe.indexOf(t)>-1}Ve.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;Ve.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128;Ve.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT=128;Ve.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT=128;Ve.DEFAULT_ENVIRONMENT={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:vs.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ve.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,OTEL_ATTRIBUTE_COUNT_LIMIT:Ve.DEFAULT_ATTRIBUTE_COUNT_LIMIT,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ve.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Ve.DEFAULT_ATTRIBUTE_COUNT_LIMIT,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ve.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Ve.DEFAULT_ATTRIBUTE_COUNT_LIMIT,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Ve.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ve.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:aoe.TracesSamplerValues.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function moe(t,e,n){if(typeof n[t]>"u")return;let r=String(n[t]);e[t]=r.toLowerCase()==="true"}function Eoe(t,e,n,r=-1/0,o=1/0){if(typeof n[t]<"u"){let s=Number(n[t]);isNaN(s)||(s<r?e[t]=r:s>o?e[t]=o:e[t]=s)}}function Soe(t,e,n,r=coe){let o=n[t];typeof o=="string"&&(e[t]=o.split(r).map(s=>s.trim()))}var goe={ALL:vs.DiagLogLevel.ALL,VERBOSE:vs.DiagLogLevel.VERBOSE,DEBUG:vs.DiagLogLevel.DEBUG,INFO:vs.DiagLogLevel.INFO,WARN:vs.DiagLogLevel.WARN,ERROR:vs.DiagLogLevel.ERROR,NONE:vs.DiagLogLevel.NONE};function hoe(t,e,n){let r=n[t];if(typeof r=="string"){let o=goe[r.toUpperCase()];o!=null&&(e[t]=o)}}function Toe(t){let e={};for(let n in Ve.DEFAULT_ENVIRONMENT){let r=n;switch(r){case"OTEL_LOG_LEVEL":hoe(r,e,t);break;default:if(loe(r))moe(r,e,t);else if(poe(r))Eoe(r,e,t);else if(foe(r))Soe(r,e,t);else{let o=t[r];typeof o<"u"&&o!==null&&(e[r]=String(o))}}}return e}Ve.parseEnvironment=Toe});var lM=m(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.getEnvWithoutDefaults=lc.getEnv=void 0;var aA=iA();function Aoe(){let t=(0,aA.parseEnvironment)(process.env);return Object.assign({},aA.DEFAULT_ENVIRONMENT,t)}lc.getEnv=Aoe;function Roe(){return(0,aA.parseEnvironment)(process.env)}lc.getEnvWithoutDefaults=Roe});var dM=m(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});sf._globalThis=void 0;sf._globalThis=typeof globalThis=="object"?globalThis:global});var cA=m(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.hexToBinary=void 0;function pM(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function yoe(t){let e=new Uint8Array(t.length/2),n=0;for(let r=0;r<t.length;r+=2){let o=pM(t.charCodeAt(r)),s=pM(t.charCodeAt(r+1));e[n++]=o<<4|s}return e}af.hexToBinary=yoe});var _M=m(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});cf.hexToBase64=void 0;var Ooe=cA();function Noe(t){return Buffer.from((0,Ooe.hexToBinary)(t)).toString("base64")}cf.hexToBase64=Noe});var EM=m(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});lf.RandomIdGenerator=void 0;var Coe=8,mM=16,uA=class{constructor(){this.generateTraceId=fM(mM),this.generateSpanId=fM(Coe)}};lf.RandomIdGenerator=uA;var uf=Buffer.allocUnsafe(mM);function fM(t){return function(){for(let n=0;n<t/4;n++)uf.writeUInt32BE(Math.random()*2**32>>>0,n*4);for(let n=0;n<t&&!(uf[n]>0);n++)n===t-1&&(uf[t-1]=1);return uf.toString("hex",0,t)}}});var SM=m(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.otperformance=void 0;var voe=require("perf_hooks");df.otperformance=voe.performance});var lA=m(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});pf.VERSION=void 0;pf.VERSION="1.30.1"});function Qe(t){for(var e={},n=t.length,r=0;r<n;r++){var o=t[r];o&&(e[String(o).toUpperCase().replace(/[-.]/g,"_")]=o)}return e}var dA=$(()=>{});var gM,hM,TM,AM,RM,yM,OM,NM,CM,vM,IM,PM,bM,MM,LM,xM,DM,UM,wM,kM,VM,BM,GM,HM,$M,FM,jM,qM,YM,KM,WM,zM,XM,JM,ZM,QM,eL,tL,nL,rL,oL,sL,iL,aL,cL,uL,lL,dL,pL,_L,fL,mL,EL,SL,gL,hL,TL,AL,RL,yL,OL,NL,CL,vL,IL,PL,bL,ML,LL,xL,DL,UL,wL,kL,VL,BL,GL,HL,$L,FL,jL,qL,YL,KL,WL,zL,XL,JL,ZL,QL,ex,tx,nx,rx,ox,sx,ix,ax,cx,ux,lx,dx,px,_x,fx,mx,Ex,Sx,gx,hx,Tx,Ax,Rx,yx,Ox,Nx,Cx,vx,Ix,Px,bx,Mx,Lx,xx,Dx,Ux,wx,kx,Ioe,Poe,boe,Moe,Loe,xoe,Doe,Uoe,woe,koe,Voe,Boe,Goe,Hoe,$oe,Foe,joe,qoe,Yoe,Koe,Woe,zoe,Xoe,Joe,Zoe,Qoe,ese,tse,nse,rse,ose,sse,ise,ase,cse,use,lse,dse,pse,_se,fse,mse,Ese,Sse,gse,hse,Tse,Ase,Rse,yse,Ose,Nse,Cse,vse,Ise,Pse,bse,Mse,Lse,xse,Dse,Use,wse,kse,Vse,Bse,Gse,Hse,$se,Fse,jse,qse,Yse,Kse,Wse,zse,Xse,Jse,Zse,Qse,eie,tie,nie,rie,oie,sie,iie,aie,cie,uie,lie,die,pie,_ie,fie,mie,Eie,Sie,gie,hie,Tie,Aie,Rie,yie,Oie,Nie,Cie,vie,Iie,Pie,bie,Mie,Lie,xie,Die,Uie,wie,kie,Vie,Bie,Gie,Hie,$ie,Fie,jie,qie,Yie,Kie,Wie,Vx,Bx,Gx,Hx,$x,Fx,jx,qx,Yx,Kx,Wx,zx,Xx,Jx,Zx,Qx,e0,t0,n0,r0,o0,s0,i0,a0,c0,u0,l0,d0,p0,_0,f0,m0,E0,S0,g0,h0,T0,A0,R0,y0,O0,N0,C0,v0,I0,P0,b0,zie,Xie,Jie,Zie,Qie,eae,tae,nae,rae,oae,sae,iae,aae,cae,uae,lae,dae,pae,_ae,fae,mae,Eae,Sae,gae,hae,Tae,Aae,Rae,yae,Oae,Nae,Cae,vae,Iae,Pae,bae,Mae,Lae,xae,Dae,Uae,wae,kae,Vae,Bae,Gae,Hae,$ae,M0,L0,x0,D0,U0,w0,k0,V0,B0,G0,H0,Fae,jae,qae,Yae,Kae,Wae,zae,Xae,Jae,Zae,Qae,ece,$0,F0,j0,q0,Y0,tce,nce,rce,oce,sce,ice,K0,W0,z0,ace,cce,uce,lce,X0,J0,Z0,Q0,dce,pce,_ce,fce,mce,eD,tD,nD,rD,oD,sD,iD,Ece,Sce,gce,hce,Tce,Ace,Rce,yce,aD,cD,uD,lD,dD,Oce,Nce,Cce,vce,Ice,Pce,pD,_D,fD,mD,ED,SD,gD,hD,TD,AD,RD,yD,OD,ND,CD,vD,ID,PD,bD,MD,LD,bce,Mce,Lce,xce,Dce,Uce,wce,kce,Vce,Bce,Gce,Hce,$ce,Fce,jce,qce,Yce,Kce,Wce,zce,Xce,Jce,xD,DD,UD,wD,kD,Zce,Qce,eue,tue,nue,rue,VD,BD,oue,sue,iue,GD,HD,aue,cue,uue,$D,FD,jD,qD,YD,KD,WD,zD,XD,JD,ZD,QD,eU,tU,nU,rU,oU,lue,due,pue,_ue,fue,mue,Eue,Sue,gue,hue,Tue,Aue,Rue,yue,Oue,Nue,Cue,vue,sU,iU,Iue,Pue,bue,aU=$(()=>{dA();gM="aws.lambda.invoked_arn",hM="db.system",TM="db.connection_string",AM="db.user",RM="db.jdbc.driver_classname",yM="db.name",OM="db.statement",NM="db.operation",CM="db.mssql.instance_name",vM="db.cassandra.keyspace",IM="db.cassandra.page_size",PM="db.cassandra.consistency_level",bM="db.cassandra.table",MM="db.cassandra.idempotence",LM="db.cassandra.speculative_execution_count",xM="db.cassandra.coordinator.id",DM="db.cassandra.coordinator.dc",UM="db.hbase.namespace",wM="db.redis.database_index",kM="db.mongodb.collection",VM="db.sql.table",BM="exception.type",GM="exception.message",HM="exception.stacktrace",$M="exception.escaped",FM="faas.trigger",jM="faas.execution",qM="faas.document.collection",YM="faas.document.operation",KM="faas.document.time",WM="faas.document.name",zM="faas.time",XM="faas.cron",JM="faas.coldstart",ZM="faas.invoked_name",QM="faas.invoked_provider",eL="faas.invoked_region",tL="net.transport",nL="net.peer.ip",rL="net.peer.port",oL="net.peer.name",sL="net.host.ip",iL="net.host.port",aL="net.host.name",cL="net.host.connection.type",uL="net.host.connection.subtype",lL="net.host.carrier.name",dL="net.host.carrier.mcc",pL="net.host.carrier.mnc",_L="net.host.carrier.icc",fL="peer.service",mL="enduser.id",EL="enduser.role",SL="enduser.scope",gL="thread.id",hL="thread.name",TL="code.function",AL="code.namespace",RL="code.filepath",yL="code.lineno",OL="http.method",NL="http.url",CL="http.target",vL="http.host",IL="http.scheme",PL="http.status_code",bL="http.flavor",ML="http.user_agent",LL="http.request_content_length",xL="http.request_content_length_uncompressed",DL="http.response_content_length",UL="http.response_content_length_uncompressed",wL="http.server_name",kL="http.route",VL="http.client_ip",BL="aws.dynamodb.table_names",GL="aws.dynamodb.consumed_capacity",HL="aws.dynamodb.item_collection_metrics",$L="aws.dynamodb.provisioned_read_capacity",FL="aws.dynamodb.provisioned_write_capacity",jL="aws.dynamodb.consistent_read",qL="aws.dynamodb.projection",YL="aws.dynamodb.limit",KL="aws.dynamodb.attributes_to_get",WL="aws.dynamodb.index_name",zL="aws.dynamodb.select",XL="aws.dynamodb.global_secondary_indexes",JL="aws.dynamodb.local_secondary_indexes",ZL="aws.dynamodb.exclusive_start_table",QL="aws.dynamodb.table_count",ex="aws.dynamodb.scan_forward",tx="aws.dynamodb.segment",nx="aws.dynamodb.total_segments",rx="aws.dynamodb.count",ox="aws.dynamodb.scanned_count",sx="aws.dynamodb.attribute_definitions",ix="aws.dynamodb.global_secondary_index_updates",ax="messaging.system",cx="messaging.destination",ux="messaging.destination_kind",lx="messaging.temp_destination",dx="messaging.protocol",px="messaging.protocol_version",_x="messaging.url",fx="messaging.message_id",mx="messaging.conversation_id",Ex="messaging.message_payload_size_bytes",Sx="messaging.message_payload_compressed_size_bytes",gx="messaging.operation",hx="messaging.consumer_id",Tx="messaging.rabbitmq.routing_key",Ax="messaging.kafka.message_key",Rx="messaging.kafka.consumer_group",yx="messaging.kafka.client_id",Ox="messaging.kafka.partition",Nx="messaging.kafka.tombstone",Cx="rpc.system",vx="rpc.service",Ix="rpc.method",Px="rpc.grpc.status_code",bx="rpc.jsonrpc.version",Mx="rpc.jsonrpc.request_id",Lx="rpc.jsonrpc.error_code",xx="rpc.jsonrpc.error_message",Dx="message.type",Ux="message.id",wx="message.compressed_size",kx="message.uncompressed_size",Ioe=gM,Poe=hM,boe=TM,Moe=AM,Loe=RM,xoe=yM,Doe=OM,Uoe=NM,woe=CM,koe=vM,Voe=IM,Boe=PM,Goe=bM,Hoe=MM,$oe=LM,Foe=xM,joe=DM,qoe=UM,Yoe=wM,Koe=kM,Woe=VM,zoe=BM,Xoe=GM,Joe=HM,Zoe=$M,Qoe=FM,ese=jM,tse=qM,nse=YM,rse=KM,ose=WM,sse=zM,ise=XM,ase=JM,cse=ZM,use=QM,lse=eL,dse=tL,pse=nL,_se=rL,fse=oL,mse=sL,Ese=iL,Sse=aL,gse=cL,hse=uL,Tse=lL,Ase=dL,Rse=pL,yse=_L,Ose=fL,Nse=mL,Cse=EL,vse=SL,Ise=gL,Pse=hL,bse=TL,Mse=AL,Lse=RL,xse=yL,Dse=OL,Use=NL,wse=CL,kse=vL,Vse=IL,Bse=PL,Gse=bL,Hse=ML,$se=LL,Fse=xL,jse=DL,qse=UL,Yse=wL,Kse=kL,Wse=VL,zse=BL,Xse=GL,Jse=HL,Zse=$L,Qse=FL,eie=jL,tie=qL,nie=YL,rie=KL,oie=WL,sie=zL,iie=XL,aie=JL,cie=ZL,uie=QL,lie=ex,die=tx,pie=nx,_ie=rx,fie=ox,mie=sx,Eie=ix,Sie=ax,gie=cx,hie=ux,Tie=lx,Aie=dx,Rie=px,yie=_x,Oie=fx,Nie=mx,Cie=Ex,vie=Sx,Iie=gx,Pie=hx,bie=Tx,Mie=Ax,Lie=Rx,xie=yx,Die=Ox,Uie=Nx,wie=Cx,kie=vx,Vie=Ix,Bie=Px,Gie=bx,Hie=Mx,$ie=Lx,Fie=xx,jie=Dx,qie=Ux,Yie=wx,Kie=kx,Wie=Qe([gM,hM,TM,AM,RM,yM,OM,NM,CM,vM,IM,PM,bM,MM,LM,xM,DM,UM,wM,kM,VM,BM,GM,HM,$M,FM,jM,qM,YM,KM,WM,zM,XM,JM,ZM,QM,eL,tL,nL,rL,oL,sL,iL,aL,cL,uL,lL,dL,pL,_L,fL,mL,EL,SL,gL,hL,TL,AL,RL,yL,OL,NL,CL,vL,IL,PL,bL,ML,LL,xL,DL,UL,wL,kL,VL,BL,GL,HL,$L,FL,jL,qL,YL,KL,WL,zL,XL,JL,ZL,QL,ex,tx,nx,rx,ox,sx,ix,ax,cx,ux,lx,dx,px,_x,fx,mx,Ex,Sx,gx,hx,Tx,Ax,Rx,yx,Ox,Nx,Cx,vx,Ix,Px,bx,Mx,Lx,xx,Dx,Ux,wx,kx]),Vx="other_sql",Bx="mssql",Gx="mysql",Hx="oracle",$x="db2",Fx="postgresql",jx="redshift",qx="hive",Yx="cloudscape",Kx="hsqldb",Wx="progress",zx="maxdb",Xx="hanadb",Jx="ingres",Zx="firstsql",Qx="edb",e0="cache",t0="adabas",n0="firebird",r0="derby",o0="filemaker",s0="informix",i0="instantdb",a0="interbase",c0="mariadb",u0="netezza",l0="pervasive",d0="pointbase",p0="sqlite",_0="sybase",f0="teradata",m0="vertica",E0="h2",S0="coldfusion",g0="cassandra",h0="hbase",T0="mongodb",A0="redis",R0="couchbase",y0="couchdb",O0="cosmosdb",N0="dynamodb",C0="neo4j",v0="geode",I0="elasticsearch",P0="memcached",b0="cockroachdb",zie=Vx,Xie=Bx,Jie=Gx,Zie=Hx,Qie=$x,eae=Fx,tae=jx,nae=qx,rae=Yx,oae=Kx,sae=Wx,iae=zx,aae=Xx,cae=Jx,uae=Zx,lae=Qx,dae=e0,pae=t0,_ae=n0,fae=r0,mae=o0,Eae=s0,Sae=i0,gae=a0,hae=c0,Tae=u0,Aae=l0,Rae=d0,yae=p0,Oae=_0,Nae=f0,Cae=m0,vae=E0,Iae=S0,Pae=g0,bae=h0,Mae=T0,Lae=A0,xae=R0,Dae=y0,Uae=O0,wae=N0,kae=C0,Vae=v0,Bae=I0,Gae=P0,Hae=b0,$ae=Qe([Vx,Bx,Gx,Hx,$x,Fx,jx,qx,Yx,Kx,Wx,zx,Xx,Jx,Zx,Qx,e0,t0,n0,r0,o0,s0,i0,a0,c0,u0,l0,d0,p0,_0,f0,m0,E0,S0,g0,h0,T0,A0,R0,y0,O0,N0,C0,v0,I0,P0,b0]),M0="all",L0="each_quorum",x0="quorum",D0="local_quorum",U0="one",w0="two",k0="three",V0="local_one",B0="any",G0="serial",H0="local_serial",Fae=M0,jae=L0,qae=x0,Yae=D0,Kae=U0,Wae=w0,zae=k0,Xae=V0,Jae=B0,Zae=G0,Qae=H0,ece=Qe([M0,L0,x0,D0,U0,w0,k0,V0,B0,G0,H0]),$0="datasource",F0="http",j0="pubsub",q0="timer",Y0="other",tce=$0,nce=F0,rce=j0,oce=q0,sce=Y0,ice=Qe([$0,F0,j0,q0,Y0]),K0="insert",W0="edit",z0="delete",ace=K0,cce=W0,uce=z0,lce=Qe([K0,W0,z0]),X0="alibaba_cloud",J0="aws",Z0="azure",Q0="gcp",dce=X0,pce=J0,_ce=Z0,fce=Q0,mce=Qe([X0,J0,Z0,Q0]),eD="ip_tcp",tD="ip_udp",nD="ip",rD="unix",oD="pipe",sD="inproc",iD="other",Ece=eD,Sce=tD,gce=nD,hce=rD,Tce=oD,Ace=sD,Rce=iD,yce=Qe([eD,tD,nD,rD,oD,sD,iD]),aD="wifi",cD="wired",uD="cell",lD="unavailable",dD="unknown",Oce=aD,Nce=cD,Cce=uD,vce=lD,Ice=dD,Pce=Qe([aD,cD,uD,lD,dD]),pD="gprs",_D="edge",fD="umts",mD="cdma",ED="evdo_0",SD="evdo_a",gD="cdma2000_1xrtt",hD="hsdpa",TD="hsupa",AD="hspa",RD="iden",yD="evdo_b",OD="lte",ND="ehrpd",CD="hspap",vD="gsm",ID="td_scdma",PD="iwlan",bD="nr",MD="nrnsa",LD="lte_ca",bce=pD,Mce=_D,Lce=fD,xce=mD,Dce=ED,Uce=SD,wce=gD,kce=hD,Vce=TD,Bce=AD,Gce=RD,Hce=yD,$ce=OD,Fce=ND,jce=CD,qce=vD,Yce=ID,Kce=PD,Wce=bD,zce=MD,Xce=LD,Jce=Qe([pD,_D,fD,mD,ED,SD,gD,hD,TD,AD,RD,yD,OD,ND,CD,vD,ID,PD,bD,MD,LD]),xD="1.0",DD="1.1",UD="2.0",wD="SPDY",kD="QUIC",Zce=xD,Qce=DD,eue=UD,tue=wD,nue=kD,rue={HTTP_1_0:xD,HTTP_1_1:DD,HTTP_2_0:UD,SPDY:wD,QUIC:kD},VD="queue",BD="topic",oue=VD,sue=BD,iue=Qe([VD,BD]),GD="receive",HD="process",aue=GD,cue=HD,uue=Qe([GD,HD]),$D=0,FD=1,jD=2,qD=3,YD=4,KD=5,WD=6,zD=7,XD=8,JD=9,ZD=10,QD=11,eU=12,tU=13,nU=14,rU=15,oU=16,lue=$D,due=FD,pue=jD,_ue=qD,fue=YD,mue=KD,Eue=WD,Sue=zD,gue=XD,hue=JD,Tue=ZD,Aue=QD,Rue=eU,yue=tU,Oue=nU,Nue=rU,Cue=oU,vue={OK:$D,CANCELLED:FD,UNKNOWN:jD,INVALID_ARGUMENT:qD,DEADLINE_EXCEEDED:YD,NOT_FOUND:KD,ALREADY_EXISTS:WD,PERMISSION_DENIED:zD,RESOURCE_EXHAUSTED:XD,FAILED_PRECONDITION:JD,ABORTED:ZD,OUT_OF_RANGE:QD,UNIMPLEMENTED:eU,INTERNAL:tU,UNAVAILABLE:nU,DATA_LOSS:rU,UNAUTHENTICATED:oU},sU="SENT",iU="RECEIVED",Iue=sU,Pue=iU,bue=Qe([sU,iU])});var cU=$(()=>{aU()});var uU,lU,dU,pU,_U,fU,mU,EU,SU,gU,hU,TU,AU,RU,yU,OU,NU,CU,vU,IU,PU,bU,MU,LU,xU,DU,UU,wU,kU,VU,BU,GU,HU,$U,FU,jU,qU,YU,KU,WU,zU,XU,JU,ZU,QU,ew,tw,nw,rw,ow,sw,iw,aw,cw,uw,lw,dw,pw,_w,fw,mw,Ew,Sw,gw,hw,Tw,Aw,Rw,yw,Ow,Nw,Cw,vw,Iw,Pw,bw,Mw,Lw,xw,Dw,Uw,Mue,Lue,xue,Due,Uue,wue,kue,Vue,Bue,Gue,Hue,$ue,Fue,jue,que,Yue,Kue,Wue,zue,Xue,Jue,Zue,Que,ele,tle,nle,rle,ole,sle,ile,ale,cle,ule,lle,dle,ple,_le,fle,mle,Ele,Sle,gle,hle,Tle,Ale,Rle,yle,Ole,Nle,Cle,vle,Ile,Ple,ble,Mle,Lle,xle,Dle,Ule,wle,kle,Vle,Ble,Gle,Hle,$le,Fle,jle,qle,Yle,Kle,Wle,zle,Xle,Jle,Zle,Qle,ede,tde,nde,rde,ode,ww,kw,Vw,Bw,sde,ide,ade,cde,ude,Gw,Hw,$w,Fw,jw,qw,Yw,Kw,Ww,zw,Xw,Jw,Zw,Qw,e1,t1,n1,lde,dde,pde,_de,fde,mde,Ede,Sde,gde,hde,Tde,Ade,Rde,yde,Ode,Nde,Cde,vde,r1,o1,Ide,Pde,bde,s1,i1,a1,c1,u1,l1,d1,Mde,Lde,xde,Dde,Ude,wde,kde,Vde,p1,_1,f1,m1,E1,S1,g1,h1,T1,A1,R1,Bde,Gde,Hde,$de,Fde,jde,qde,Yde,Kde,Wde,zde,Xde,y1,O1,N1,C1,v1,I1,P1,b1,M1,L1,Jde,Zde,Qde,epe,tpe,npe,rpe,ope,spe,ipe,ape,x1=$(()=>{dA();uU="cloud.provider",lU="cloud.account.id",dU="cloud.region",pU="cloud.availability_zone",_U="cloud.platform",fU="aws.ecs.container.arn",mU="aws.ecs.cluster.arn",EU="aws.ecs.launchtype",SU="aws.ecs.task.arn",gU="aws.ecs.task.family",hU="aws.ecs.task.revision",TU="aws.eks.cluster.arn",AU="aws.log.group.names",RU="aws.log.group.arns",yU="aws.log.stream.names",OU="aws.log.stream.arns",NU="container.name",CU="container.id",vU="container.runtime",IU="container.image.name",PU="container.image.tag",bU="deployment.environment",MU="device.id",LU="device.model.identifier",xU="device.model.name",DU="faas.name",UU="faas.id",wU="faas.version",kU="faas.instance",VU="faas.max_memory",BU="host.id",GU="host.name",HU="host.type",$U="host.arch",FU="host.image.name",jU="host.image.id",qU="host.image.version",YU="k8s.cluster.name",KU="k8s.node.name",WU="k8s.node.uid",zU="k8s.namespace.name",XU="k8s.pod.uid",JU="k8s.pod.name",ZU="k8s.container.name",QU="k8s.replicaset.uid",ew="k8s.replicaset.name",tw="k8s.deployment.uid",nw="k8s.deployment.name",rw="k8s.statefulset.uid",ow="k8s.statefulset.name",sw="k8s.daemonset.uid",iw="k8s.daemonset.name",aw="k8s.job.uid",cw="k8s.job.name",uw="k8s.cronjob.uid",lw="k8s.cronjob.name",dw="os.type",pw="os.description",_w="os.name",fw="os.version",mw="process.pid",Ew="process.executable.name",Sw="process.executable.path",gw="process.command",hw="process.command_line",Tw="process.command_args",Aw="process.owner",Rw="process.runtime.name",yw="process.runtime.version",Ow="process.runtime.description",Nw="service.name",Cw="service.namespace",vw="service.instance.id",Iw="service.version",Pw="telemetry.sdk.name",bw="telemetry.sdk.language",Mw="telemetry.sdk.version",Lw="telemetry.auto.version",xw="webengine.name",Dw="webengine.version",Uw="webengine.description",Mue=uU,Lue=lU,xue=dU,Due=pU,Uue=_U,wue=fU,kue=mU,Vue=EU,Bue=SU,Gue=gU,Hue=hU,$ue=TU,Fue=AU,jue=RU,que=yU,Yue=OU,Kue=NU,Wue=CU,zue=vU,Xue=IU,Jue=PU,Zue=bU,Que=MU,ele=LU,tle=xU,nle=DU,rle=UU,ole=wU,sle=kU,ile=VU,ale=BU,cle=GU,ule=HU,lle=$U,dle=FU,ple=jU,_le=qU,fle=YU,mle=KU,Ele=WU,Sle=zU,gle=XU,hle=JU,Tle=ZU,Ale=QU,Rle=ew,yle=tw,Ole=nw,Nle=rw,Cle=ow,vle=sw,Ile=iw,Ple=aw,ble=cw,Mle=uw,Lle=lw,xle=dw,Dle=pw,Ule=_w,wle=fw,kle=mw,Vle=Ew,Ble=Sw,Gle=gw,Hle=hw,$le=Tw,Fle=Aw,jle=Rw,qle=yw,Yle=Ow,Kle=Nw,Wle=Cw,zle=vw,Xle=Iw,Jle=Pw,Zle=bw,Qle=Mw,ede=Lw,tde=xw,nde=Dw,rde=Uw,ode=Qe([uU,lU,dU,pU,_U,fU,mU,EU,SU,gU,hU,TU,AU,RU,yU,OU,NU,CU,vU,IU,PU,bU,MU,LU,xU,DU,UU,wU,kU,VU,BU,GU,HU,$U,FU,jU,qU,YU,KU,WU,zU,XU,JU,ZU,QU,ew,tw,nw,rw,ow,sw,iw,aw,cw,uw,lw,dw,pw,_w,fw,mw,Ew,Sw,gw,hw,Tw,Aw,Rw,yw,Ow,Nw,Cw,vw,Iw,Pw,bw,Mw,Lw,xw,Dw,Uw]),ww="alibaba_cloud",kw="aws",Vw="azure",Bw="gcp",sde=ww,ide=kw,ade=Vw,cde=Bw,ude=Qe([ww,kw,Vw,Bw]),Gw="alibaba_cloud_ecs",Hw="alibaba_cloud_fc",$w="aws_ec2",Fw="aws_ecs",jw="aws_eks",qw="aws_lambda",Yw="aws_elastic_beanstalk",Kw="azure_vm",Ww="azure_container_instances",zw="azure_aks",Xw="azure_functions",Jw="azure_app_service",Zw="gcp_compute_engine",Qw="gcp_cloud_run",e1="gcp_kubernetes_engine",t1="gcp_cloud_functions",n1="gcp_app_engine",lde=Gw,dde=Hw,pde=$w,_de=Fw,fde=jw,mde=qw,Ede=Yw,Sde=Kw,gde=Ww,hde=zw,Tde=Xw,Ade=Jw,Rde=Zw,yde=Qw,Ode=e1,Nde=t1,Cde=n1,vde=Qe([Gw,Hw,$w,Fw,jw,qw,Yw,Kw,Ww,zw,Xw,Jw,Zw,Qw,e1,t1,n1]),r1="ec2",o1="fargate",Ide=r1,Pde=o1,bde=Qe([r1,o1]),s1="amd64",i1="arm32",a1="arm64",c1="ia64",u1="ppc32",l1="ppc64",d1="x86",Mde=s1,Lde=i1,xde=a1,Dde=c1,Ude=u1,wde=l1,kde=d1,Vde=Qe([s1,i1,a1,c1,u1,l1,d1]),p1="windows",_1="linux",f1="darwin",m1="freebsd",E1="netbsd",S1="openbsd",g1="dragonflybsd",h1="hpux",T1="aix",A1="solaris",R1="z_os",Bde=p1,Gde=_1,Hde=f1,$de=m1,Fde=E1,jde=S1,qde=g1,Yde=h1,Kde=T1,Wde=A1,zde=R1,Xde=Qe([p1,_1,f1,m1,E1,S1,g1,h1,T1,A1,R1]),y1="cpp",O1="dotnet",N1="erlang",C1="go",v1="java",I1="nodejs",P1="php",b1="python",M1="ruby",L1="webjs",Jde=y1,Zde=O1,Qde=N1,epe=C1,tpe=v1,npe=I1,rpe=P1,ope=b1,spe=M1,ipe=L1,ape=Qe([y1,O1,N1,C1,v1,I1,P1,b1,M1,L1])});var D1=$(()=>{x1()});var cpe,upe,lpe,dpe,ppe,_pe,fpe,mpe,Epe,Spe,gpe,hpe,Tpe,Ape,Rpe,ype,Ope,Npe,Cpe,vpe,Ipe,Ppe,bpe,Mpe,Lpe,xpe,Dpe,Upe,wpe,kpe,Vpe,Bpe,Gpe,Hpe,$pe,Fpe,jpe,qpe,Ype,Kpe,Wpe,zpe,Xpe,Jpe,Zpe,Qpe,e_e,t_e,n_e,r_e,o_e,s_e,i_e,a_e,c_e,u_e,l_e,d_e,p_e,__e,f_e,m_e,E_e,S_e,g_e,h_e,T_e,A_e,R_e,y_e,O_e,N_e,C_e,v_e,I_e,P_e,b_e,M_e,L_e,x_e,D_e,U_e,w_e,k_e,V_e,B_e,G_e,H_e,$_e,F_e,j_e,q_e,Y_e,K_e,W_e,z_e,X_e,J_e,Z_e,Q_e,efe,tfe,nfe,rfe,ofe,sfe,ife,afe,cfe,ufe,U1=$(()=>{cpe="aspnetcore.rate_limiting.result",upe="acquired",lpe="endpoint_limiter",dpe="global_limiter",ppe="request_canceled",_pe="telemetry.sdk.language",fpe="cpp",mpe="dotnet",Epe="erlang",Spe="go",gpe="java",hpe="nodejs",Tpe="php",Ape="python",Rpe="ruby",ype="rust",Ope="swift",Npe="webjs",Cpe="telemetry.sdk.name",vpe="telemetry.sdk.version",Ipe="aspnetcore.diagnostics.handler.type",Ppe="aspnetcore.diagnostics.exception.result",bpe="aborted",Mpe="handled",Lpe="skipped",xpe="unhandled",Dpe="aspnetcore.rate_limiting.policy",Upe="aspnetcore.request.is_unhandled",wpe="aspnetcore.routing.is_fallback",kpe="aspnetcore.routing.match_status",Vpe="failure",Bpe="success",Gpe="client.address",Hpe="client.port",$pe="error.type",Fpe="_OTHER",jpe="exception.escaped",qpe="exception.message",Ype="exception.stacktrace",Kpe="exception.type",Wpe=function(t){return"http.request.header."+t},zpe="http.request.method",Xpe="_OTHER",Jpe="CONNECT",Zpe="DELETE",Qpe="GET",e_e="HEAD",t_e="OPTIONS",n_e="PATCH",r_e="POST",o_e="PUT",s_e="TRACE",i_e="http.request.method_original",a_e="http.request.resend_count",c_e=function(t){return"http.response.header."+t},u_e="http.response.status_code",l_e="http.route",d_e="jvm.gc.action",p_e="jvm.gc.name",__e="jvm.memory.pool.name",f_e="jvm.memory.type",m_e="heap",E_e="non_heap",S_e="jvm.thread.daemon",g_e="jvm.thread.state",h_e="blocked",T_e="new",A_e="runnable",R_e="terminated",y_e="timed_waiting",O_e="waiting",N_e="network.local.address",C_e="network.local.port",v_e="network.peer.address",I_e="network.peer.port",P_e="network.protocol.name",b_e="network.protocol.version",M_e="network.transport",L_e="pipe",x_e="quic",D_e="tcp",U_e="udp",w_e="unix",k_e="network.type",V_e="ipv4",B_e="ipv6",G_e="otel.scope.name",H_e="otel.scope.version",$_e="otel.status_code",F_e="ERROR",j_e="OK",q_e="otel.status_description",Y_e="server.address",K_e="server.port",W_e="service.name",z_e="service.version",X_e="signalr.connection.status",J_e="app_shutdown",Z_e="normal_closure",Q_e="timeout",efe="signalr.transport",tfe="long_polling",nfe="server_sent_events",rfe="web_sockets",ofe="url.fragment",sfe="url.full",ife="url.path",afe="url.query",cfe="url.scheme",ufe="user_agent.original"});var lfe,dfe,pfe,_fe,ffe,mfe,Efe,Sfe,gfe,hfe,Tfe,Afe,Rfe,yfe,Ofe,Nfe,Cfe,vfe,Ife,Pfe,bfe,Mfe,Lfe,xfe,Dfe,Ufe,wfe,kfe,Vfe,Bfe,Gfe,w1=$(()=>{lfe="aspnetcore.diagnostics.exceptions",dfe="aspnetcore.rate_limiting.active_request_leases",pfe="aspnetcore.rate_limiting.queued_requests",_fe="aspnetcore.rate_limiting.request.time_in_queue",ffe="aspnetcore.rate_limiting.request_lease.duration",mfe="aspnetcore.rate_limiting.requests",Efe="aspnetcore.routing.match_attempts",Sfe="http.client.request.duration",gfe="http.server.request.duration",hfe="jvm.class.count",Tfe="jvm.class.loaded",Afe="jvm.class.unloaded",Rfe="jvm.cpu.count",yfe="jvm.cpu.recent_utilization",Ofe="jvm.cpu.time",Nfe="jvm.gc.duration",Cfe="jvm.memory.committed",vfe="jvm.memory.limit",Ife="jvm.memory.used",Pfe="jvm.memory.used_after_last_gc",bfe="jvm.thread.count",Mfe="kestrel.active_connections",Lfe="kestrel.active_tls_handshakes",xfe="kestrel.connection.duration",Dfe="kestrel.queued_connections",Ufe="kestrel.queued_requests",wfe="kestrel.rejected_connections",kfe="kestrel.tls_handshake.duration",Vfe="kestrel.upgraded_connections",Bfe="signalr.server.active_connections",Gfe="signalr.server.connection.duration"});var Wn={};Lp(Wn,{ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>bpe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>Mpe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>Lpe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>xpe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>upe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>lpe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>dpe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ppe,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>Vpe,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>Bpe,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>Ppe,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>Ipe,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>Dpe,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>cpe,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>Upe,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>wpe,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>kpe,ATTR_CLIENT_ADDRESS:()=>Gpe,ATTR_CLIENT_PORT:()=>Hpe,ATTR_ERROR_TYPE:()=>$pe,ATTR_EXCEPTION_ESCAPED:()=>jpe,ATTR_EXCEPTION_MESSAGE:()=>qpe,ATTR_EXCEPTION_STACKTRACE:()=>Ype,ATTR_EXCEPTION_TYPE:()=>Kpe,ATTR_HTTP_REQUEST_HEADER:()=>Wpe,ATTR_HTTP_REQUEST_METHOD:()=>zpe,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>i_e,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>a_e,ATTR_HTTP_RESPONSE_HEADER:()=>c_e,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>u_e,ATTR_HTTP_ROUTE:()=>l_e,ATTR_JVM_GC_ACTION:()=>d_e,ATTR_JVM_GC_NAME:()=>p_e,ATTR_JVM_MEMORY_POOL_NAME:()=>__e,ATTR_JVM_MEMORY_TYPE:()=>f_e,ATTR_JVM_THREAD_DAEMON:()=>S_e,ATTR_JVM_THREAD_STATE:()=>g_e,ATTR_NETWORK_LOCAL_ADDRESS:()=>N_e,ATTR_NETWORK_LOCAL_PORT:()=>C_e,ATTR_NETWORK_PEER_ADDRESS:()=>v_e,ATTR_NETWORK_PEER_PORT:()=>I_e,ATTR_NETWORK_PROTOCOL_NAME:()=>P_e,ATTR_NETWORK_PROTOCOL_VERSION:()=>b_e,ATTR_NETWORK_TRANSPORT:()=>M_e,ATTR_NETWORK_TYPE:()=>k_e,ATTR_OTEL_SCOPE_NAME:()=>G_e,ATTR_OTEL_SCOPE_VERSION:()=>H_e,ATTR_OTEL_STATUS_CODE:()=>$_e,ATTR_OTEL_STATUS_DESCRIPTION:()=>q_e,ATTR_SERVER_ADDRESS:()=>Y_e,ATTR_SERVER_PORT:()=>K_e,ATTR_SERVICE_NAME:()=>W_e,ATTR_SERVICE_VERSION:()=>z_e,ATTR_SIGNALR_CONNECTION_STATUS:()=>X_e,ATTR_SIGNALR_TRANSPORT:()=>efe,ATTR_TELEMETRY_SDK_LANGUAGE:()=>_pe,ATTR_TELEMETRY_SDK_NAME:()=>Cpe,ATTR_TELEMETRY_SDK_VERSION:()=>vpe,ATTR_URL_FRAGMENT:()=>ofe,ATTR_URL_FULL:()=>sfe,ATTR_URL_PATH:()=>ife,ATTR_URL_QUERY:()=>afe,ATTR_URL_SCHEME:()=>cfe,ATTR_USER_AGENT_ORIGINAL:()=>ufe,AWSECSLAUNCHTYPEVALUES_EC2:()=>Ide,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>Pde,AwsEcsLaunchtypeValues:()=>bde,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>lde,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>dde,CLOUDPLATFORMVALUES_AWS_EC2:()=>pde,CLOUDPLATFORMVALUES_AWS_ECS:()=>_de,CLOUDPLATFORMVALUES_AWS_EKS:()=>fde,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>Ede,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>mde,CLOUDPLATFORMVALUES_AZURE_AKS:()=>hde,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>Ade,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>gde,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>Tde,CLOUDPLATFORMVALUES_AZURE_VM:()=>Sde,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>Cde,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>Nde,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>yde,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>Rde,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>Ode,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>sde,CLOUDPROVIDERVALUES_AWS:()=>ide,CLOUDPROVIDERVALUES_AZURE:()=>ade,CLOUDPROVIDERVALUES_GCP:()=>cde,CloudPlatformValues:()=>vde,CloudProviderValues:()=>ude,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>Fae,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>Jae,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>jae,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>Xae,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>Yae,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>Qae,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>Kae,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>qae,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>Zae,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>zae,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>Wae,DBSYSTEMVALUES_ADABAS:()=>pae,DBSYSTEMVALUES_CACHE:()=>dae,DBSYSTEMVALUES_CASSANDRA:()=>Pae,DBSYSTEMVALUES_CLOUDSCAPE:()=>rae,DBSYSTEMVALUES_COCKROACHDB:()=>Hae,DBSYSTEMVALUES_COLDFUSION:()=>Iae,DBSYSTEMVALUES_COSMOSDB:()=>Uae,DBSYSTEMVALUES_COUCHBASE:()=>xae,DBSYSTEMVALUES_COUCHDB:()=>Dae,DBSYSTEMVALUES_DB2:()=>Qie,DBSYSTEMVALUES_DERBY:()=>fae,DBSYSTEMVALUES_DYNAMODB:()=>wae,DBSYSTEMVALUES_EDB:()=>lae,DBSYSTEMVALUES_ELASTICSEARCH:()=>Bae,DBSYSTEMVALUES_FILEMAKER:()=>mae,DBSYSTEMVALUES_FIREBIRD:()=>_ae,DBSYSTEMVALUES_FIRSTSQL:()=>uae,DBSYSTEMVALUES_GEODE:()=>Vae,DBSYSTEMVALUES_H2:()=>vae,DBSYSTEMVALUES_HANADB:()=>aae,DBSYSTEMVALUES_HBASE:()=>bae,DBSYSTEMVALUES_HIVE:()=>nae,DBSYSTEMVALUES_HSQLDB:()=>oae,DBSYSTEMVALUES_INFORMIX:()=>Eae,DBSYSTEMVALUES_INGRES:()=>cae,DBSYSTEMVALUES_INSTANTDB:()=>Sae,DBSYSTEMVALUES_INTERBASE:()=>gae,DBSYSTEMVALUES_MARIADB:()=>hae,DBSYSTEMVALUES_MAXDB:()=>iae,DBSYSTEMVALUES_MEMCACHED:()=>Gae,DBSYSTEMVALUES_MONGODB:()=>Mae,DBSYSTEMVALUES_MSSQL:()=>Xie,DBSYSTEMVALUES_MYSQL:()=>Jie,DBSYSTEMVALUES_NEO4J:()=>kae,DBSYSTEMVALUES_NETEZZA:()=>Tae,DBSYSTEMVALUES_ORACLE:()=>Zie,DBSYSTEMVALUES_OTHER_SQL:()=>zie,DBSYSTEMVALUES_PERVASIVE:()=>Aae,DBSYSTEMVALUES_POINTBASE:()=>Rae,DBSYSTEMVALUES_POSTGRESQL:()=>eae,DBSYSTEMVALUES_PROGRESS:()=>sae,DBSYSTEMVALUES_REDIS:()=>Lae,DBSYSTEMVALUES_REDSHIFT:()=>tae,DBSYSTEMVALUES_SQLITE:()=>yae,DBSYSTEMVALUES_SYBASE:()=>Oae,DBSYSTEMVALUES_TERADATA:()=>Nae,DBSYSTEMVALUES_VERTICA:()=>Cae,DbCassandraConsistencyLevelValues:()=>ece,DbSystemValues:()=>$ae,ERROR_TYPE_VALUE_OTHER:()=>Fpe,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>uce,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>cce,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>ace,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>dce,FAASINVOKEDPROVIDERVALUES_AWS:()=>pce,FAASINVOKEDPROVIDERVALUES_AZURE:()=>_ce,FAASINVOKEDPROVIDERVALUES_GCP:()=>fce,FAASTRIGGERVALUES_DATASOURCE:()=>tce,FAASTRIGGERVALUES_HTTP:()=>nce,FAASTRIGGERVALUES_OTHER:()=>sce,FAASTRIGGERVALUES_PUBSUB:()=>rce,FAASTRIGGERVALUES_TIMER:()=>oce,FaasDocumentOperationValues:()=>lce,FaasInvokedProviderValues:()=>mce,FaasTriggerValues:()=>ice,HOSTARCHVALUES_AMD64:()=>Mde,HOSTARCHVALUES_ARM32:()=>Lde,HOSTARCHVALUES_ARM64:()=>xde,HOSTARCHVALUES_IA64:()=>Dde,HOSTARCHVALUES_PPC32:()=>Ude,HOSTARCHVALUES_PPC64:()=>wde,HOSTARCHVALUES_X86:()=>kde,HTTPFLAVORVALUES_HTTP_1_0:()=>Zce,HTTPFLAVORVALUES_HTTP_1_1:()=>Qce,HTTPFLAVORVALUES_HTTP_2_0:()=>eue,HTTPFLAVORVALUES_QUIC:()=>nue,HTTPFLAVORVALUES_SPDY:()=>tue,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>Jpe,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>Zpe,HTTP_REQUEST_METHOD_VALUE_GET:()=>Qpe,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>e_e,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>t_e,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>Xpe,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>n_e,HTTP_REQUEST_METHOD_VALUE_POST:()=>r_e,HTTP_REQUEST_METHOD_VALUE_PUT:()=>o_e,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>s_e,HostArchValues:()=>Vde,HttpFlavorValues:()=>rue,JVM_MEMORY_TYPE_VALUE_HEAP:()=>m_e,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>E_e,JVM_THREAD_STATE_VALUE_BLOCKED:()=>h_e,JVM_THREAD_STATE_VALUE_NEW:()=>T_e,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>A_e,JVM_THREAD_STATE_VALUE_TERMINATED:()=>R_e,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>y_e,JVM_THREAD_STATE_VALUE_WAITING:()=>O_e,MESSAGETYPEVALUES_RECEIVED:()=>Pue,MESSAGETYPEVALUES_SENT:()=>Iue,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>oue,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>sue,MESSAGINGOPERATIONVALUES_PROCESS:()=>cue,MESSAGINGOPERATIONVALUES_RECEIVE:()=>aue,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>lfe,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>dfe,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>pfe,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>mfe,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>ffe,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>_fe,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>Efe,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>Sfe,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>gfe,METRIC_JVM_CLASS_COUNT:()=>hfe,METRIC_JVM_CLASS_LOADED:()=>Tfe,METRIC_JVM_CLASS_UNLOADED:()=>Afe,METRIC_JVM_CPU_COUNT:()=>Rfe,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>yfe,METRIC_JVM_CPU_TIME:()=>Ofe,METRIC_JVM_GC_DURATION:()=>Nfe,METRIC_JVM_MEMORY_COMMITTED:()=>Cfe,METRIC_JVM_MEMORY_LIMIT:()=>vfe,METRIC_JVM_MEMORY_USED:()=>Ife,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>Pfe,METRIC_JVM_THREAD_COUNT:()=>bfe,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>Mfe,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>Lfe,METRIC_KESTREL_CONNECTION_DURATION:()=>xfe,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>Dfe,METRIC_KESTREL_QUEUED_REQUESTS:()=>Ufe,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>wfe,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>kfe,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>Vfe,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>Bfe,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>Gfe,MessageTypeValues:()=>bue,MessagingDestinationKindValues:()=>iue,MessagingOperationValues:()=>uue,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>xce,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>wce,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>Mce,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>Fce,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>Dce,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>Uce,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>Hce,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>bce,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>qce,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>kce,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>Bce,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>jce,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>Vce,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>Gce,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>Kce,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>$ce,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>Xce,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>Wce,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>zce,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>Yce,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>Lce,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>Cce,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>vce,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>Ice,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>Oce,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>Nce,NETTRANSPORTVALUES_INPROC:()=>Ace,NETTRANSPORTVALUES_IP:()=>gce,NETTRANSPORTVALUES_IP_TCP:()=>Ece,NETTRANSPORTVALUES_IP_UDP:()=>Sce,NETTRANSPORTVALUES_OTHER:()=>Rce,NETTRANSPORTVALUES_PIPE:()=>Tce,NETTRANSPORTVALUES_UNIX:()=>hce,NETWORK_TRANSPORT_VALUE_PIPE:()=>L_e,NETWORK_TRANSPORT_VALUE_QUIC:()=>x_e,NETWORK_TRANSPORT_VALUE_TCP:()=>D_e,NETWORK_TRANSPORT_VALUE_UDP:()=>U_e,NETWORK_TRANSPORT_VALUE_UNIX:()=>w_e,NETWORK_TYPE_VALUE_IPV4:()=>V_e,NETWORK_TYPE_VALUE_IPV6:()=>B_e,NetHostConnectionSubtypeValues:()=>Jce,NetHostConnectionTypeValues:()=>Pce,NetTransportValues:()=>yce,OSTYPEVALUES_AIX:()=>Kde,OSTYPEVALUES_DARWIN:()=>Hde,OSTYPEVALUES_DRAGONFLYBSD:()=>qde,OSTYPEVALUES_FREEBSD:()=>$de,OSTYPEVALUES_HPUX:()=>Yde,OSTYPEVALUES_LINUX:()=>Gde,OSTYPEVALUES_NETBSD:()=>Fde,OSTYPEVALUES_OPENBSD:()=>jde,OSTYPEVALUES_SOLARIS:()=>Wde,OSTYPEVALUES_WINDOWS:()=>Bde,OSTYPEVALUES_Z_OS:()=>zde,OTEL_STATUS_CODE_VALUE_ERROR:()=>F_e,OTEL_STATUS_CODE_VALUE_OK:()=>j_e,OsTypeValues:()=>Xde,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>Tue,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>Eue,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>due,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>Nue,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>fue,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>hue,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>yue,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>_ue,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>mue,RPCGRPCSTATUSCODEVALUES_OK:()=>lue,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>Aue,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>Sue,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>gue,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>Cue,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>Oue,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>Rue,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>pue,RpcGrpcStatusCodeValues:()=>vue,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>rie,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>mie,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>eie,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>Xse,SEMATTRS_AWS_DYNAMODB_COUNT:()=>_ie,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>cie,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>iie,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>Eie,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>oie,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>Jse,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>nie,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>aie,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>tie,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>Zse,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>Qse,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>fie,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>lie,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>die,SEMATTRS_AWS_DYNAMODB_SELECT:()=>sie,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>uie,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>zse,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>pie,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>Ioe,SEMATTRS_CODE_FILEPATH:()=>Lse,SEMATTRS_CODE_FUNCTION:()=>bse,SEMATTRS_CODE_LINENO:()=>xse,SEMATTRS_CODE_NAMESPACE:()=>Mse,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>Boe,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>joe,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>Foe,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>Hoe,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>koe,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>Voe,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>$oe,SEMATTRS_DB_CASSANDRA_TABLE:()=>Goe,SEMATTRS_DB_CONNECTION_STRING:()=>boe,SEMATTRS_DB_HBASE_NAMESPACE:()=>qoe,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>Loe,SEMATTRS_DB_MONGODB_COLLECTION:()=>Koe,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>woe,SEMATTRS_DB_NAME:()=>xoe,SEMATTRS_DB_OPERATION:()=>Uoe,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>Yoe,SEMATTRS_DB_SQL_TABLE:()=>Woe,SEMATTRS_DB_STATEMENT:()=>Doe,SEMATTRS_DB_SYSTEM:()=>Poe,SEMATTRS_DB_USER:()=>Moe,SEMATTRS_ENDUSER_ID:()=>Nse,SEMATTRS_ENDUSER_ROLE:()=>Cse,SEMATTRS_ENDUSER_SCOPE:()=>vse,SEMATTRS_EXCEPTION_ESCAPED:()=>Zoe,SEMATTRS_EXCEPTION_MESSAGE:()=>Xoe,SEMATTRS_EXCEPTION_STACKTRACE:()=>Joe,SEMATTRS_EXCEPTION_TYPE:()=>zoe,SEMATTRS_FAAS_COLDSTART:()=>ase,SEMATTRS_FAAS_CRON:()=>ise,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>tse,SEMATTRS_FAAS_DOCUMENT_NAME:()=>ose,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>nse,SEMATTRS_FAAS_DOCUMENT_TIME:()=>rse,SEMATTRS_FAAS_EXECUTION:()=>ese,SEMATTRS_FAAS_INVOKED_NAME:()=>cse,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>use,SEMATTRS_FAAS_INVOKED_REGION:()=>lse,SEMATTRS_FAAS_TIME:()=>sse,SEMATTRS_FAAS_TRIGGER:()=>Qoe,SEMATTRS_HTTP_CLIENT_IP:()=>Wse,SEMATTRS_HTTP_FLAVOR:()=>Gse,SEMATTRS_HTTP_HOST:()=>kse,SEMATTRS_HTTP_METHOD:()=>Dse,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>$se,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>Fse,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>jse,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>qse,SEMATTRS_HTTP_ROUTE:()=>Kse,SEMATTRS_HTTP_SCHEME:()=>Vse,SEMATTRS_HTTP_SERVER_NAME:()=>Yse,SEMATTRS_HTTP_STATUS_CODE:()=>Bse,SEMATTRS_HTTP_TARGET:()=>wse,SEMATTRS_HTTP_URL:()=>Use,SEMATTRS_HTTP_USER_AGENT:()=>Hse,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>Yie,SEMATTRS_MESSAGE_ID:()=>qie,SEMATTRS_MESSAGE_TYPE:()=>jie,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>Kie,SEMATTRS_MESSAGING_CONSUMER_ID:()=>Pie,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>Nie,SEMATTRS_MESSAGING_DESTINATION:()=>gie,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>hie,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>xie,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>Lie,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>Mie,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>Die,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>Uie,SEMATTRS_MESSAGING_MESSAGE_ID:()=>Oie,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>vie,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>Cie,SEMATTRS_MESSAGING_OPERATION:()=>Iie,SEMATTRS_MESSAGING_PROTOCOL:()=>Aie,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>Rie,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>bie,SEMATTRS_MESSAGING_SYSTEM:()=>Sie,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>Tie,SEMATTRS_MESSAGING_URL:()=>yie,SEMATTRS_NET_HOST_CARRIER_ICC:()=>yse,SEMATTRS_NET_HOST_CARRIER_MCC:()=>Ase,SEMATTRS_NET_HOST_CARRIER_MNC:()=>Rse,SEMATTRS_NET_HOST_CARRIER_NAME:()=>Tse,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>hse,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>gse,SEMATTRS_NET_HOST_IP:()=>mse,SEMATTRS_NET_HOST_NAME:()=>Sse,SEMATTRS_NET_HOST_PORT:()=>Ese,SEMATTRS_NET_PEER_IP:()=>pse,SEMATTRS_NET_PEER_NAME:()=>fse,SEMATTRS_NET_PEER_PORT:()=>_se,SEMATTRS_NET_TRANSPORT:()=>dse,SEMATTRS_PEER_SERVICE:()=>Ose,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>Bie,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>$ie,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>Fie,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>Hie,SEMATTRS_RPC_JSONRPC_VERSION:()=>Gie,SEMATTRS_RPC_METHOD:()=>Vie,SEMATTRS_RPC_SERVICE:()=>kie,SEMATTRS_RPC_SYSTEM:()=>wie,SEMATTRS_THREAD_ID:()=>Ise,SEMATTRS_THREAD_NAME:()=>Pse,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>kue,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>wue,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>Vue,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>Bue,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>Gue,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>Hue,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>$ue,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>jue,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>Fue,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>Yue,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>que,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>Lue,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>Due,SEMRESATTRS_CLOUD_PLATFORM:()=>Uue,SEMRESATTRS_CLOUD_PROVIDER:()=>Mue,SEMRESATTRS_CLOUD_REGION:()=>xue,SEMRESATTRS_CONTAINER_ID:()=>Wue,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>Xue,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>Jue,SEMRESATTRS_CONTAINER_NAME:()=>Kue,SEMRESATTRS_CONTAINER_RUNTIME:()=>zue,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>Zue,SEMRESATTRS_DEVICE_ID:()=>Que,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>ele,SEMRESATTRS_DEVICE_MODEL_NAME:()=>tle,SEMRESATTRS_FAAS_ID:()=>rle,SEMRESATTRS_FAAS_INSTANCE:()=>sle,SEMRESATTRS_FAAS_MAX_MEMORY:()=>ile,SEMRESATTRS_FAAS_NAME:()=>nle,SEMRESATTRS_FAAS_VERSION:()=>ole,SEMRESATTRS_HOST_ARCH:()=>lle,SEMRESATTRS_HOST_ID:()=>ale,SEMRESATTRS_HOST_IMAGE_ID:()=>ple,SEMRESATTRS_HOST_IMAGE_NAME:()=>dle,SEMRESATTRS_HOST_IMAGE_VERSION:()=>_le,SEMRESATTRS_HOST_NAME:()=>cle,SEMRESATTRS_HOST_TYPE:()=>ule,SEMRESATTRS_K8S_CLUSTER_NAME:()=>fle,SEMRESATTRS_K8S_CONTAINER_NAME:()=>Tle,SEMRESATTRS_K8S_CRONJOB_NAME:()=>Lle,SEMRESATTRS_K8S_CRONJOB_UID:()=>Mle,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>Ile,SEMRESATTRS_K8S_DAEMONSET_UID:()=>vle,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>Ole,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>yle,SEMRESATTRS_K8S_JOB_NAME:()=>ble,SEMRESATTRS_K8S_JOB_UID:()=>Ple,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>Sle,SEMRESATTRS_K8S_NODE_NAME:()=>mle,SEMRESATTRS_K8S_NODE_UID:()=>Ele,SEMRESATTRS_K8S_POD_NAME:()=>hle,SEMRESATTRS_K8S_POD_UID:()=>gle,SEMRESATTRS_K8S_REPLICASET_NAME:()=>Rle,SEMRESATTRS_K8S_REPLICASET_UID:()=>Ale,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>Cle,SEMRESATTRS_K8S_STATEFULSET_UID:()=>Nle,SEMRESATTRS_OS_DESCRIPTION:()=>Dle,SEMRESATTRS_OS_NAME:()=>Ule,SEMRESATTRS_OS_TYPE:()=>xle,SEMRESATTRS_OS_VERSION:()=>wle,SEMRESATTRS_PROCESS_COMMAND:()=>Gle,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>$le,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>Hle,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>Vle,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>Ble,SEMRESATTRS_PROCESS_OWNER:()=>Fle,SEMRESATTRS_PROCESS_PID:()=>kle,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>Yle,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>jle,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>qle,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>zle,SEMRESATTRS_SERVICE_NAME:()=>Kle,SEMRESATTRS_SERVICE_NAMESPACE:()=>Wle,SEMRESATTRS_SERVICE_VERSION:()=>Xle,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>ede,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>Zle,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>Jle,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>Qle,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>rde,SEMRESATTRS_WEBENGINE_NAME:()=>tde,SEMRESATTRS_WEBENGINE_VERSION:()=>nde,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>J_e,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>Z_e,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>Q_e,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>tfe,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>nfe,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>rfe,SemanticAttributes:()=>Wie,SemanticResourceAttributes:()=>ode,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>Jde,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>Zde,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>Qde,TELEMETRYSDKLANGUAGEVALUES_GO:()=>epe,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>tpe,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>npe,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>rpe,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>ope,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>spe,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>ipe,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>fpe,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>mpe,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>Epe,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>Spe,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>gpe,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>hpe,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>Tpe,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>Ape,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>Rpe,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>ype,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>Ope,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>Npe,TelemetrySdkLanguageValues:()=>ape});var zn=$(()=>{cU();D1();U1();w1()});var k1=m(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});_f.SDK_INFO=void 0;var Hfe=lA(),Dl=(zn(),b(Wn));_f.SDK_INFO={[Dl.SEMRESATTRS_TELEMETRY_SDK_NAME]:"opentelemetry",[Dl.SEMRESATTRS_PROCESS_RUNTIME_NAME]:"node",[Dl.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:Dl.TELEMETRYSDKLANGUAGEVALUES_NODEJS,[Dl.SEMRESATTRS_TELEMETRY_SDK_VERSION]:Hfe.VERSION}});var V1=m(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});ff.unrefTimer=void 0;function $fe(t){t.unref()}ff.unrefTimer=$fe});var G1=m(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.unrefTimer=Rt.SDK_INFO=Rt.otperformance=Rt.RandomIdGenerator=Rt.hexToBase64=Rt._globalThis=Rt.getEnv=Rt.getEnvWithoutDefaults=void 0;var B1=lM();Object.defineProperty(Rt,"getEnvWithoutDefaults",{enumerable:!0,get:function(){return B1.getEnvWithoutDefaults}});Object.defineProperty(Rt,"getEnv",{enumerable:!0,get:function(){return B1.getEnv}});var Ffe=dM();Object.defineProperty(Rt,"_globalThis",{enumerable:!0,get:function(){return Ffe._globalThis}});var jfe=_M();Object.defineProperty(Rt,"hexToBase64",{enumerable:!0,get:function(){return jfe.hexToBase64}});var qfe=EM();Object.defineProperty(Rt,"RandomIdGenerator",{enumerable:!0,get:function(){return qfe.RandomIdGenerator}});var Yfe=SM();Object.defineProperty(Rt,"otperformance",{enumerable:!0,get:function(){return Yfe.otperformance}});var Kfe=k1();Object.defineProperty(Rt,"SDK_INFO",{enumerable:!0,get:function(){return Kfe.SDK_INFO}});var Wfe=V1();Object.defineProperty(Rt,"unrefTimer",{enumerable:!0,get:function(){return Wfe.unrefTimer}})});var pA=m(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.unrefTimer=yt.otperformance=yt.hexToBase64=yt.getEnvWithoutDefaults=yt.getEnv=yt._globalThis=yt.SDK_INFO=yt.RandomIdGenerator=void 0;var Is=G1();Object.defineProperty(yt,"RandomIdGenerator",{enumerable:!0,get:function(){return Is.RandomIdGenerator}});Object.defineProperty(yt,"SDK_INFO",{enumerable:!0,get:function(){return Is.SDK_INFO}});Object.defineProperty(yt,"_globalThis",{enumerable:!0,get:function(){return Is._globalThis}});Object.defineProperty(yt,"getEnv",{enumerable:!0,get:function(){return Is.getEnv}});Object.defineProperty(yt,"getEnvWithoutDefaults",{enumerable:!0,get:function(){return Is.getEnvWithoutDefaults}});Object.defineProperty(yt,"hexToBase64",{enumerable:!0,get:function(){return Is.hexToBase64}});Object.defineProperty(yt,"otperformance",{enumerable:!0,get:function(){return Is.otperformance}});Object.defineProperty(yt,"unrefTimer",{enumerable:!0,get:function(){return Is.unrefTimer}})});var j1=m(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.addHrTimes=be.isTimeInput=be.isTimeInputHrTime=be.hrTimeToMicroseconds=be.hrTimeToMilliseconds=be.hrTimeToNanoseconds=be.hrTimeToTimeStamp=be.hrTimeDuration=be.timeInputToHrTime=be.hrTime=be.getTimeOrigin=be.millisToHrTime=void 0;var _A=pA(),H1=9,zfe=6,Xfe=Math.pow(10,zfe),mf=Math.pow(10,H1);function Ul(t){let e=t/1e3,n=Math.trunc(e),r=Math.round(t%1e3*Xfe);return[n,r]}be.millisToHrTime=Ul;function fA(){let t=_A.otperformance.timeOrigin;if(typeof t!="number"){let e=_A.otperformance;t=e.timing&&e.timing.fetchStart}return t}be.getTimeOrigin=fA;function $1(t){let e=Ul(fA()),n=Ul(typeof t=="number"?t:_A.otperformance.now());return F1(e,n)}be.hrTime=$1;function Jfe(t){if(mA(t))return t;if(typeof t=="number")return t<fA()?$1(t):Ul(t);if(t instanceof Date)return Ul(t.getTime());throw TypeError("Invalid input type")}be.timeInputToHrTime=Jfe;function Zfe(t,e){let n=e[0]-t[0],r=e[1]-t[1];return r<0&&(n-=1,r+=mf),[n,r]}be.hrTimeDuration=Zfe;function Qfe(t){let e=H1,n=`${"0".repeat(e)}${t[1]}Z`,r=n.substring(n.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",r)}be.hrTimeToTimeStamp=Qfe;function eme(t){return t[0]*mf+t[1]}be.hrTimeToNanoseconds=eme;function tme(t){return t[0]*1e3+t[1]/1e6}be.hrTimeToMilliseconds=tme;function nme(t){return t[0]*1e6+t[1]/1e3}be.hrTimeToMicroseconds=nme;function mA(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}be.isTimeInputHrTime=mA;function rme(t){return mA(t)||typeof t=="number"||t instanceof Date}be.isTimeInput=rme;function F1(t,e){let n=[t[0]+e[0],t[1]+e[1]];return n[1]>=mf&&(n[1]-=mf,n[0]+=1),n}be.addHrTimes=F1});var q1=m(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.ExportResultCode=void 0;var ome;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(ome=wl.ExportResultCode||(wl.ExportResultCode={}))});var K1=m(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});Ef.CompositePropagator=void 0;var Y1=(x(),b(B)),EA=class{constructor(e={}){var n;this._propagators=(n=e.propagators)!==null&&n!==void 0?n:[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,o)=>r.concat(o),[])))}inject(e,n,r){for(let o of this._propagators)try{o.inject(e,n,r)}catch(s){Y1.diag.warn(`Failed to inject with ${o.constructor.name}. Err: ${s.message}`)}}extract(e,n,r){return this._propagators.reduce((o,s)=>{try{return s.extract(o,n,r)}catch(i){Y1.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${i.message}`)}return o},e)}fields(){return this._fields.slice()}};Ef.CompositePropagator=EA});var W1=m(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.validateValue=dc.validateKey=void 0;var SA="[_0-9a-z-*/]",sme=`[a-z]${SA}{0,255}`,ime=`[a-z0-9]${SA}{0,240}@[a-z]${SA}{0,13}`,ame=new RegExp(`^(?:${sme}|${ime})$`),cme=/^[ -~]{0,255}[!-~]$/,ume=/,|=/;function lme(t){return ame.test(t)}dc.validateKey=lme;function dme(t){return cme.test(t)&&!ume.test(t)}dc.validateValue=dme});var hA=m(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});Sf.TraceState=void 0;var z1=W1(),X1=32,pme=512,J1=",",Z1="=",gA=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,n){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,n),r}unset(e){let n=this._clone();return n._internalState.delete(e),n}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,n)=>(e.push(n+Z1+this.get(n)),e),[]).join(J1)}_parse(e){e.length>pme||(this._internalState=e.split(J1).reverse().reduce((n,r)=>{let o=r.trim(),s=o.indexOf(Z1);if(s!==-1){let i=o.slice(0,s),a=o.slice(s+1,r.length);(0,z1.validateKey)(i)&&(0,z1.validateValue)(a)&&n.set(i,a)}return n},new Map),this._internalState.size>X1&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,X1))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};Sf.TraceState=gA});var ek=m(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.W3CTraceContextPropagator=jt.parseTraceParent=jt.TRACE_STATE_HEADER=jt.TRACE_PARENT_HEADER=void 0;var gf=(x(),b(B)),_me=Ll(),fme=hA();jt.TRACE_PARENT_HEADER="traceparent";jt.TRACE_STATE_HEADER="tracestate";var mme="00",Eme="(?!ff)[\\da-f]{2}",Sme="(?![0]{32})[\\da-f]{32}",gme="(?![0]{16})[\\da-f]{16}",hme="[\\da-f]{2}",Tme=new RegExp(`^\\s?(${Eme})-(${Sme})-(${gme})-(${hme})(-.*)?\\s?$`);function Q1(t){let e=Tme.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}jt.parseTraceParent=Q1;var TA=class{inject(e,n,r){let o=gf.trace.getSpanContext(e);if(!o||(0,_me.isTracingSuppressed)(e)||!(0,gf.isSpanContextValid)(o))return;let s=`${mme}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||gf.TraceFlags.NONE).toString(16)}`;r.set(n,jt.TRACE_PARENT_HEADER,s),o.traceState&&r.set(n,jt.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,n,r){let o=r.get(n,jt.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let i=Q1(s);if(!i)return e;i.isRemote=!0;let a=r.get(n,jt.TRACE_STATE_HEADER);if(a){let c=Array.isArray(a)?a.join(","):a;i.traceState=new fme.TraceState(typeof c=="string"?c:void 0)}return gf.trace.setSpanContext(e,i)}fields(){return[jt.TRACE_PARENT_HEADER,jt.TRACE_STATE_HEADER]}};jt.W3CTraceContextPropagator=TA});var tk=m(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.getRPCMetadata=hr.deleteRPCMetadata=hr.setRPCMetadata=hr.RPCType=void 0;var Ame=(x(),b(B)),AA=(0,Ame.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),Rme;(function(t){t.HTTP="http"})(Rme=hr.RPCType||(hr.RPCType={}));function yme(t,e){return t.setValue(AA,e)}hr.setRPCMetadata=yme;function Ome(t){return t.deleteValue(AA)}hr.deleteRPCMetadata=Ome;function Nme(t){return t.getValue(AA)}hr.getRPCMetadata=Nme});var yA=m(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});hf.AlwaysOffSampler=void 0;var Cme=(x(),b(B)),RA=class{shouldSample(){return{decision:Cme.SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}};hf.AlwaysOffSampler=RA});var NA=m(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});Tf.AlwaysOnSampler=void 0;var vme=(x(),b(B)),OA=class{shouldSample(){return{decision:vme.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}};Tf.AlwaysOnSampler=OA});var rk=m(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});Rf.ParentBasedSampler=void 0;var Af=(x(),b(B)),Ime=oA(),nk=yA(),CA=NA(),vA=class{constructor(e){var n,r,o,s;this._root=e.root,this._root||((0,Ime.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new CA.AlwaysOnSampler),this._remoteParentSampled=(n=e.remoteParentSampled)!==null&&n!==void 0?n:new CA.AlwaysOnSampler,this._remoteParentNotSampled=(r=e.remoteParentNotSampled)!==null&&r!==void 0?r:new nk.AlwaysOffSampler,this._localParentSampled=(o=e.localParentSampled)!==null&&o!==void 0?o:new CA.AlwaysOnSampler,this._localParentNotSampled=(s=e.localParentNotSampled)!==null&&s!==void 0?s:new nk.AlwaysOffSampler}shouldSample(e,n,r,o,s,i){let a=Af.trace.getSpanContext(e);return!a||!(0,Af.isSpanContextValid)(a)?this._root.shouldSample(e,n,r,o,s,i):a.isRemote?a.traceFlags&Af.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,n,r,o,s,i):this._remoteParentNotSampled.shouldSample(e,n,r,o,s,i):a.traceFlags&Af.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,n,r,o,s,i):this._localParentNotSampled.shouldSample(e,n,r,o,s,i)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}};Rf.ParentBasedSampler=vA});var ok=m(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});yf.TraceIdRatioBasedSampler=void 0;var IA=(x(),b(B)),PA=class{constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,n){return{decision:(0,IA.isValidTraceId)(n)&&this._accumulate(n)<this._upperBound?IA.SamplingDecision.RECORD_AND_SAMPLED:IA.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!="number"||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let n=0;for(let r=0;r<e.length/8;r++){let o=r*8,s=parseInt(e.slice(o,o+8),16);n=(n^s)>>>0}return n}};yf.TraceIdRatioBasedSampler=PA});var uk=m(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});Of.isPlainObject=void 0;var Pme="[object Object]",bme="[object Null]",Mme="[object Undefined]",Lme=Function.prototype,sk=Lme.toString,xme=sk.call(Object),Dme=Ume(Object.getPrototypeOf,Object),ik=Object.prototype,ak=ik.hasOwnProperty,Qi=Symbol?Symbol.toStringTag:void 0,ck=ik.toString;function Ume(t,e){return function(n){return t(e(n))}}function wme(t){if(!kme(t)||Vme(t)!==Pme)return!1;let e=Dme(t);if(e===null)return!0;let n=ak.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&sk.call(n)===xme}Of.isPlainObject=wme;function kme(t){return t!=null&&typeof t=="object"}function Vme(t){return t==null?t===void 0?Mme:bme:Qi&&Qi in Object(t)?Bme(t):Gme(t)}function Bme(t){let e=ak.call(t,Qi),n=t[Qi],r=!1;try{t[Qi]=void 0,r=!0}catch{}let o=ck.call(t);return r&&(e?t[Qi]=n:delete t[Qi]),o}function Gme(t){return ck.call(t)}});var fk=m(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});vf.merge=void 0;var lk=uk(),Hme=20;function $me(...t){let e=t.shift(),n=new WeakMap;for(;t.length>0;)e=pk(e,t.shift(),0,n);return e}vf.merge=$me;function bA(t){return Cf(t)?t.slice():t}function pk(t,e,n=0,r){let o;if(!(n>Hme)){if(n++,Nf(t)||Nf(e)||_k(e))o=bA(e);else if(Cf(t)){if(o=t.slice(),Cf(e))for(let s=0,i=e.length;s<i;s++)o.push(bA(e[s]));else if(kl(e)){let s=Object.keys(e);for(let i=0,a=s.length;i<a;i++){let c=s[i];o[c]=bA(e[c])}}}else if(kl(t))if(kl(e)){if(!Fme(t,e))return e;o=Object.assign({},t);let s=Object.keys(e);for(let i=0,a=s.length;i<a;i++){let c=s[i],u=e[c];if(Nf(u))typeof u>"u"?delete o[c]:o[c]=u;else{let l=o[c],d=u;if(dk(t,c,r)||dk(e,c,r))delete o[c];else{if(kl(l)&&kl(d)){let p=r.get(l)||[],_=r.get(d)||[];p.push({obj:t,key:c}),_.push({obj:e,key:c}),r.set(l,p),r.set(d,_)}o[c]=pk(o[c],u,n,r)}}}}else o=e;return o}}function dk(t,e,n){let r=n.get(t[e])||[];for(let o=0,s=r.length;o<s;o++){let i=r[o];if(i.key===e&&i.obj===t)return!0}return!1}function Cf(t){return Array.isArray(t)}function _k(t){return typeof t=="function"}function kl(t){return!Nf(t)&&!Cf(t)&&!_k(t)&&typeof t=="object"}function Nf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Fme(t,e){return!(!(0,lk.isPlainObject)(t)||!(0,lk.isPlainObject)(e))}});var mk=m(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.callWithTimeout=pc.TimeoutError=void 0;var If=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};pc.TimeoutError=If;function jme(t,e){let n,r=new Promise(function(s,i){n=setTimeout(function(){i(new If("Operation timed out."))},e)});return Promise.race([t,r]).then(o=>(clearTimeout(n),o),o=>{throw clearTimeout(n),o})}pc.callWithTimeout=jme});var Sk=m(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.isUrlIgnored=_c.urlMatches=void 0;function Ek(t,e){return typeof e=="string"?t===e:!!t.match(e)}_c.urlMatches=Ek;function qme(t,e){if(!e)return!1;for(let n of e)if(Ek(t,n))return!0;return!1}_c.isUrlIgnored=qme});var gk=m(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});Pf.isWrapped=void 0;function Yme(t){return typeof t=="function"&&typeof t.__original=="function"&&typeof t.__unwrap=="function"&&t.__wrapped===!0}Pf.isWrapped=Yme});var hk=m(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});bf.Deferred=void 0;var MA=class{constructor(){this._promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};bf.Deferred=MA});var Tk=m(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});Mf.BindOnceFuture=void 0;var Kme=hk(),LA=class{constructor(e,n){this._callback=e,this._that=n,this._isCalled=!1,this._deferred=new Kme.Deferred}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(n=>this._deferred.resolve(n),n=>this._deferred.reject(n))}catch(n){this._deferred.reject(n)}}return this._deferred.promise}};Mf.BindOnceFuture=LA});var Rk=m(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});Lf._export=void 0;var Ak=(x(),b(B)),Wme=Ll();function zme(t,e){return new Promise(n=>{Ak.context.with((0,Wme.suppressTracing)(Ak.context.active()),()=>{t.export(e,r=>{n(r)})})})}Lf._export=zme});var Se=m(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=N.DEFAULT_ATTRIBUTE_COUNT_LIMIT=N.TraceState=N.unsuppressTracing=N.suppressTracing=N.isTracingSuppressed=N.TraceIdRatioBasedSampler=N.ParentBasedSampler=N.AlwaysOnSampler=N.AlwaysOffSampler=N.setRPCMetadata=N.getRPCMetadata=N.deleteRPCMetadata=N.RPCType=N.parseTraceParent=N.W3CTraceContextPropagator=N.TRACE_STATE_HEADER=N.TRACE_PARENT_HEADER=N.CompositePropagator=N.unrefTimer=N.otperformance=N.hexToBase64=N.getEnvWithoutDefaults=N.getEnv=N._globalThis=N.SDK_INFO=N.RandomIdGenerator=N.baggageUtils=N.ExportResultCode=N.hexToBinary=N.timeInputToHrTime=N.millisToHrTime=N.isTimeInputHrTime=N.isTimeInput=N.hrTimeToTimeStamp=N.hrTimeToNanoseconds=N.hrTimeToMilliseconds=N.hrTimeToMicroseconds=N.hrTimeDuration=N.hrTime=N.getTimeOrigin=N.addHrTimes=N.loggingErrorHandler=N.setGlobalErrorHandler=N.globalErrorHandler=N.sanitizeAttributes=N.isAttributeValue=N.isAttributeKey=N.AnchoredClock=N.W3CBaggagePropagator=void 0;N.internal=N.VERSION=N.BindOnceFuture=N.isWrapped=N.urlMatches=N.isUrlIgnored=N.callWithTimeout=N.TimeoutError=N.TracesSamplerValues=N.merge=N.parseEnvironment=N.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT=N.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT=N.DEFAULT_ENVIRONMENT=void 0;var Xme=nM();Object.defineProperty(N,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Xme.W3CBaggagePropagator}});var Jme=rM();Object.defineProperty(N,"AnchoredClock",{enumerable:!0,get:function(){return Jme.AnchoredClock}});var xA=cM();Object.defineProperty(N,"isAttributeKey",{enumerable:!0,get:function(){return xA.isAttributeKey}});Object.defineProperty(N,"isAttributeValue",{enumerable:!0,get:function(){return xA.isAttributeValue}});Object.defineProperty(N,"sanitizeAttributes",{enumerable:!0,get:function(){return xA.sanitizeAttributes}});var yk=oA();Object.defineProperty(N,"globalErrorHandler",{enumerable:!0,get:function(){return yk.globalErrorHandler}});Object.defineProperty(N,"setGlobalErrorHandler",{enumerable:!0,get:function(){return yk.setGlobalErrorHandler}});var Zme=rA();Object.defineProperty(N,"loggingErrorHandler",{enumerable:!0,get:function(){return Zme.loggingErrorHandler}});var Xn=j1();Object.defineProperty(N,"addHrTimes",{enumerable:!0,get:function(){return Xn.addHrTimes}});Object.defineProperty(N,"getTimeOrigin",{enumerable:!0,get:function(){return Xn.getTimeOrigin}});Object.defineProperty(N,"hrTime",{enumerable:!0,get:function(){return Xn.hrTime}});Object.defineProperty(N,"hrTimeDuration",{enumerable:!0,get:function(){return Xn.hrTimeDuration}});Object.defineProperty(N,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return Xn.hrTimeToMicroseconds}});Object.defineProperty(N,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return Xn.hrTimeToMilliseconds}});Object.defineProperty(N,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return Xn.hrTimeToNanoseconds}});Object.defineProperty(N,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return Xn.hrTimeToTimeStamp}});Object.defineProperty(N,"isTimeInput",{enumerable:!0,get:function(){return Xn.isTimeInput}});Object.defineProperty(N,"isTimeInputHrTime",{enumerable:!0,get:function(){return Xn.isTimeInputHrTime}});Object.defineProperty(N,"millisToHrTime",{enumerable:!0,get:function(){return Xn.millisToHrTime}});Object.defineProperty(N,"timeInputToHrTime",{enumerable:!0,get:function(){return Xn.timeInputToHrTime}});var Qme=cA();Object.defineProperty(N,"hexToBinary",{enumerable:!0,get:function(){return Qme.hexToBinary}});var eEe=q1();Object.defineProperty(N,"ExportResultCode",{enumerable:!0,get:function(){return eEe.ExportResultCode}});var xf=ZT();N.baggageUtils={getKeyPairs:xf.getKeyPairs,serializeKeyPairs:xf.serializeKeyPairs,parseKeyPairsIntoRecord:xf.parseKeyPairsIntoRecord,parsePairKeyValue:xf.parsePairKeyValue};var Ps=pA();Object.defineProperty(N,"RandomIdGenerator",{enumerable:!0,get:function(){return Ps.RandomIdGenerator}});Object.defineProperty(N,"SDK_INFO",{enumerable:!0,get:function(){return Ps.SDK_INFO}});Object.defineProperty(N,"_globalThis",{enumerable:!0,get:function(){return Ps._globalThis}});Object.defineProperty(N,"getEnv",{enumerable:!0,get:function(){return Ps.getEnv}});Object.defineProperty(N,"getEnvWithoutDefaults",{enumerable:!0,get:function(){return Ps.getEnvWithoutDefaults}});Object.defineProperty(N,"hexToBase64",{enumerable:!0,get:function(){return Ps.hexToBase64}});Object.defineProperty(N,"otperformance",{enumerable:!0,get:function(){return Ps.otperformance}});Object.defineProperty(N,"unrefTimer",{enumerable:!0,get:function(){return Ps.unrefTimer}});var tEe=K1();Object.defineProperty(N,"CompositePropagator",{enumerable:!0,get:function(){return tEe.CompositePropagator}});var Df=ek();Object.defineProperty(N,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return Df.TRACE_PARENT_HEADER}});Object.defineProperty(N,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return Df.TRACE_STATE_HEADER}});Object.defineProperty(N,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return Df.W3CTraceContextPropagator}});Object.defineProperty(N,"parseTraceParent",{enumerable:!0,get:function(){return Df.parseTraceParent}});var Uf=tk();Object.defineProperty(N,"RPCType",{enumerable:!0,get:function(){return Uf.RPCType}});Object.defineProperty(N,"deleteRPCMetadata",{enumerable:!0,get:function(){return Uf.deleteRPCMetadata}});Object.defineProperty(N,"getRPCMetadata",{enumerable:!0,get:function(){return Uf.getRPCMetadata}});Object.defineProperty(N,"setRPCMetadata",{enumerable:!0,get:function(){return Uf.setRPCMetadata}});var nEe=yA();Object.defineProperty(N,"AlwaysOffSampler",{enumerable:!0,get:function(){return nEe.AlwaysOffSampler}});var rEe=NA();Object.defineProperty(N,"AlwaysOnSampler",{enumerable:!0,get:function(){return rEe.AlwaysOnSampler}});var oEe=rk();Object.defineProperty(N,"ParentBasedSampler",{enumerable:!0,get:function(){return oEe.ParentBasedSampler}});var sEe=ok();Object.defineProperty(N,"TraceIdRatioBasedSampler",{enumerable:!0,get:function(){return sEe.TraceIdRatioBasedSampler}});var DA=Ll();Object.defineProperty(N,"isTracingSuppressed",{enumerable:!0,get:function(){return DA.isTracingSuppressed}});Object.defineProperty(N,"suppressTracing",{enumerable:!0,get:function(){return DA.suppressTracing}});Object.defineProperty(N,"unsuppressTracing",{enumerable:!0,get:function(){return DA.unsuppressTracing}});var iEe=hA();Object.defineProperty(N,"TraceState",{enumerable:!0,get:function(){return iEe.TraceState}});var fc=iA();Object.defineProperty(N,"DEFAULT_ATTRIBUTE_COUNT_LIMIT",{enumerable:!0,get:function(){return fc.DEFAULT_ATTRIBUTE_COUNT_LIMIT}});Object.defineProperty(N,"DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT",{enumerable:!0,get:function(){return fc.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT}});Object.defineProperty(N,"DEFAULT_ENVIRONMENT",{enumerable:!0,get:function(){return fc.DEFAULT_ENVIRONMENT}});Object.defineProperty(N,"DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT",{enumerable:!0,get:function(){return fc.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT}});Object.defineProperty(N,"DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT",{enumerable:!0,get:function(){return fc.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT}});Object.defineProperty(N,"parseEnvironment",{enumerable:!0,get:function(){return fc.parseEnvironment}});var aEe=fk();Object.defineProperty(N,"merge",{enumerable:!0,get:function(){return aEe.merge}});var cEe=sA();Object.defineProperty(N,"TracesSamplerValues",{enumerable:!0,get:function(){return cEe.TracesSamplerValues}});var Ok=mk();Object.defineProperty(N,"TimeoutError",{enumerable:!0,get:function(){return Ok.TimeoutError}});Object.defineProperty(N,"callWithTimeout",{enumerable:!0,get:function(){return Ok.callWithTimeout}});var Nk=Sk();Object.defineProperty(N,"isUrlIgnored",{enumerable:!0,get:function(){return Nk.isUrlIgnored}});Object.defineProperty(N,"urlMatches",{enumerable:!0,get:function(){return Nk.urlMatches}});var uEe=gk();Object.defineProperty(N,"isWrapped",{enumerable:!0,get:function(){return uEe.isWrapped}});var lEe=Tk();Object.defineProperty(N,"BindOnceFuture",{enumerable:!0,get:function(){return lEe.BindOnceFuture}});var dEe=lA();Object.defineProperty(N,"VERSION",{enumerable:!0,get:function(){return dEe.VERSION}});var pEe=Rk();N.internal={_export:pEe._export}});var Vl=m((g2e,Ck)=>{"use strict";var _Ee="2.0.0",fEe=Number.MAX_SAFE_INTEGER||9007199254740991,mEe=16,EEe=250,SEe=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ck.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:mEe,MAX_SAFE_BUILD_LENGTH:EEe,MAX_SAFE_INTEGER:fEe,RELEASE_TYPES:SEe,SEMVER_SPEC_VERSION:_Ee,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Bl=m((h2e,vk)=>{"use strict";var gEe=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};vk.exports=gEe});var mc=m((zr,Ik)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:UA,MAX_SAFE_BUILD_LENGTH:hEe,MAX_LENGTH:TEe}=Vl(),AEe=Bl();zr=Ik.exports={};var REe=zr.re=[],yEe=zr.safeRe=[],w=zr.src=[],OEe=zr.safeSrc=[],k=zr.t={},NEe=0,wA="[a-zA-Z0-9-]",CEe=[["\\s",1],["\\d",TEe],[wA,hEe]],vEe=t=>{for(let[e,n]of CEe)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},ne=(t,e,n)=>{let r=vEe(e),o=NEe++;AEe(t,o,e),k[t]=o,w[o]=e,OEe[o]=r,REe[o]=new RegExp(e,n?"g":void 0),yEe[o]=new RegExp(r,n?"g":void 0)};ne("NUMERICIDENTIFIER","0|[1-9]\\d*");ne("NUMERICIDENTIFIERLOOSE","\\d+");ne("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${wA}*`);ne("MAINVERSION",`(${w[k.NUMERICIDENTIFIER]})\\.(${w[k.NUMERICIDENTIFIER]})\\.(${w[k.NUMERICIDENTIFIER]})`);ne("MAINVERSIONLOOSE",`(${w[k.NUMERICIDENTIFIERLOOSE]})\\.(${w[k.NUMERICIDENTIFIERLOOSE]})\\.(${w[k.NUMERICIDENTIFIERLOOSE]})`);ne("PRERELEASEIDENTIFIER",`(?:${w[k.NONNUMERICIDENTIFIER]}|${w[k.NUMERICIDENTIFIER]})`);ne("PRERELEASEIDENTIFIERLOOSE",`(?:${w[k.NONNUMERICIDENTIFIER]}|${w[k.NUMERICIDENTIFIERLOOSE]})`);ne("PRERELEASE",`(?:-(${w[k.PRERELEASEIDENTIFIER]}(?:\\.${w[k.PRERELEASEIDENTIFIER]})*))`);ne("PRERELEASELOOSE",`(?:-?(${w[k.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${w[k.PRERELEASEIDENTIFIERLOOSE]})*))`);ne("BUILDIDENTIFIER",`${wA}+`);ne("BUILD",`(?:\\+(${w[k.BUILDIDENTIFIER]}(?:\\.${w[k.BUILDIDENTIFIER]})*))`);ne("FULLPLAIN",`v?${w[k.MAINVERSION]}${w[k.PRERELEASE]}?${w[k.BUILD]}?`);ne("FULL",`^${w[k.FULLPLAIN]}$`);ne("LOOSEPLAIN",`[v=\\s]*${w[k.MAINVERSIONLOOSE]}${w[k.PRERELEASELOOSE]}?${w[k.BUILD]}?`);ne("LOOSE",`^${w[k.LOOSEPLAIN]}$`);ne("GTLT","((?:<|>)?=?)");ne("XRANGEIDENTIFIERLOOSE",`${w[k.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);ne("XRANGEIDENTIFIER",`${w[k.NUMERICIDENTIFIER]}|x|X|\\*`);ne("XRANGEPLAIN",`[v=\\s]*(${w[k.XRANGEIDENTIFIER]})(?:\\.(${w[k.XRANGEIDENTIFIER]})(?:\\.(${w[k.XRANGEIDENTIFIER]})(?:${w[k.PRERELEASE]})?${w[k.BUILD]}?)?)?`);ne("XRANGEPLAINLOOSE",`[v=\\s]*(${w[k.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[k.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[k.XRANGEIDENTIFIERLOOSE]})(?:${w[k.PRERELEASELOOSE]})?${w[k.BUILD]}?)?)?`);ne("XRANGE",`^${w[k.GTLT]}\\s*${w[k.XRANGEPLAIN]}$`);ne("XRANGELOOSE",`^${w[k.GTLT]}\\s*${w[k.XRANGEPLAINLOOSE]}$`);ne("COERCEPLAIN",`(^|[^\\d])(\\d{1,${UA}})(?:\\.(\\d{1,${UA}}))?(?:\\.(\\d{1,${UA}}))?`);ne("COERCE",`${w[k.COERCEPLAIN]}(?:$|[^\\d])`);ne("COERCEFULL",w[k.COERCEPLAIN]+`(?:${w[k.PRERELEASE]})?(?:${w[k.BUILD]})?(?:$|[^\\d])`);ne("COERCERTL",w[k.COERCE],!0);ne("COERCERTLFULL",w[k.COERCEFULL],!0);ne("LONETILDE","(?:~>?)");ne("TILDETRIM",`(\\s*)${w[k.LONETILDE]}\\s+`,!0);zr.tildeTrimReplace="$1~";ne("TILDE",`^${w[k.LONETILDE]}${w[k.XRANGEPLAIN]}$`);ne("TILDELOOSE",`^${w[k.LONETILDE]}${w[k.XRANGEPLAINLOOSE]}$`);ne("LONECARET","(?:\\^)");ne("CARETTRIM",`(\\s*)${w[k.LONECARET]}\\s+`,!0);zr.caretTrimReplace="$1^";ne("CARET",`^${w[k.LONECARET]}${w[k.XRANGEPLAIN]}$`);ne("CARETLOOSE",`^${w[k.LONECARET]}${w[k.XRANGEPLAINLOOSE]}$`);ne("COMPARATORLOOSE",`^${w[k.GTLT]}\\s*(${w[k.LOOSEPLAIN]})$|^$`);ne("COMPARATOR",`^${w[k.GTLT]}\\s*(${w[k.FULLPLAIN]})$|^$`);ne("COMPARATORTRIM",`(\\s*)${w[k.GTLT]}\\s*(${w[k.LOOSEPLAIN]}|${w[k.XRANGEPLAIN]})`,!0);zr.comparatorTrimReplace="$1$2$3";ne("HYPHENRANGE",`^\\s*(${w[k.XRANGEPLAIN]})\\s+-\\s+(${w[k.XRANGEPLAIN]})\\s*$`);ne("HYPHENRANGELOOSE",`^\\s*(${w[k.XRANGEPLAINLOOSE]})\\s+-\\s+(${w[k.XRANGEPLAINLOOSE]})\\s*$`);ne("STAR","(<|>)?=?\\s*\\*");ne("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");ne("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var wf=m((T2e,Pk)=>{"use strict";var IEe=Object.freeze({loose:!0}),PEe=Object.freeze({}),bEe=t=>t?typeof t!="object"?IEe:t:PEe;Pk.exports=bEe});var kA=m((A2e,Lk)=>{"use strict";var bk=/^[0-9]+$/,Mk=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=bk.test(t),r=bk.test(e);return n&&r&&(t=+t,e=+e),t===e?0:n&&!r?-1:r&&!n?1:t<e?-1:1},MEe=(t,e)=>Mk(e,t);Lk.exports={compareIdentifiers:Mk,rcompareIdentifiers:MEe}});var qt=m((R2e,Dk)=>{"use strict";var kf=Bl(),{MAX_LENGTH:xk,MAX_SAFE_INTEGER:Vf}=Vl(),{safeRe:Bf,t:Gf}=mc(),LEe=wf(),{compareIdentifiers:VA}=kA(),BA=class t{constructor(e,n){if(n=LEe(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>xk)throw new TypeError(`version is longer than ${xk} characters`);kf("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let r=e.trim().match(n.loose?Bf[Gf.LOOSE]:Bf[Gf.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Vf||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Vf||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Vf||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let s=+o;if(s>=0&&s<Vf)return s}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(kf("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let n=0;do{let r=this.prerelease[n],o=e.prerelease[n];if(kf("prerelease compare",n,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return VA(r,o)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let r=this.build[n],o=e.build[n];if(kf("build compare",n,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return VA(r,o)}while(++n)}inc(e,n,r){if(e.startsWith("pre")){if(!n&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let o=`-${n}`.match(this.options.loose?Bf[Gf.PRERELEASELOOSE]:Bf[Gf.PRERELEASE]);if(!o||o[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,r),this.inc("pre",n,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,r),this.inc("pre",n,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(n===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(n){let s=[n,o];r===!1&&(s=[n]),VA(this.prerelease[0],n)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Dk.exports=BA});var ea=m((y2e,wk)=>{"use strict";var Uk=qt(),xEe=(t,e,n=!1)=>{if(t instanceof Uk)return t;try{return new Uk(t,e)}catch(r){if(!n)return null;throw r}};wk.exports=xEe});var Vk=m((O2e,kk)=>{"use strict";var DEe=ea(),UEe=(t,e)=>{let n=DEe(t,e);return n?n.version:null};kk.exports=UEe});var Gk=m((N2e,Bk)=>{"use strict";var wEe=ea(),kEe=(t,e)=>{let n=wEe(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};Bk.exports=kEe});var Fk=m((C2e,$k)=>{"use strict";var Hk=qt(),VEe=(t,e,n,r,o)=>{typeof n=="string"&&(o=r,r=n,n=void 0);try{return new Hk(t instanceof Hk?t.version:t,n).inc(e,r,o).version}catch{return null}};$k.exports=VEe});var Yk=m((v2e,qk)=>{"use strict";var jk=ea(),BEe=(t,e)=>{let n=jk(t,null,!0),r=jk(e,null,!0),o=n.compare(r);if(o===0)return null;let s=o>0,i=s?n:r,a=s?r:n,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let l=c?"pre":"";return n.major!==r.major?l+"major":n.minor!==r.minor?l+"minor":n.patch!==r.patch?l+"patch":"prerelease"};qk.exports=BEe});var Wk=m((I2e,Kk)=>{"use strict";var GEe=qt(),HEe=(t,e)=>new GEe(t,e).major;Kk.exports=HEe});var Xk=m((P2e,zk)=>{"use strict";var $Ee=qt(),FEe=(t,e)=>new $Ee(t,e).minor;zk.exports=FEe});var Zk=m((b2e,Jk)=>{"use strict";var jEe=qt(),qEe=(t,e)=>new jEe(t,e).patch;Jk.exports=qEe});var eV=m((M2e,Qk)=>{"use strict";var YEe=ea(),KEe=(t,e)=>{let n=YEe(t,e);return n&&n.prerelease.length?n.prerelease:null};Qk.exports=KEe});var Jn=m((L2e,nV)=>{"use strict";var tV=qt(),WEe=(t,e,n)=>new tV(t,n).compare(new tV(e,n));nV.exports=WEe});var oV=m((x2e,rV)=>{"use strict";var zEe=Jn(),XEe=(t,e,n)=>zEe(e,t,n);rV.exports=XEe});var iV=m((D2e,sV)=>{"use strict";var JEe=Jn(),ZEe=(t,e)=>JEe(t,e,!0);sV.exports=ZEe});var Hf=m((U2e,cV)=>{"use strict";var aV=qt(),QEe=(t,e,n)=>{let r=new aV(t,n),o=new aV(e,n);return r.compare(o)||r.compareBuild(o)};cV.exports=QEe});var lV=m((w2e,uV)=>{"use strict";var eSe=Hf(),tSe=(t,e)=>t.sort((n,r)=>eSe(n,r,e));uV.exports=tSe});var pV=m((k2e,dV)=>{"use strict";var nSe=Hf(),rSe=(t,e)=>t.sort((n,r)=>nSe(r,n,e));dV.exports=rSe});var Gl=m((V2e,_V)=>{"use strict";var oSe=Jn(),sSe=(t,e,n)=>oSe(t,e,n)>0;_V.exports=sSe});var $f=m((B2e,fV)=>{"use strict";var iSe=Jn(),aSe=(t,e,n)=>iSe(t,e,n)<0;fV.exports=aSe});var GA=m((G2e,mV)=>{"use strict";var cSe=Jn(),uSe=(t,e,n)=>cSe(t,e,n)===0;mV.exports=uSe});var HA=m((H2e,EV)=>{"use strict";var lSe=Jn(),dSe=(t,e,n)=>lSe(t,e,n)!==0;EV.exports=dSe});var Ff=m(($2e,SV)=>{"use strict";var pSe=Jn(),_Se=(t,e,n)=>pSe(t,e,n)>=0;SV.exports=_Se});var jf=m((F2e,gV)=>{"use strict";var fSe=Jn(),mSe=(t,e,n)=>fSe(t,e,n)<=0;gV.exports=mSe});var $A=m((j2e,hV)=>{"use strict";var ESe=GA(),SSe=HA(),gSe=Gl(),hSe=Ff(),TSe=$f(),ASe=jf(),RSe=(t,e,n,r)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return ESe(t,n,r);case"!=":return SSe(t,n,r);case">":return gSe(t,n,r);case">=":return hSe(t,n,r);case"<":return TSe(t,n,r);case"<=":return ASe(t,n,r);default:throw new TypeError(`Invalid operator: ${e}`)}};hV.exports=RSe});var AV=m((q2e,TV)=>{"use strict";var ySe=qt(),OSe=ea(),{safeRe:qf,t:Yf}=mc(),NSe=(t,e)=>{if(t instanceof ySe)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?qf[Yf.COERCEFULL]:qf[Yf.COERCE]);else{let c=e.includePrerelease?qf[Yf.COERCERTLFULL]:qf[Yf.COERCERTL],u;for(;(u=c.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||u.index+u[0].length!==n.index+n[0].length)&&(n=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(n===null)return null;let r=n[2],o=n[3]||"0",s=n[4]||"0",i=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return OSe(`${r}.${o}.${s}${i}${a}`,e)};TV.exports=NSe});var yV=m((Y2e,RV)=>{"use strict";var FA=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let o=this.map.keys().next().value;this.delete(o)}this.map.set(e,n)}return this}};RV.exports=FA});var Zn=m((K2e,vV)=>{"use strict";var CSe=/\s+/g,jA=class t{constructor(e,n){if(n=ISe(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof qA)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(CSe," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(r=>r.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter(o=>!NV(o[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&USe(o[0])){this.set=[o];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let n=this.set[e];for(let r=0;r<n.length;r++)r>0&&(this.formatted+=" "),this.formatted+=n[r].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let r=((this.options.includePrerelease&&xSe)|(this.options.loose&&DSe))+":"+e,o=OV.get(r);if(o)return o;let s=this.options.loose,i=s?on[Yt.HYPHENRANGELOOSE]:on[Yt.HYPHENRANGE];e=e.replace(i,qSe(this.options.includePrerelease)),Le("hyphen replace",e),e=e.replace(on[Yt.COMPARATORTRIM],bSe),Le("comparator trim",e),e=e.replace(on[Yt.TILDETRIM],MSe),Le("tilde trim",e),e=e.replace(on[Yt.CARETTRIM],LSe),Le("caret trim",e);let a=e.split(" ").map(d=>wSe(d,this.options)).join(" ").split(/\s+/).map(d=>jSe(d,this.options));s&&(a=a.filter(d=>(Le("loose invalid filter",d,this.options),!!d.match(on[Yt.COMPARATORLOOSE])))),Le("range list",a);let c=new Map,u=a.map(d=>new qA(d,this.options));for(let d of u){if(NV(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let l=[...c.values()];return OV.set(r,l),l}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(r=>CV(r,n)&&e.set.some(o=>CV(o,n)&&r.every(s=>o.every(i=>s.intersects(i,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new PSe(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(YSe(this.set[n],e,this.options))return!0;return!1}};vV.exports=jA;var vSe=yV(),OV=new vSe,ISe=wf(),qA=Hl(),Le=Bl(),PSe=qt(),{safeRe:on,t:Yt,comparatorTrimReplace:bSe,tildeTrimReplace:MSe,caretTrimReplace:LSe}=mc(),{FLAG_INCLUDE_PRERELEASE:xSe,FLAG_LOOSE:DSe}=Vl(),NV=t=>t.value==="<0.0.0-0",USe=t=>t.value==="",CV=(t,e)=>{let n=!0,r=t.slice(),o=r.pop();for(;n&&r.length;)n=r.every(s=>o.intersects(s,e)),o=r.pop();return n},wSe=(t,e)=>(t=t.replace(on[Yt.BUILD],""),Le("comp",t,e),t=BSe(t,e),Le("caret",t),t=kSe(t,e),Le("tildes",t),t=HSe(t,e),Le("xrange",t),t=FSe(t,e),Le("stars",t),t),sn=t=>!t||t.toLowerCase()==="x"||t==="*",kSe=(t,e)=>t.trim().split(/\s+/).map(n=>VSe(n,e)).join(" "),VSe=(t,e)=>{let n=e.loose?on[Yt.TILDELOOSE]:on[Yt.TILDE];return t.replace(n,(r,o,s,i,a)=>{Le("tilde",t,r,o,s,i,a);let c;return sn(o)?c="":sn(s)?c=`>=${o}.0.0 <${+o+1}.0.0-0`:sn(i)?c=`>=${o}.${s}.0 <${o}.${+s+1}.0-0`:a?(Le("replaceTilde pr",a),c=`>=${o}.${s}.${i}-${a} <${o}.${+s+1}.0-0`):c=`>=${o}.${s}.${i} <${o}.${+s+1}.0-0`,Le("tilde return",c),c})},BSe=(t,e)=>t.trim().split(/\s+/).map(n=>GSe(n,e)).join(" "),GSe=(t,e)=>{Le("caret",t,e);let n=e.loose?on[Yt.CARETLOOSE]:on[Yt.CARET],r=e.includePrerelease?"-0":"";return t.replace(n,(o,s,i,a,c)=>{Le("caret",t,o,s,i,a,c);let u;return sn(s)?u="":sn(i)?u=`>=${s}.0.0${r} <${+s+1}.0.0-0`:sn(a)?s==="0"?u=`>=${s}.${i}.0${r} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${r} <${+s+1}.0.0-0`:c?(Le("replaceCaret pr",c),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${c} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${c} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${c} <${+s+1}.0.0-0`):(Le("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${r} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${r} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),Le("caret return",u),u})},HSe=(t,e)=>(Le("replaceXRanges",t,e),t.split(/\s+/).map(n=>$Se(n,e)).join(" ")),$Se=(t,e)=>{t=t.trim();let n=e.loose?on[Yt.XRANGELOOSE]:on[Yt.XRANGE];return t.replace(n,(r,o,s,i,a,c)=>{Le("xRange",t,r,o,s,i,a,c);let u=sn(s),l=u||sn(i),d=l||sn(a),p=d;return o==="="&&p&&(o=""),c=e.includePrerelease?"-0":"",u?o===">"||o==="<"?r="<0.0.0-0":r="*":o&&p?(l&&(i=0),a=0,o===">"?(o=">=",l?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):o==="<="&&(o="<",l?s=+s+1:i=+i+1),o==="<"&&(c="-0"),r=`${o+s}.${i}.${a}${c}`):l?r=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(r=`>=${s}.${i}.0${c} <${s}.${+i+1}.0-0`),Le("xRange return",r),r})},FSe=(t,e)=>(Le("replaceStars",t,e),t.trim().replace(on[Yt.STAR],"")),jSe=(t,e)=>(Le("replaceGTE0",t,e),t.trim().replace(on[e.includePrerelease?Yt.GTE0PRE:Yt.GTE0],"")),qSe=t=>(e,n,r,o,s,i,a,c,u,l,d,p)=>(sn(r)?n="":sn(o)?n=`>=${r}.0.0${t?"-0":""}`:sn(s)?n=`>=${r}.${o}.0${t?"-0":""}`:i?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,sn(u)?c="":sn(l)?c=`<${+u+1}.0.0-0`:sn(d)?c=`<${u}.${+l+1}.0-0`:p?c=`<=${u}.${l}.${d}-${p}`:t?c=`<${u}.${l}.${+d+1}-0`:c=`<=${c}`,`${n} ${c}`.trim()),YSe=(t,e,n)=>{for(let r=0;r<t.length;r++)if(!t[r].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let r=0;r<t.length;r++)if(Le(t[r].semver),t[r].semver!==qA.ANY&&t[r].semver.prerelease.length>0){let o=t[r].semver;if(o.major===e.major&&o.minor===e.minor&&o.patch===e.patch)return!0}return!1}return!0}});var Hl=m((W2e,xV)=>{"use strict";var $l=Symbol("SemVer ANY"),WA=class t{static get ANY(){return $l}constructor(e,n){if(n=IV(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),KA("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===$l?this.value="":this.value=this.operator+this.semver.version,KA("comp",this)}parse(e){let n=this.options.loose?PV[bV.COMPARATORLOOSE]:PV[bV.COMPARATOR],r=e.match(n);if(!r)throw new TypeError(`Invalid comparator: ${e}`);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new MV(r[2],this.options.loose):this.semver=$l}toString(){return this.value}test(e){if(KA("Comparator.test",e,this.options.loose),this.semver===$l||e===$l)return!0;if(typeof e=="string")try{e=new MV(e,this.options)}catch{return!1}return YA(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new LV(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new LV(this.value,n).test(e.semver):(n=IV(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||YA(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||YA(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};xV.exports=WA;var IV=wf(),{safeRe:PV,t:bV}=mc(),YA=$A(),KA=Bl(),MV=qt(),LV=Zn()});var Fl=m((z2e,DV)=>{"use strict";var KSe=Zn(),WSe=(t,e,n)=>{try{e=new KSe(e,n)}catch{return!1}return e.test(t)};DV.exports=WSe});var wV=m((X2e,UV)=>{"use strict";var zSe=Zn(),XSe=(t,e)=>new zSe(t,e).set.map(n=>n.map(r=>r.value).join(" ").trim().split(" "));UV.exports=XSe});var VV=m((J2e,kV)=>{"use strict";var JSe=qt(),ZSe=Zn(),QSe=(t,e,n)=>{let r=null,o=null,s=null;try{s=new ZSe(e,n)}catch{return null}return t.forEach(i=>{s.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new JSe(r,n))}),r};kV.exports=QSe});var GV=m((Z2e,BV)=>{"use strict";var ege=qt(),tge=Zn(),nge=(t,e,n)=>{let r=null,o=null,s=null;try{s=new tge(e,n)}catch{return null}return t.forEach(i=>{s.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new ege(r,n))}),r};BV.exports=nge});var FV=m((Q2e,$V)=>{"use strict";var zA=qt(),rge=Zn(),HV=Gl(),oge=(t,e)=>{t=new rge(t,e);let n=new zA("0.0.0");if(t.test(n)||(n=new zA("0.0.0-0"),t.test(n)))return n;n=null;for(let r=0;r<t.set.length;++r){let o=t.set[r],s=null;o.forEach(i=>{let a=new zA(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||HV(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!n||HV(n,s))&&(n=s)}return n&&t.test(n)?n:null};$V.exports=oge});var qV=m((e4e,jV)=>{"use strict";var sge=Zn(),ige=(t,e)=>{try{return new sge(t,e).range||"*"}catch{return null}};jV.exports=ige});var Kf=m((t4e,zV)=>{"use strict";var age=qt(),WV=Hl(),{ANY:cge}=WV,uge=Zn(),lge=Fl(),YV=Gl(),KV=$f(),dge=jf(),pge=Ff(),_ge=(t,e,n,r)=>{t=new age(t,r),e=new uge(e,r);let o,s,i,a,c;switch(n){case">":o=YV,s=dge,i=KV,a=">",c=">=";break;case"<":o=KV,s=pge,i=YV,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(lge(t,e,r))return!1;for(let u=0;u<e.set.length;++u){let l=e.set[u],d=null,p=null;if(l.forEach(_=>{_.semver===cge&&(_=new WV(">=0.0.0")),d=d||_,p=p||_,o(_.semver,d.semver,r)?d=_:i(_.semver,p.semver,r)&&(p=_)}),d.operator===a||d.operator===c||(!p.operator||p.operator===a)&&s(t,p.semver))return!1;if(p.operator===c&&i(t,p.semver))return!1}return!0};zV.exports=_ge});var JV=m((n4e,XV)=>{"use strict";var fge=Kf(),mge=(t,e,n)=>fge(t,e,">",n);XV.exports=mge});var QV=m((r4e,ZV)=>{"use strict";var Ege=Kf(),Sge=(t,e,n)=>Ege(t,e,"<",n);ZV.exports=Sge});var nB=m((o4e,tB)=>{"use strict";var eB=Zn(),gge=(t,e,n)=>(t=new eB(t,n),e=new eB(e,n),t.intersects(e,n));tB.exports=gge});var oB=m((s4e,rB)=>{"use strict";var hge=Fl(),Tge=Jn();rB.exports=(t,e,n)=>{let r=[],o=null,s=null,i=t.sort((l,d)=>Tge(l,d,n));for(let l of i)hge(l,e,n)?(s=l,o||(o=l)):(s&&r.push([o,s]),s=null,o=null);o&&r.push([o,null]);let a=[];for(let[l,d]of r)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);let c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e}});var lB=m((i4e,uB)=>{"use strict";var sB=Zn(),JA=Hl(),{ANY:XA}=JA,jl=Fl(),ZA=Jn(),Age=(t,e,n={})=>{if(t===e)return!0;t=new sB(t,n),e=new sB(e,n);let r=!1;e:for(let o of t.set){for(let s of e.set){let i=yge(o,s,n);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Rge=[new JA(">=0.0.0-0")],iB=[new JA(">=0.0.0")],yge=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===XA){if(e.length===1&&e[0].semver===XA)return!0;n.includePrerelease?t=Rge:t=iB}if(e.length===1&&e[0].semver===XA){if(n.includePrerelease)return!0;e=iB}let r=new Set,o,s;for(let _ of t)_.operator===">"||_.operator===">="?o=aB(o,_,n):_.operator==="<"||_.operator==="<="?s=cB(s,_,n):r.add(_.semver);if(r.size>1)return null;let i;if(o&&s){if(i=ZA(o.semver,s.semver,n),i>0)return null;if(i===0&&(o.operator!==">="||s.operator!=="<="))return null}for(let _ of r){if(o&&!jl(_,String(o),n)||s&&!jl(_,String(s),n))return null;for(let f of e)if(!jl(_,String(f),n))return!1;return!0}let a,c,u,l,d=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1,p=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let _ of e){if(l=l||_.operator===">"||_.operator===">=",u=u||_.operator==="<"||_.operator==="<=",o){if(p&&_.semver.prerelease&&_.semver.prerelease.length&&_.semver.major===p.major&&_.semver.minor===p.minor&&_.semver.patch===p.patch&&(p=!1),_.operator===">"||_.operator===">="){if(a=aB(o,_,n),a===_&&a!==o)return!1}else if(o.operator===">="&&!jl(o.semver,String(_),n))return!1}if(s){if(d&&_.semver.prerelease&&_.semver.prerelease.length&&_.semver.major===d.major&&_.semver.minor===d.minor&&_.semver.patch===d.patch&&(d=!1),_.operator==="<"||_.operator==="<="){if(c=cB(s,_,n),c===_&&c!==s)return!1}else if(s.operator==="<="&&!jl(s.semver,String(_),n))return!1}if(!_.operator&&(s||o)&&i!==0)return!1}return!(o&&u&&!s&&i!==0||s&&l&&!o&&i!==0||p||d)},aB=(t,e,n)=>{if(!t)return e;let r=ZA(t.semver,e.semver,n);return r>0?t:r<0||e.operator===">"&&t.operator===">="?e:t},cB=(t,e,n)=>{if(!t)return e;let r=ZA(t.semver,e.semver,n);return r<0?t:r>0||e.operator==="<"&&t.operator==="<="?e:t};uB.exports=Age});var eR=m((a4e,_B)=>{"use strict";var QA=mc(),dB=Vl(),Oge=qt(),pB=kA(),Nge=ea(),Cge=Vk(),vge=Gk(),Ige=Fk(),Pge=Yk(),bge=Wk(),Mge=Xk(),Lge=Zk(),xge=eV(),Dge=Jn(),Uge=oV(),wge=iV(),kge=Hf(),Vge=lV(),Bge=pV(),Gge=Gl(),Hge=$f(),$ge=GA(),Fge=HA(),jge=Ff(),qge=jf(),Yge=$A(),Kge=AV(),Wge=Hl(),zge=Zn(),Xge=Fl(),Jge=wV(),Zge=VV(),Qge=GV(),ehe=FV(),the=qV(),nhe=Kf(),rhe=JV(),ohe=QV(),she=nB(),ihe=oB(),ahe=lB();_B.exports={parse:Nge,valid:Cge,clean:vge,inc:Ige,diff:Pge,major:bge,minor:Mge,patch:Lge,prerelease:xge,compare:Dge,rcompare:Uge,compareLoose:wge,compareBuild:kge,sort:Vge,rsort:Bge,gt:Gge,lt:Hge,eq:$ge,neq:Fge,gte:jge,lte:qge,cmp:Yge,coerce:Kge,Comparator:Wge,Range:zge,satisfies:Xge,toComparators:Jge,maxSatisfying:Zge,minSatisfying:Qge,minVersion:ehe,validRange:the,outside:nhe,gtr:rhe,ltr:ohe,intersects:she,simplifyRange:ihe,subset:ahe,SemVer:Oge,re:QA.re,src:QA.src,tokens:QA.t,SEMVER_SPEC_VERSION:dB.SEMVER_SPEC_VERSION,RELEASE_TYPES:dB.RELEASE_TYPES,compareIdentifiers:pB.compareIdentifiers,rcompareIdentifiers:pB.rcompareIdentifiers}});var fB=m(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});Wf.VERSION=void 0;Wf.VERSION="0.57.2"});var mB=m(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});ql.SeverityNumber=void 0;var che;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.TRACE=1]="TRACE",t[t.TRACE2=2]="TRACE2",t[t.TRACE3=3]="TRACE3",t[t.TRACE4=4]="TRACE4",t[t.DEBUG=5]="DEBUG",t[t.DEBUG2=6]="DEBUG2",t[t.DEBUG3=7]="DEBUG3",t[t.DEBUG4=8]="DEBUG4",t[t.INFO=9]="INFO",t[t.INFO2=10]="INFO2",t[t.INFO3=11]="INFO3",t[t.INFO4=12]="INFO4",t[t.WARN=13]="WARN",t[t.WARN2=14]="WARN2",t[t.WARN3=15]="WARN3",t[t.WARN4=16]="WARN4",t[t.ERROR=17]="ERROR",t[t.ERROR2=18]="ERROR2",t[t.ERROR3=19]="ERROR3",t[t.ERROR4=20]="ERROR4",t[t.FATAL=21]="FATAL",t[t.FATAL2=22]="FATAL2",t[t.FATAL3=23]="FATAL3",t[t.FATAL4=24]="FATAL4"})(che=ql.SeverityNumber||(ql.SeverityNumber={}))});var Xf=m(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.NOOP_LOGGER=Ec.NoopLogger=void 0;var zf=class{emit(e){}};Ec.NoopLogger=zf;Ec.NOOP_LOGGER=new zf});var Zf=m(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.NOOP_LOGGER_PROVIDER=Sc.NoopLoggerProvider=void 0;var uhe=Xf(),Jf=class{getLogger(e,n,r){return new uhe.NoopLogger}};Sc.NoopLoggerProvider=Jf;Sc.NOOP_LOGGER_PROVIDER=new Jf});var nR=m(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});Qf.ProxyLogger=void 0;var lhe=Xf(),tR=class{constructor(e,n,r,o){this._provider=e,this.name=n,this.version=r,this.options=o}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):lhe.NOOP_LOGGER}};Qf.ProxyLogger=tR});var oR=m(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.ProxyLoggerProvider=void 0;var dhe=Zf(),phe=nR(),rR=class{getLogger(e,n,r){var o;return(o=this.getDelegateLogger(e,n,r))!==null&&o!==void 0?o:new phe.ProxyLogger(this,e,n,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:dhe.NOOP_LOGGER_PROVIDER}setDelegate(e){this._delegate=e}getDelegateLogger(e,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getLogger(e,n,r)}};em.ProxyLoggerProvider=rR});var EB=m(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});tm._globalThis=void 0;tm._globalThis=typeof globalThis=="object"?globalThis:global});var SB=m(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm._globalThis=void 0;var _he=EB();Object.defineProperty(nm,"_globalThis",{enumerable:!0,get:function(){return _he._globalThis}})});var gB=m(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});rm._globalThis=void 0;var fhe=SB();Object.defineProperty(rm,"_globalThis",{enumerable:!0,get:function(){return fhe._globalThis}})});var hB=m(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.API_BACKWARDS_COMPATIBILITY_VERSION=Xr.makeGetter=Xr._global=Xr.GLOBAL_LOGS_API_KEY=void 0;var mhe=gB();Xr.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");Xr._global=mhe._globalThis;function Ehe(t,e,n){return r=>r===t?e:n}Xr.makeGetter=Ehe;Xr.API_BACKWARDS_COMPATIBILITY_VERSION=1});var AB=m(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});om.LogsAPI=void 0;var Qn=hB(),She=Zf(),TB=oR(),sR=class t{constructor(){this._proxyLoggerProvider=new TB.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return Qn._global[Qn.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(Qn._global[Qn.GLOBAL_LOGS_API_KEY]=(0,Qn.makeGetter)(Qn.API_BACKWARDS_COMPATIBILITY_VERSION,e,She.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,n;return(n=(e=Qn._global[Qn.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(Qn._global,Qn.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&n!==void 0?n:this._proxyLoggerProvider}getLogger(e,n,r){return this.getLoggerProvider().getLogger(e,n,r)}disable(){delete Qn._global[Qn.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new TB.ProxyLoggerProvider}};om.LogsAPI=sR});var iR=m(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.logs=Ot.ProxyLoggerProvider=Ot.ProxyLogger=Ot.NoopLoggerProvider=Ot.NOOP_LOGGER_PROVIDER=Ot.NoopLogger=Ot.NOOP_LOGGER=Ot.SeverityNumber=void 0;var ghe=mB();Object.defineProperty(Ot,"SeverityNumber",{enumerable:!0,get:function(){return ghe.SeverityNumber}});var RB=Xf();Object.defineProperty(Ot,"NOOP_LOGGER",{enumerable:!0,get:function(){return RB.NOOP_LOGGER}});Object.defineProperty(Ot,"NoopLogger",{enumerable:!0,get:function(){return RB.NoopLogger}});var yB=Zf();Object.defineProperty(Ot,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return yB.NOOP_LOGGER_PROVIDER}});Object.defineProperty(Ot,"NoopLoggerProvider",{enumerable:!0,get:function(){return yB.NoopLoggerProvider}});var hhe=nR();Object.defineProperty(Ot,"ProxyLogger",{enumerable:!0,get:function(){return hhe.ProxyLogger}});var The=oR();Object.defineProperty(Ot,"ProxyLoggerProvider",{enumerable:!0,get:function(){return The.ProxyLoggerProvider}});var Ahe=AB();Ot.logs=Ahe.LogsAPI.getInstance()});var OB=m(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.disableInstrumentations=gc.enableInstrumentations=void 0;function Rhe(t,e,n,r){for(let o=0,s=t.length;o<s;o++){let i=t[o];e&&i.setTracerProvider(e),n&&i.setMeterProvider(n),r&&i.setLoggerProvider&&i.setLoggerProvider(r),i.getConfig().enabled||i.enable()}}gc.enableInstrumentations=Rhe;function yhe(t){t.forEach(e=>e.disable())}gc.disableInstrumentations=yhe});var vB=m(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});sm.registerInstrumentations=void 0;var NB=(x(),b(B)),Ohe=iR(),CB=OB();function Nhe(t){var e,n;let r=t.tracerProvider||NB.trace.getTracerProvider(),o=t.meterProvider||NB.metrics.getMeterProvider(),s=t.loggerProvider||Ohe.logs.getLoggerProvider(),i=(n=(e=t.instrumentations)===null||e===void 0?void 0:e.flat())!==null&&n!==void 0?n:[];return(0,CB.enableInstrumentations)(i,r,o,s),()=>{(0,CB.disableInstrumentations)(i)}}sm.registerInstrumentations=Nhe});var cR=m((R4e,bB)=>{"use strict";function aR(t){return typeof t=="function"}var an=console.error.bind(console);function Yl(t,e,n){var r=!!t[e]&&t.propertyIsEnumerable(e);Object.defineProperty(t,e,{configurable:!0,enumerable:r,writable:!0,value:n})}function Kl(t){t&&t.logger&&(aR(t.logger)?an=t.logger:an("new logger isn't a function, not replacing"))}function IB(t,e,n){if(!t||!t[e]){an("no original function "+e+" to wrap");return}if(!n){an("no wrapper function"),an(new Error().stack);return}if(!aR(t[e])||!aR(n)){an("original object and wrapper must be functions");return}var r=t[e],o=n(r,e);return Yl(o,"__original",r),Yl(o,"__unwrap",function(){t[e]===o&&Yl(t,e,r)}),Yl(o,"__wrapped",!0),Yl(t,e,o),o}function Che(t,e,n){if(t)Array.isArray(t)||(t=[t]);else{an("must provide one or more modules to patch"),an(new Error().stack);return}if(!(e&&Array.isArray(e))){an("must provide one or more functions to wrap on modules");return}t.forEach(function(r){e.forEach(function(o){IB(r,o,n)})})}function PB(t,e){if(!t||!t[e]){an("no function to unwrap."),an(new Error().stack);return}if(!t[e].__unwrap)an("no original to unwrap to -- has "+e+" already been unwrapped?");else return t[e].__unwrap()}function vhe(t,e){if(t)Array.isArray(t)||(t=[t]);else{an("must provide one or more modules to patch"),an(new Error().stack);return}if(!(e&&Array.isArray(e))){an("must provide one or more functions to unwrap on modules");return}t.forEach(function(n){e.forEach(function(r){PB(n,r)})})}Kl.wrap=IB;Kl.massWrap=Che;Kl.unwrap=PB;Kl.massUnwrap=vhe;bB.exports=Kl});var MB=m(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});am.InstrumentationAbstract=void 0;var uR=(x(),b(B)),Ihe=iR(),im=cR(),lR=class{constructor(e,n,r){this.instrumentationName=e,this.instrumentationVersion=n,this._config={},this._wrap=im.wrap,this._unwrap=im.unwrap,this._massWrap=im.massWrap,this._massUnwrap=im.massUnwrap,this.setConfig(r),this._diag=uR.diag.createComponentLogger({namespace:e}),this._tracer=uR.trace.getTracer(e,n),this._meter=uR.metrics.getMeter(e,n),this._logger=Ihe.logs.getLogger(e,n),this._updateMetricInstruments()}get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){var e;let n=(e=this.init())!==null&&e!==void 0?e:[];return Array.isArray(n)?n:[n]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config=Object.assign({enabled:!0},e)}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,n,r,o){if(e)try{e(r,o)}catch(s){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:n},s)}}};am.InstrumentationAbstract=lR});var xB=m((O4e,LB)=>{var hc=1e3,Tc=hc*60,Ac=Tc*60,ta=Ac*24,Phe=ta*7,bhe=ta*365.25;LB.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return Mhe(t);if(n==="number"&&isFinite(t))return e.long?xhe(t):Lhe(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Mhe(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*bhe;case"weeks":case"week":case"w":return n*Phe;case"days":case"day":case"d":return n*ta;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Ac;case"minutes":case"minute":case"mins":case"min":case"m":return n*Tc;case"seconds":case"second":case"secs":case"sec":case"s":return n*hc;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function Lhe(t){var e=Math.abs(t);return e>=ta?Math.round(t/ta)+"d":e>=Ac?Math.round(t/Ac)+"h":e>=Tc?Math.round(t/Tc)+"m":e>=hc?Math.round(t/hc)+"s":t+"ms"}function xhe(t){var e=Math.abs(t);return e>=ta?cm(t,e,ta,"day"):e>=Ac?cm(t,e,Ac,"hour"):e>=Tc?cm(t,e,Tc,"minute"):e>=hc?cm(t,e,hc,"second"):t+" ms"}function cm(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var dR=m((N4e,DB)=>{function Dhe(t){n.debug=n,n.default=n,n.coerce=c,n.disable=i,n.enable=o,n.enabled=a,n.humanize=xB(),n.destroy=u,Object.keys(t).forEach(l=>{n[l]=t[l]}),n.names=[],n.skips=[],n.formatters={};function e(l){let d=0;for(let p=0;p<l.length;p++)d=(d<<5)-d+l.charCodeAt(p),d|=0;return n.colors[Math.abs(d)%n.colors.length]}n.selectColor=e;function n(l){let d,p=null,_,f;function E(...S){if(!E.enabled)return;let h=E,R=Number(new Date),A=R-(d||R);h.diff=A,h.prev=d,h.curr=R,d=R,S[0]=n.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let O=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(M,I)=>{if(M==="%%")return"%";O++;let J=n.formatters[I];if(typeof J=="function"){let H=S[O];M=J.call(h,H),S.splice(O,1),O--}return M}),n.formatArgs.call(h,S),(h.log||n.log).apply(h,S)}return E.namespace=l,E.useColors=n.useColors(),E.color=n.selectColor(l),E.extend=r,E.destroy=n.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(_!==n.namespaces&&(_=n.namespaces,f=n.enabled(l)),f),set:S=>{p=S}}),typeof n.init=="function"&&n.init(E),E}function r(l,d){let p=n(this.namespace+(typeof d>"u"?":":d)+l);return p.log=this.log,p}function o(l){n.save(l),n.namespaces=l,n.names=[],n.skips=[];let d=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of d)p[0]==="-"?n.skips.push(p.slice(1)):n.names.push(p)}function s(l,d){let p=0,_=0,f=-1,E=0;for(;p<l.length;)if(_<d.length&&(d[_]===l[p]||d[_]==="*"))d[_]==="*"?(f=_,E=p,_++):(p++,_++);else if(f!==-1)_=f+1,E++,p=E;else return!1;for(;_<d.length&&d[_]==="*";)_++;return _===d.length}function i(){let l=[...n.names,...n.skips.map(d=>"-"+d)].join(",");return n.enable(""),l}function a(l){for(let d of n.skips)if(s(l,d))return!1;for(let d of n.names)if(s(l,d))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}DB.exports=Dhe});var UB=m((Tn,um)=>{Tn.formatArgs=whe;Tn.save=khe;Tn.load=Vhe;Tn.useColors=Uhe;Tn.storage=Bhe();Tn.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Tn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Uhe(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function whe(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+um.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}Tn.log=console.debug||console.log||(()=>{});function khe(t){try{t?Tn.storage.setItem("debug",t):Tn.storage.removeItem("debug")}catch{}}function Vhe(){let t;try{t=Tn.storage.getItem("debug")||Tn.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Bhe(){try{return localStorage}catch{}}um.exports=dR()(Tn);var{formatters:Ghe}=um.exports;Ghe.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var kB=m((C4e,wB)=>{"use strict";wB.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var GB=m((v4e,BB)=>{"use strict";var Hhe=require("os"),VB=require("tty"),er=kB(),{env:Nt}=process,bs;er("no-color")||er("no-colors")||er("color=false")||er("color=never")?bs=0:(er("color")||er("colors")||er("color=true")||er("color=always"))&&(bs=1);"FORCE_COLOR"in Nt&&(Nt.FORCE_COLOR==="true"?bs=1:Nt.FORCE_COLOR==="false"?bs=0:bs=Nt.FORCE_COLOR.length===0?1:Math.min(parseInt(Nt.FORCE_COLOR,10),3));function pR(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function _R(t,e){if(bs===0)return 0;if(er("color=16m")||er("color=full")||er("color=truecolor"))return 3;if(er("color=256"))return 2;if(t&&!e&&bs===void 0)return 0;let n=bs||0;if(Nt.TERM==="dumb")return n;if(process.platform==="win32"){let r=Hhe.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Nt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Nt)||Nt.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Nt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Nt.TEAMCITY_VERSION)?1:0;if(Nt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Nt){let r=parseInt((Nt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Nt.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Nt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Nt.TERM)||"COLORTERM"in Nt?1:n}function $he(t){let e=_R(t,t&&t.isTTY);return pR(e)}BB.exports={supportsColor:$he,stdout:pR(_R(!0,VB.isatty(1))),stderr:pR(_R(!0,VB.isatty(2)))}});var $B=m((Ct,dm)=>{var Fhe=require("tty"),lm=require("util");Ct.init=Xhe;Ct.log=Khe;Ct.formatArgs=qhe;Ct.save=Whe;Ct.load=zhe;Ct.useColors=jhe;Ct.destroy=lm.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ct.colors=[6,2,3,4,5,1];try{let t=GB();t&&(t.stderr||t).level>=2&&(Ct.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ct.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function jhe(){return"colors"in Ct.inspectOpts?!!Ct.inspectOpts.colors:Fhe.isatty(process.stderr.fd)}function qhe(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
2
- `).join(`
3
- `+s),t.push(o+"m+"+dm.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Yhe()+e+" "+t[0]}function Yhe(){return Ct.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Khe(...t){return process.stderr.write(lm.formatWithOptions(Ct.inspectOpts,...t)+`
4
- `)}function Whe(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function zhe(){return process.env.DEBUG}function Xhe(t){t.inspectOpts={};let e=Object.keys(Ct.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=Ct.inspectOpts[e[n]]}dm.exports=dR()(Ct);var{formatters:HB}=dm.exports;HB.o=function(t){return this.inspectOpts.colors=this.useColors,lm.inspect(t,this.inspectOpts).split(`
5
- `).map(e=>e.trim()).join(" ")};HB.O=function(t){return this.inspectOpts.colors=this.useColors,lm.inspect(t,this.inspectOpts)}});var FB=m((I4e,fR)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?fR.exports=UB():fR.exports=$B()});var ER=m((P4e,jB)=>{"use strict";var mR=require("path").sep;jB.exports=function(t){var e=t.split(mR),n=e.lastIndexOf("node_modules");if(n!==-1&&e[n+1]){for(var r=e[n+1][0]==="@",o=r?e[n+1]+"/"+e[n+2]:e[n+1],s=r?3:2,i="",a=n+s-1,c=0;c<=a;c++)c===a?i+=e[c]:i+=e[c]+mR;for(var u="",l=e.length-1,d=n+s;d<=l;d++)d===l?u+=e[d]:u+=e[d]+mR;return{name:o,basedir:i,path:u}}}});var SR=m((b4e,qB)=>{"use strict";var Jhe=require("os");qB.exports=Jhe.homedir||function(){var e=process.env.HOME,n=process.env.LOGNAME||process.env.USER||process.env.LNAME||process.env.USERNAME;return process.platform==="win32"?process.env.USERPROFILE||process.env.HOMEDRIVE&&process.env.HOMEPATH&&process.env.HOMEDRIVE+process.env.HOMEPATH||e||null:process.platform==="darwin"?e||(n?"/Users/"+n:null):process.platform==="linux"?e||(process.getuid()===0?"/root":n?"/home/"+n:null):e||null}});var pm=m((M4e,YB)=>{"use strict";YB.exports=Error});var gR=m((L4e,KB)=>{"use strict";var _m=pm();KB.exports=function(){var t=_m.prepareStackTrace;_m.prepareStackTrace=function(n,r){return r};var e=new _m().stack;return _m.prepareStackTrace=t,e[2].getFileName()}});var WB=m((x4e,Wl)=>{"use strict";var Zhe=process.platform==="win32",Qhe=/^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/,hR={};function eTe(t){return Qhe.exec(t).slice(1)}hR.parse=function(t){if(typeof t!="string")throw new TypeError("Parameter 'pathString' must be a string, not "+typeof t);var e=eTe(t);if(!e||e.length!==5)throw new TypeError("Invalid path '"+t+"'");return{root:e[1],dir:e[0]===e[1]?e[0]:e[0].slice(0,-1),base:e[2],ext:e[4],name:e[3]}};var tTe=/^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/,TR={};function nTe(t){return tTe.exec(t).slice(1)}TR.parse=function(t){if(typeof t!="string")throw new TypeError("Parameter 'pathString' must be a string, not "+typeof t);var e=nTe(t);if(!e||e.length!==5)throw new TypeError("Invalid path '"+t+"'");return{root:e[1],dir:e[0].slice(0,-1),base:e[2],ext:e[4],name:e[3]}};Zhe?Wl.exports=hR.parse:Wl.exports=TR.parse;Wl.exports.posix=TR.parse;Wl.exports.win32=hR.parse});var AR=m((D4e,ZB)=>{var JB=require("path"),zB=JB.parse||WB(),rTe=/^([A-Za-z]:)/,oTe=/^\\\\/;function XB(t,e){var n="/";rTe.test(t)?n="":oTe.test(t)&&(n="\\\\");for(var r=[t],o=zB(t);o.dir!==r[r.length-1];)r.push(o.dir),o=zB(o.dir);return r.reduce(function(s,i){return s.concat(e.map(function(a){return JB.resolve(n,i,a)}))},[])}ZB.exports=function(e,n,r){var o=n&&n.moduleDirectory?[].concat(n.moduleDirectory):["node_modules"];if(n&&typeof n.paths=="function")return n.paths(r,e,function(){return XB(e,o)},n);var s=XB(e,o);return n&&n.paths?s.concat(n.paths):s}});var RR=m((U4e,QB)=>{QB.exports=function(t,e){return e||{}}});var nG=m((w4e,tG)=>{"use strict";var sTe="Function.prototype.bind called on incompatible ",iTe=Object.prototype.toString,aTe=Math.max,cTe="[object Function]",eG=function(e,n){for(var r=[],o=0;o<e.length;o+=1)r[o]=e[o];for(var s=0;s<n.length;s+=1)r[s+e.length]=n[s];return r},uTe=function(e,n){for(var r=[],o=n||0,s=0;o<e.length;o+=1,s+=1)r[s]=e[o];return r},lTe=function(t,e){for(var n="",r=0;r<t.length;r+=1)n+=t[r],r+1<t.length&&(n+=e);return n};tG.exports=function(e){var n=this;if(typeof n!="function"||iTe.apply(n)!==cTe)throw new TypeError(sTe+n);for(var r=uTe(arguments,1),o,s=function(){if(this instanceof o){var l=n.apply(this,eG(r,arguments));return Object(l)===l?l:this}return n.apply(e,eG(r,arguments))},i=aTe(0,n.length-r.length),a=[],c=0;c<i;c++)a[c]="$"+c;if(o=Function("binder","return function ("+lTe(a,",")+"){ return binder.apply(this,arguments); }")(s),n.prototype){var u=function(){};u.prototype=n.prototype,o.prototype=new u,u.prototype=null}return o}});var oG=m((k4e,rG)=>{"use strict";var dTe=nG();rG.exports=Function.prototype.bind||dTe});var iG=m((V4e,sG)=>{"use strict";var pTe=Function.prototype.call,_Te=Object.prototype.hasOwnProperty,fTe=oG();sG.exports=fTe.call(pTe,_Te)});var aG=m((B4e,mTe)=>{mTe.exports={assert:!0,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16",async_hooks:">= 8","node:async_hooks":[">= 14.18 && < 15",">= 16"],buffer_ieee754:">= 0.5 && < 0.9.7",buffer:!0,"node:buffer":[">= 14.18 && < 15",">= 16"],child_process:!0,"node:child_process":[">= 14.18 && < 15",">= 16"],cluster:">= 0.5","node:cluster":[">= 14.18 && < 15",">= 16"],console:!0,"node:console":[">= 14.18 && < 15",">= 16"],constants:!0,"node:constants":[">= 14.18 && < 15",">= 16"],crypto:!0,"node:crypto":[">= 14.18 && < 15",">= 16"],_debug_agent:">= 1 && < 8",_debugger:"< 8",dgram:!0,"node:dgram":[">= 14.18 && < 15",">= 16"],diagnostics_channel:[">= 14.17 && < 15",">= 15.1"],"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],dns:!0,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16",domain:">= 0.7.12","node:domain":[">= 14.18 && < 15",">= 16"],events:!0,"node:events":[">= 14.18 && < 15",">= 16"],freelist:"< 6",fs:!0,"node:fs":[">= 14.18 && < 15",">= 16"],"fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],_http_agent:">= 0.11.1","node:_http_agent":[">= 14.18 && < 15",">= 16"],_http_client:">= 0.11.1","node:_http_client":[">= 14.18 && < 15",">= 16"],_http_common:">= 0.11.1","node:_http_common":[">= 14.18 && < 15",">= 16"],_http_incoming:">= 0.11.1","node:_http_incoming":[">= 14.18 && < 15",">= 16"],_http_outgoing:">= 0.11.1","node:_http_outgoing":[">= 14.18 && < 15",">= 16"],_http_server:">= 0.11.1","node:_http_server":[">= 14.18 && < 15",">= 16"],http:!0,"node:http":[">= 14.18 && < 15",">= 16"],http2:">= 8.8","node:http2":[">= 14.18 && < 15",">= 16"],https:!0,"node:https":[">= 14.18 && < 15",">= 16"],inspector:">= 8","node:inspector":[">= 14.18 && < 15",">= 16"],"inspector/promises":[">= 19"],"node:inspector/promises":[">= 19"],_linklist:"< 8",module:!0,"node:module":[">= 14.18 && < 15",">= 16"],net:!0,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12",os:!0,"node:os":[">= 14.18 && < 15",">= 16"],path:!0,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16",perf_hooks:">= 8.5","node:perf_hooks":[">= 14.18 && < 15",">= 16"],process:">= 1","node:process":[">= 14.18 && < 15",">= 16"],punycode:">= 0.5","node:punycode":[">= 14.18 && < 15",">= 16"],querystring:!0,"node:querystring":[">= 14.18 && < 15",">= 16"],readline:!0,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17",repl:!0,"node:repl":[">= 14.18 && < 15",">= 16"],"node:sea":[">= 20.12 && < 21",">= 21.7"],smalloc:">= 0.11.5 && < 3","node:sqlite":[">= 22.13 && < 23",">= 23.4"],_stream_duplex:">= 0.9.4","node:_stream_duplex":[">= 14.18 && < 15",">= 16"],_stream_transform:">= 0.9.4","node:_stream_transform":[">= 14.18 && < 15",">= 16"],_stream_wrap:">= 1.4.1","node:_stream_wrap":[">= 14.18 && < 15",">= 16"],_stream_passthrough:">= 0.9.4","node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],_stream_readable:">= 0.9.4","node:_stream_readable":[">= 14.18 && < 15",">= 16"],_stream_writable:">= 0.9.4","node:_stream_writable":[">= 14.18 && < 15",">= 16"],stream:!0,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5",string_decoder:!0,"node:string_decoder":[">= 14.18 && < 15",">= 16"],sys:[">= 0.4 && < 0.7",">= 0.8"],"node:sys":[">= 14.18 && < 15",">= 16"],"test/reporters":">= 19.9 && < 20.2","node:test/reporters":[">= 18.17 && < 19",">= 19.9",">= 20"],"test/mock_loader":">= 22.3 && < 22.7","node:test/mock_loader":">= 22.3 && < 22.7","node:test":[">= 16.17 && < 17",">= 18"],timers:!0,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16",_tls_common:">= 0.11.13","node:_tls_common":[">= 14.18 && < 15",">= 16"],_tls_legacy:">= 0.11.3 && < 10",_tls_wrap:">= 0.11.3","node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls:!0,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events:">= 10","node:trace_events":[">= 14.18 && < 15",">= 16"],tty:!0,"node:tty":[">= 14.18 && < 15",">= 16"],url:!0,"node:url":[">= 14.18 && < 15",">= 16"],util:!0,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],v8:">= 1","node:v8":[">= 14.18 && < 15",">= 16"],vm:!0,"node:vm":[">= 14.18 && < 15",">= 16"],wasi:[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],"node:wasi":[">= 18.17 && < 19",">= 20"],worker_threads:">= 11.7","node:worker_threads":[">= 14.18 && < 15",">= 16"],zlib:">= 0.5","node:zlib":[">= 14.18 && < 15",">= 16"]}});var zl=m((G4e,lG)=>{"use strict";var ETe=iG();function STe(t,e){for(var n=t.split("."),r=e.split(" "),o=r.length>1?r[0]:"=",s=(r.length>1?r[1]:r[0]).split("."),i=0;i<3;++i){var a=parseInt(n[i]||0,10),c=parseInt(s[i]||0,10);if(a!==c)return o==="<"?a<c:o===">="?a>=c:!1}return o===">="}function cG(t,e){var n=e.split(/ ?&& ?/);if(n.length===0)return!1;for(var r=0;r<n.length;++r)if(!STe(t,n[r]))return!1;return!0}function gTe(t,e){if(typeof e=="boolean")return e;var n=typeof t>"u"?process.versions&&process.versions.node:t;if(typeof n!="string")throw new TypeError(typeof t>"u"?"Unable to determine current node version":"If provided, a valid node version is required");if(e&&typeof e=="object"){for(var r=0;r<e.length;++r)if(cG(n,e[r]))return!0;return!1}return cG(n,e)}var uG=aG();lG.exports=function(e,n){return ETe(uG,e)&&gTe(n,uG[e])}});var yR=m((H4e,dG)=>{"use strict";dG.exports=TypeError});var fG=m(($4e,_G)=>{var na=require("fs"),hTe=SR(),at=require("path"),TTe=gR(),ATe=AR(),RTe=RR(),yTe=zl(),pG=pm(),OR=yR(),OTe=process.platform!=="win32"&&na.realpath&&typeof na.realpath.native=="function"?na.realpath.native:na.realpath,NTe=/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/,CTe=/^\w:[/\\]*$/,vTe=/[/\\]node_modules[/\\]*$/,NR=hTe();function ITe(){return NR?[at.join(NR,".node_modules"),at.join(NR,".node_libraries")]:[]}var PTe=function(e,n){na.stat(e,function(r,o){return r?r.code==="ENOENT"||r.code==="ENOTDIR"?n(null,!1):n(r):n(null,o.isFile()||o.isFIFO())})},bTe=function(e,n){na.stat(e,function(r,o){return r?r.code==="ENOENT"||r.code==="ENOTDIR"?n(null,!1):n(r):n(null,o.isDirectory())})},MTe=function(e,n){OTe(e,function(r,o){r&&r.code!=="ENOENT"?n(r):n(null,r?e:o)})};function Xl(t,e,n,r){n&&n.preserveSymlinks===!1?t(e,r):r(null,e)}function LTe(t,e,n){t(e,function(r,o){if(r)n(r);else try{var s=JSON.parse(o);n(null,s)}catch{n(null)}})}function xTe(t,e,n){for(var r=ATe(e,n,t),o=0;o<r.length;o++)r[o]=at.join(r[o],t);return r}_G.exports=function(e,n,r){var o=r,s=n;if(typeof n=="function"&&(o=s,s={}),typeof e!="string"){var i=new OR("Path must be a string.");return process.nextTick(function(){o(i)})}s=RTe(e,s);var a=s.isFile||PTe,c=s.isDirectory||bTe,u=s.readFile||na.readFile,l=s.realpath||MTe,d=s.readPackage||LTe;if(s.readFile&&s.readPackage){var p=new OR("`readFile` and `readPackage` are mutually exclusive.");return process.nextTick(function(){o(p)})}var _=s.packageIterator,f=s.extensions||[".js"],E=s.includeCoreModules!==!1,S=s.basedir||at.dirname(TTe()),h=s.filename||S;s.paths=s.paths||ITe();var R=at.resolve(S);Xl(l,R,s,function(G,j){G?o(G):O(j)});var A;function O(G){if(NTe.test(e))A=at.resolve(G,e),(e==="."||e===".."||e.slice(-1)==="/")&&(A+="/"),e.slice(-1)==="/"&&A===G?J(A,s.package,y):M(A,s.package,y);else{if(E&&yTe(e))return o(null,e);me(e,G,function(j,Ne,pe){if(j)o(j);else{if(Ne)return Xl(l,Ne,s,function(Bn,Xe){Bn?o(Bn):o(null,Xe,pe)});var $e=new pG("Cannot find module '"+e+"' from '"+h+"'");$e.code="MODULE_NOT_FOUND",o($e)}})}}function y(G,j,Ne){G?o(G):j?o(null,j,Ne):J(A,function(pe,$e,Bn){if(pe)o(pe);else if($e)Xl(l,$e,s,function(Fe,_n){Fe?o(Fe):o(null,_n,Bn)});else{var Xe=new pG("Cannot find module '"+e+"' from '"+h+"'");Xe.code="MODULE_NOT_FOUND",o(Xe)}})}function M(G,j,Ne){var pe=j,$e=Ne;typeof pe=="function"&&($e=pe,pe=void 0);var Bn=[""].concat(f);Xe(Bn,G,pe);function Xe(Fe,_n,go){if(Fe.length===0)return $e(null,void 0,go);var Ni=_n+Fe[0],wr=go;wr?Bt(null,wr):I(at.dirname(Ni),Bt);function Bt(is,ka,ho){if(wr=ka,is)return $e(is);if(ho&&wr&&s.pathFilter){var Pp=at.relative(ho,Ni),bp=Pp.slice(0,Pp.length-Fe[0].length),Zu=s.pathFilter(wr,_n,bp);if(Zu)return Xe([""].concat(f),at.resolve(ho,Zu),wr)}a(Ni,Ip)}function Ip(is,ka){if(is)return $e(is);if(ka)return $e(null,Ni,wr);Xe(Fe.slice(1),_n,wr)}}}function I(G,j){if(G===""||G==="/"||process.platform==="win32"&&CTe.test(G)||vTe.test(G))return j(null);Xl(l,G,s,function(Ne,pe){if(Ne)return I(at.dirname(G),j);var $e=at.join(pe,"package.json");a($e,function(Bn,Xe){if(!Xe)return I(at.dirname(G),j);d(u,$e,function(Fe,_n){if(Fe)return j(Fe);var go=_n;go&&s.packageFilter&&(go=s.packageFilter(go,$e)),j(null,go,G)})})})}function J(G,j,Ne){var pe=Ne,$e=j;typeof $e=="function"&&(pe=$e,$e=s.package),Xl(l,G,s,function(Bn,Xe){if(Bn)return pe(Bn);var Fe=at.join(Xe,"package.json");a(Fe,function(_n,go){if(_n)return pe(_n);if(!go)return M(at.join(G,"index"),$e,pe);d(u,Fe,function(Ni,wr){if(Ni)return pe(Ni);var Bt=wr;if(Bt&&s.packageFilter&&(Bt=s.packageFilter(Bt,Fe)),Bt&&Bt.main){if(typeof Bt.main!="string"){var Ip=new OR("package \u201C"+Bt.name+"\u201D `main` must be a string");return Ip.code="INVALID_PACKAGE_MAIN",pe(Ip)}(Bt.main==="."||Bt.main==="./")&&(Bt.main="index"),M(at.resolve(G,Bt.main),Bt,function(is,ka,ho){if(is)return pe(is);if(ka)return pe(null,ka,ho);if(!ho)return M(at.join(G,"index"),ho,pe);var Pp=at.resolve(G,ho.main);J(Pp,ho,function(bp,Zu,Rv){if(bp)return pe(bp);if(Zu)return pe(null,Zu,Rv);M(at.join(G,"index"),Rv,pe)})});return}M(at.join(G,"/index"),Bt,pe)})})})}function H(G,j){if(j.length===0)return G(null,void 0);var Ne=j[0];c(at.dirname(Ne),pe);function pe(Xe,Fe){if(Xe)return G(Xe);if(!Fe)return H(G,j.slice(1));M(Ne,s.package,$e)}function $e(Xe,Fe,_n){if(Xe)return G(Xe);if(Fe)return G(null,Fe,_n);J(Ne,s.package,Bn)}function Bn(Xe,Fe,_n){if(Xe)return G(Xe);if(Fe)return G(null,Fe,_n);H(G,j.slice(1))}}function me(G,j,Ne){var pe=function(){return xTe(G,j,s)};H(Ne,_?_(G,j,pe,s):pe())}}});var mG=m((F4e,DTe)=>{DTe.exports={assert:!0,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16",async_hooks:">= 8","node:async_hooks":[">= 14.18 && < 15",">= 16"],buffer_ieee754:">= 0.5 && < 0.9.7",buffer:!0,"node:buffer":[">= 14.18 && < 15",">= 16"],child_process:!0,"node:child_process":[">= 14.18 && < 15",">= 16"],cluster:">= 0.5","node:cluster":[">= 14.18 && < 15",">= 16"],console:!0,"node:console":[">= 14.18 && < 15",">= 16"],constants:!0,"node:constants":[">= 14.18 && < 15",">= 16"],crypto:!0,"node:crypto":[">= 14.18 && < 15",">= 16"],_debug_agent:">= 1 && < 8",_debugger:"< 8",dgram:!0,"node:dgram":[">= 14.18 && < 15",">= 16"],diagnostics_channel:[">= 14.17 && < 15",">= 15.1"],"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],dns:!0,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16",domain:">= 0.7.12","node:domain":[">= 14.18 && < 15",">= 16"],events:!0,"node:events":[">= 14.18 && < 15",">= 16"],freelist:"< 6",fs:!0,"node:fs":[">= 14.18 && < 15",">= 16"],"fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],_http_agent:">= 0.11.1","node:_http_agent":[">= 14.18 && < 15",">= 16"],_http_client:">= 0.11.1","node:_http_client":[">= 14.18 && < 15",">= 16"],_http_common:">= 0.11.1","node:_http_common":[">= 14.18 && < 15",">= 16"],_http_incoming:">= 0.11.1","node:_http_incoming":[">= 14.18 && < 15",">= 16"],_http_outgoing:">= 0.11.1","node:_http_outgoing":[">= 14.18 && < 15",">= 16"],_http_server:">= 0.11.1","node:_http_server":[">= 14.18 && < 15",">= 16"],http:!0,"node:http":[">= 14.18 && < 15",">= 16"],http2:">= 8.8","node:http2":[">= 14.18 && < 15",">= 16"],https:!0,"node:https":[">= 14.18 && < 15",">= 16"],inspector:">= 8","node:inspector":[">= 14.18 && < 15",">= 16"],"inspector/promises":[">= 19"],"node:inspector/promises":[">= 19"],_linklist:"< 8",module:!0,"node:module":[">= 14.18 && < 15",">= 16"],net:!0,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12",os:!0,"node:os":[">= 14.18 && < 15",">= 16"],path:!0,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16",perf_hooks:">= 8.5","node:perf_hooks":[">= 14.18 && < 15",">= 16"],process:">= 1","node:process":[">= 14.18 && < 15",">= 16"],punycode:">= 0.5","node:punycode":[">= 14.18 && < 15",">= 16"],querystring:!0,"node:querystring":[">= 14.18 && < 15",">= 16"],readline:!0,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17",repl:!0,"node:repl":[">= 14.18 && < 15",">= 16"],"node:sea":[">= 20.12 && < 21",">= 21.7"],smalloc:">= 0.11.5 && < 3","node:sqlite":[">= 22.13 && < 23",">= 23.4"],_stream_duplex:">= 0.9.4","node:_stream_duplex":[">= 14.18 && < 15",">= 16"],_stream_transform:">= 0.9.4","node:_stream_transform":[">= 14.18 && < 15",">= 16"],_stream_wrap:">= 1.4.1","node:_stream_wrap":[">= 14.18 && < 15",">= 16"],_stream_passthrough:">= 0.9.4","node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],_stream_readable:">= 0.9.4","node:_stream_readable":[">= 14.18 && < 15",">= 16"],_stream_writable:">= 0.9.4","node:_stream_writable":[">= 14.18 && < 15",">= 16"],stream:!0,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5",string_decoder:!0,"node:string_decoder":[">= 14.18 && < 15",">= 16"],sys:[">= 0.4 && < 0.7",">= 0.8"],"node:sys":[">= 14.18 && < 15",">= 16"],"test/reporters":">= 19.9 && < 20.2","node:test/reporters":[">= 18.17 && < 19",">= 19.9",">= 20"],"test/mock_loader":">= 22.3 && < 22.7","node:test/mock_loader":">= 22.3 && < 22.7","node:test":[">= 16.17 && < 17",">= 18"],timers:!0,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16",_tls_common:">= 0.11.13","node:_tls_common":[">= 14.18 && < 15",">= 16"],_tls_legacy:">= 0.11.3 && < 10",_tls_wrap:">= 0.11.3","node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls:!0,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events:">= 10","node:trace_events":[">= 14.18 && < 15",">= 16"],tty:!0,"node:tty":[">= 14.18 && < 15",">= 16"],url:!0,"node:url":[">= 14.18 && < 15",">= 16"],util:!0,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],v8:">= 1","node:v8":[">= 14.18 && < 15",">= 16"],vm:!0,"node:vm":[">= 14.18 && < 15",">= 16"],wasi:[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],"node:wasi":[">= 18.17 && < 19",">= 20"],worker_threads:">= 11.7","node:worker_threads":[">= 14.18 && < 15",">= 16"],zlib:">= 0.5","node:zlib":[">= 14.18 && < 15",">= 16"]}});var hG=m((j4e,gG)=>{"use strict";var UTe=zl(),EG=mG(),SG={};for(fm in EG)Object.prototype.hasOwnProperty.call(EG,fm)&&(SG[fm]=UTe(fm));var fm;gG.exports=SG});var AG=m((q4e,TG)=>{var wTe=zl();TG.exports=function(e){return wTe(e)}});var yG=m((Y4e,RG)=>{var kTe=zl(),ra=require("fs"),Kt=require("path"),VTe=pm(),CR=yR(),BTe=SR(),GTe=gR(),HTe=AR(),$Te=RR(),FTe=process.platform!=="win32"&&ra.realpathSync&&typeof ra.realpathSync.native=="function"?ra.realpathSync.native:ra.realpathSync,jTe=/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/,qTe=/^\w:[/\\]*$/,YTe=/[/\\]node_modules[/\\]*$/,vR=BTe();function KTe(){return vR?[Kt.join(vR,".node_modules"),Kt.join(vR,".node_libraries")]:[]}var WTe=function(e){try{var n=ra.statSync(e,{throwIfNoEntry:!1})}catch(r){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return!1;throw r}return!!n&&(n.isFile()||n.isFIFO())},zTe=function(e){try{var n=ra.statSync(e,{throwIfNoEntry:!1})}catch(r){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return!1;throw r}return!!n&&n.isDirectory()},XTe=function(e){try{return FTe(e)}catch(n){if(n.code!=="ENOENT")throw n}return e};function Jl(t,e,n){return n&&n.preserveSymlinks===!1?t(e):e}function JTe(t,e){var n=t(e);try{var r=JSON.parse(n);return r}catch{}}function ZTe(t,e,n){for(var r=HTe(e,n,t),o=0;o<r.length;o++)r[o]=Kt.join(r[o],t);return r}RG.exports=function(e,n){if(typeof e!="string")throw new CR("Path must be a string.");var r=$Te(e,n),o=r.isFile||WTe,s=r.readFileSync||ra.readFileSync,i=r.isDirectory||zTe,a=r.realpathSync||XTe,c=r.readPackageSync||JTe;if(r.readFileSync&&r.readPackageSync)throw new CR("`readFileSync` and `readPackageSync` are mutually exclusive.");var u=r.packageIterator,l=r.extensions||[".js"],d=r.includeCoreModules!==!1,p=r.basedir||Kt.dirname(GTe()),_=r.filename||p;r.paths=r.paths||KTe();var f=Jl(a,Kt.resolve(p),r);if(jTe.test(e)){var E=Kt.resolve(f,e);(e==="."||e===".."||e.slice(-1)==="/")&&(E+="/");var S=A(E)||y(E);if(S)return Jl(a,S,r)}else{if(d&&kTe(e))return e;var h=M(e,f);if(h)return Jl(a,h,r)}var R=new VTe("Cannot find module '"+e+"' from '"+_+"'");throw R.code="MODULE_NOT_FOUND",R;function A(I){var J=O(Kt.dirname(I));if(J&&J.dir&&J.pkg&&r.pathFilter){var H=Kt.relative(J.dir,I),me=r.pathFilter(J.pkg,I,H);me&&(I=Kt.resolve(J.dir,me))}if(o(I))return I;for(var G=0;G<l.length;G++){var j=I+l[G];if(o(j))return j}}function O(I){if(!(I===""||I==="/")&&!(process.platform==="win32"&&qTe.test(I))&&!YTe.test(I)){var J=Kt.join(Jl(a,I,r),"package.json");if(!o(J))return O(Kt.dirname(I));var H=c(s,J);return H&&r.packageFilter&&(H=r.packageFilter(H,I)),{pkg:H,dir:I}}}function y(I){var J=Kt.join(Jl(a,I,r),"/package.json");if(o(J)){try{var H=c(s,J)}catch{}if(H&&r.packageFilter&&(H=r.packageFilter(H,I)),H&&H.main){if(typeof H.main!="string"){var me=new CR("package \u201C"+H.name+"\u201D `main` must be a string");throw me.code="INVALID_PACKAGE_MAIN",me}(H.main==="."||H.main==="./")&&(H.main="index");try{var G=A(Kt.resolve(I,H.main));if(G)return G;var j=y(Kt.resolve(I,H.main));if(j)return j}catch{}}}return A(Kt.join(I,"/index"))}function M(I,J){for(var H=function(){return ZTe(I,J,r)},me=u?u(I,J,H,r):H(),G=0;G<me.length;G++){var j=me[G];if(i(Kt.dirname(j))){var Ne=A(j);if(Ne)return Ne;var pe=y(j);if(pe)return pe}}}}});var IR=m((K4e,OG)=>{var mm=fG();mm.core=hG();mm.isCore=AG();mm.sync=yG();OG.exports=mm});var NG=m((W4e,QTe)=>{QTe.exports={name:"require-in-the-middle",version:"7.5.2",description:"Module to hook into the Node.js require function",main:"index.js",types:"types/index.d.ts",dependencies:{debug:"^4.3.5","module-details-from-path":"^1.0.3",resolve:"^1.22.8"},devDependencies:{"@babel/core":"^7.9.0","@babel/preset-env":"^7.9.5","@babel/preset-typescript":"^7.9.0","@babel/register":"^7.9.0","ipp-printer":"^1.0.0",patterns:"^1.0.3",roundround:"^0.2.0",semver:"^6.3.0",standard:"^14.3.1",tape:"^4.11.0"},scripts:{test:"npm run test:lint && npm run test:tape && npm run test:babel","test:lint":"standard","test:tape":"tape test/*.js","test:babel":"node test/babel/babel-register.js"},repository:{type:"git",url:"git+https://github.com/nodejs/require-in-the-middle.git"},keywords:["require","hook","shim","shimmer","shimming","patch","monkey","monkeypatch","module","load"],files:["types"],author:"Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)",license:"MIT",bugs:{url:"https://github.com/nodejs/require-in-the-middle/issues"},homepage:"https://github.com/nodejs/require-in-the-middle#readme",engines:{node:">=8.6.0"}}});var LR=m((z4e,MR)=>{"use strict";var yc=require("path"),Tr=require("module"),et=FB()("require-in-the-middle"),eAe=ER();MR.exports=Zl;MR.exports.Hook=Zl;var PR,Rc;if(Tr.isBuiltin)Rc=Tr.isBuiltin;else if(Tr.builtinModules)Rc=t=>t.startsWith("node:")?!0:(PR===void 0&&(PR=new Set(Tr.builtinModules)),PR.has(t));else{let t=IR(),[e,n]=process.versions.node.split(".").map(Number);e===8&&n<8?Rc=r=>r==="http2"?!0:!!t.core[r]:Rc=r=>!!t.core[r]}var Em;function tAe(t,e){if(!Em)if(require.resolve&&require.resolve.paths)Em=function(n,r){return require.resolve(n,{paths:[r]})};else{let n=IR();Em=function(r,o){return n.sync(r,{basedir:o})}}return Em(t,e)}var nAe=/([/\\]index)?(\.js)?$/,bR=class{constructor(){this._localCache=new Map,this._kRitmExports=Symbol("RitmExports")}has(e,n){if(this._localCache.has(e))return!0;if(n)return!1;{let r=require.cache[e];return!!(r&&this._kRitmExports in r)}}get(e,n){let r=this._localCache.get(e);if(r!==void 0)return r;if(!n){let o=require.cache[e];return o&&o[this._kRitmExports]}}set(e,n,r){r?this._localCache.set(e,n):e in require.cache?require.cache[e][this._kRitmExports]=n:(et('non-core module is unexpectedly not in require.cache: "%s"',e),this._localCache.set(e,n))}};function Zl(t,e,n){if(!(this instanceof Zl))return new Zl(t,e,n);if(typeof t=="function"?(n=t,t=null,e=null):typeof e=="function"&&(n=e,e=null),typeof Tr._resolveFilename!="function"){console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!",typeof Tr._resolveFilename),console.error("Please report this error as an issue related to Node.js %s at %s",process.version,NG().bugs.url);return}this._cache=new bR,this._unhooked=!1,this._origRequire=Tr.prototype.require;let r=this,o=new Set,s=e?e.internals===!0:!1,i=Array.isArray(t);et("registering require hook"),this._require=Tr.prototype.require=function(c){return r._unhooked===!0?(et("ignoring require call - module is soft-unhooked"),r._origRequire.apply(this,arguments)):a.call(this,arguments,!1)},typeof process.getBuiltinModule=="function"&&(this._origGetBuiltinModule=process.getBuiltinModule,this._getBuiltinModule=process.getBuiltinModule=function(c){return r._unhooked===!0?(et("ignoring process.getBuiltinModule call - module is soft-unhooked"),r._origGetBuiltinModule.apply(this,arguments)):a.call(this,arguments,!0)});function a(c,u){let l=c[0],d=Rc(l),p;if(d){if(p=l,l.startsWith("node:")){let R=l.slice(5);Rc(R)&&(p=R)}}else{if(u)return et("call to process.getBuiltinModule with unknown built-in id"),r._origGetBuiltinModule.apply(this,c);try{p=Tr._resolveFilename(l,this)}catch(R){return et('Module._resolveFilename("%s") threw %j, calling original Module.require',l,R.message),r._origRequire.apply(this,c)}}let _,f;if(et("processing %s module require('%s'): %s",d===!0?"core":"non-core",l,p),r._cache.has(p,d)===!0)return et("returning already patched cached module: %s",p),r._cache.get(p,d);let E=o.has(p);E===!1&&o.add(p);let S=u?r._origGetBuiltinModule.apply(this,c):r._origRequire.apply(this,c);if(E===!0)return et("module is in the process of being patched already - ignoring: %s",p),S;if(o.delete(p),d===!0){if(i===!0&&t.includes(p)===!1)return et("ignoring core module not on whitelist: %s",p),S;_=p}else if(i===!0&&t.includes(p)){let R=yc.parse(p);_=R.name,f=R.dir}else{let R=eAe(p);if(R===void 0)return et("could not parse filename: %s",p),S;_=R.name,f=R.basedir;let A=rAe(R);et("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)",_,l,A,f);let O=!1;if(i){if(!l.startsWith(".")&&t.includes(l)&&(_=l,O=!0),!t.includes(_)&&!t.includes(A))return S;t.includes(A)&&A!==_&&(_=A,O=!0)}if(!O){let y;try{y=tAe(_,f)}catch{return et("could not resolve module: %s",_),r._cache.set(p,S,d),S}if(y!==p)if(s===!0)_=_+yc.sep+yc.relative(f,p),et("preparing to process require of internal file: %s",_);else return et("ignoring require of non-main module file: %s",y),r._cache.set(p,S,d),S}}r._cache.set(p,S,d),et("calling require hook: %s",_);let h=n(S,_,f);return r._cache.set(p,h,d),et("returning module: %s",_),h}}Zl.prototype.unhook=function(){this._unhooked=!0,this._require===Tr.prototype.require?(Tr.prototype.require=this._origRequire,et("require unhook successful")):et("require unhook unsuccessful"),process.getBuiltinModule!==void 0&&(this._getBuiltinModule===process.getBuiltinModule?(process.getBuiltinModule=this._origGetBuiltinModule,et("process.getBuiltinModule unhook successful")):et("process.getBuiltinModule unhook unsuccessful"))};function rAe(t){let e=yc.sep!=="/"?t.path.split(yc.sep).join("/"):t.path;return yc.posix.join(t.name,e).replace(nAe,"")}});var CG=m(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.ModuleNameTrie=Ms.ModuleNameSeparator=void 0;Ms.ModuleNameSeparator="/";var Sm=class{constructor(){this.hooks=[],this.children=new Map}},xR=class{constructor(){this._trie=new Sm,this._counter=0}insert(e){let n=this._trie;for(let r of e.moduleName.split(Ms.ModuleNameSeparator)){let o=n.children.get(r);o||(o=new Sm,n.children.set(r,o)),n=o}n.hooks.push({hook:e,insertedId:this._counter++})}search(e,{maintainInsertionOrder:n,fullOnly:r}={}){let o=this._trie,s=[],i=!0;for(let a of e.split(Ms.ModuleNameSeparator)){let c=o.children.get(a);if(!c){i=!1;break}r||s.push(...c.hooks),o=c}return r&&i&&s.push(...o.hooks),s.length===0?[]:s.length===1?[s[0].hook]:(n&&s.sort((a,c)=>a.insertedId-c.insertedId),s.map(({hook:a})=>a))}};Ms.ModuleNameTrie=xR});var IG=m(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});gm.RequireInTheMiddleSingleton=void 0;var oAe=LR(),vG=require("path"),DR=CG(),sAe=["afterEach","after","beforeEach","before","describe","it"].every(t=>typeof global[t]=="function"),UR=class t{constructor(){this._moduleNameTrie=new DR.ModuleNameTrie,this._initialize()}_initialize(){new oAe.Hook(null,{internals:!0},(e,n,r)=>{let o=iAe(n),s=this._moduleNameTrie.search(o,{maintainInsertionOrder:!0,fullOnly:r===void 0});for(let{onRequire:i}of s)e=i(e,n,r);return e})}register(e,n){let r={moduleName:e,onRequire:n};return this._moduleNameTrie.insert(r),r}static getInstance(){var e;return sAe?new t:this._instance=(e=this._instance)!==null&&e!==void 0?e:new t}};gm.RequireInTheMiddleSingleton=UR;function iAe(t){return vG.sep!==DR.ModuleNameSeparator?t.split(vG.sep).join(DR.ModuleNameSeparator):t}});var DG=m(oa=>{var PG=[],wR=new WeakMap,bG=new WeakMap,MG=new Map,LG=[],aAe={set(t,e,n){return wR.get(t)[e](n)},get(t,e){if(e===Symbol.toStringTag)return"Module";let n=bG.get(t)[e];if(typeof n=="function")return n()},defineProperty(t,e,n){if(!("value"in n))throw new Error("Getters/setters are not supported for exports property descriptors.");return wR.get(t)[e](n.value)}};function cAe(t,e,n,r,o){MG.set(t,o),wR.set(e,n),bG.set(e,r);let s=new Proxy(e,aAe);PG.forEach(i=>i(t,s)),LG.push([t,s])}var xG=!1;function uAe(){return xG}function lAe(t){xG=t}oa.register=cAe;oa.importHooks=PG;oa.specifiers=MG;oa.toHook=LG;oa.getExperimentalPatchInternals=uAe;oa.setExperimentalPatchInternals=lAe});var hm=m((Q4e,Oc)=>{var UG=require("path"),dAe=ER(),{fileURLToPath:wG}=require("url"),{MessageChannel:pAe}=require("worker_threads"),{importHooks:kR,specifiers:_Ae,toHook:fAe,getExperimentalPatchInternals:mAe}=DG();function VG(t){kR.push(t),fAe.forEach(([e,n])=>t(e,n))}function BG(t){let e=kR.indexOf(t);e>-1&&kR.splice(e,1)}function kG(t,e,n,r){let o=t(e,n,r);o&&o!==e&&(e.default=o)}var VR;function EAe(){let{port1:t,port2:e}=new pAe,n=0,r;VR=a=>{n++,t.postMessage(a)},t.on("message",()=>{n--,r&&n<=0&&r()}).unref();function o(){let a=setInterval(()=>{},1e3),c=new Promise(u=>{r=u}).then(()=>{clearInterval(a)});return n===0&&r(),c}let s=e;return{registerOptions:{data:{addHookMessagePort:s,include:[]},transferList:[s]},addHookMessagePort:s,waitForAllMessagesAcknowledged:o}}function Ql(t,e,n){if(!(this instanceof Ql))return new Ql(t,e,n);typeof t=="function"?(n=t,t=null,e=null):typeof e=="function"&&(n=e,e=null);let r=e?e.internals===!0:!1;VR&&Array.isArray(t)&&VR(t),this._iitmHook=(o,s)=>{let i=o,a=o.startsWith("node:"),c;if(a)o=o.replace(/^node:/,"");else{if(o.startsWith("file://"))try{o=wG(o)}catch{}let u=dAe(o);u&&(o=u.name,c=u.basedir)}if(t){for(let u of t)if(u===o){if(c){if(r)o=o+UG.sep+UG.relative(c,wG(i));else if(!mAe()&&!c.endsWith(_Ae.get(i)))continue}kG(n,s,o,c)}}else kG(n,s,o,c)},VG(this._iitmHook)}Ql.prototype.unhook=function(){BG(this._iitmHook)};Oc.exports=Ql;Oc.exports.Hook=Ql;Oc.exports.addHook=VG;Oc.exports.removeHook=BG;Oc.exports.createAddHookMessageChannel=EAe});var BR=m(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.isWrapped=Ls.safeExecuteInTheMiddleAsync=Ls.safeExecuteInTheMiddle=void 0;function SAe(t,e,n){let r,o;try{o=t()}catch(s){r=s}finally{if(e(r,o),r&&!n)throw r;return o}}Ls.safeExecuteInTheMiddle=SAe;async function gAe(t,e,n){let r,o;try{o=await t()}catch(s){r=s}finally{if(e(r,o),r&&!n)throw r;return o}}Ls.safeExecuteInTheMiddleAsync=gAe;function hAe(t){return typeof t=="function"&&typeof t.__original=="function"&&typeof t.__unwrap=="function"&&t.__wrapped===!0}Ls.isWrapped=hAe});var $G=m(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.InstrumentationBase=void 0;var ed=require("path"),GG=require("util"),TAe=eR(),GR=cR(),AAe=MB(),RAe=IG(),yAe=hm(),td=(x(),b(B)),OAe=LR(),NAe=require("fs"),CAe=BR(),HR=class extends AAe.InstrumentationAbstract{constructor(e,n,r){super(e,n,r),this._hooks=[],this._requireInTheMiddleSingleton=RAe.RequireInTheMiddleSingleton.getInstance(),this._enabled=!1,this._wrap=(s,i,a)=>{if((0,CAe.isWrapped)(s[i])&&this._unwrap(s,i),GG.types.isProxy(s)){let c=(0,GR.wrap)(Object.assign({},s),i,a);return Object.defineProperty(s,i,{value:c}),c}else return(0,GR.wrap)(s,i,a)},this._unwrap=(s,i)=>GG.types.isProxy(s)?Object.defineProperty(s,i,{value:s[i]}):(0,GR.unwrap)(s,i),this._massWrap=(s,i,a)=>{if(s)Array.isArray(s)||(s=[s]);else{td.diag.error("must provide one or more modules to patch");return}if(!(i&&Array.isArray(i))){td.diag.error("must provide one or more functions to wrap on modules");return}s.forEach(c=>{i.forEach(u=>{this._wrap(c,u,a)})})},this._massUnwrap=(s,i)=>{if(s)Array.isArray(s)||(s=[s]);else{td.diag.error("must provide one or more modules to patch");return}if(!(i&&Array.isArray(i))){td.diag.error("must provide one or more functions to wrap on modules");return}s.forEach(a=>{i.forEach(c=>{this._unwrap(a,c)})})};let o=this.init();o&&!Array.isArray(o)&&(o=[o]),this._modules=o||[],this._config.enabled&&this.enable()}_warnOnPreloadedModules(){this._modules.forEach(e=>{let{name:n}=e;try{let r=require.resolve(n);require.cache[r]&&this._diag.warn(`Module ${n} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${n}`)}catch{}})}_extractPackageVersion(e){try{let n=(0,NAe.readFileSync)(ed.join(e,"package.json"),{encoding:"utf8"}),r=JSON.parse(n).version;return typeof r=="string"?r:void 0}catch{td.diag.warn("Failed extracting version",e)}}_onRequire(e,n,r,o){var s;if(!o)return typeof e.patch=="function"&&(e.moduleExports=n,this._enabled)?(this._diag.debug("Applying instrumentation patch for nodejs core module on require hook",{module:e.name}),e.patch(n)):n;let i=this._extractPackageVersion(o);if(e.moduleVersion=i,e.name===r)return HG(e.supportedVersions,i,e.includePrerelease)&&typeof e.patch=="function"&&(e.moduleExports=n,this._enabled)?(this._diag.debug("Applying instrumentation patch for module on require hook",{module:e.name,version:e.moduleVersion,baseDir:o}),e.patch(n,e.moduleVersion)):n;let a=(s=e.files)!==null&&s!==void 0?s:[],c=ed.normalize(r);return a.filter(l=>l.name===c).filter(l=>HG(l.supportedVersions,i,e.includePrerelease)).reduce((l,d)=>(d.moduleExports=l,this._enabled?(this._diag.debug("Applying instrumentation patch for nodejs module file on require hook",{module:e.name,version:e.moduleVersion,fileName:d.name,baseDir:o}),d.patch(l,e.moduleVersion)):l),n)}enable(){if(!this._enabled){if(this._enabled=!0,this._hooks.length>0){for(let e of this._modules){typeof e.patch=="function"&&e.moduleExports&&(this._diag.debug("Applying instrumentation patch for nodejs module on instrumentation enabled",{module:e.name,version:e.moduleVersion}),e.patch(e.moduleExports,e.moduleVersion));for(let n of e.files)n.moduleExports&&(this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled",{module:e.name,version:e.moduleVersion,fileName:n.name}),n.patch(n.moduleExports,e.moduleVersion))}return}this._warnOnPreloadedModules();for(let e of this._modules){let n=(i,a,c)=>{if(!c&&ed.isAbsolute(a)){let u=ed.parse(a);a=u.name,c=u.dir}return this._onRequire(e,i,a,c)},r=(i,a,c)=>this._onRequire(e,i,a,c),o=ed.isAbsolute(e.name)?new OAe.Hook([e.name],{internals:!0},r):this._requireInTheMiddleSingleton.register(e.name,r);this._hooks.push(o);let s=new yAe.Hook([e.name],{internals:!1},n);this._hooks.push(s)}}}disable(){if(this._enabled){this._enabled=!1;for(let e of this._modules){typeof e.unpatch=="function"&&e.moduleExports&&(this._diag.debug("Removing instrumentation patch for nodejs module on instrumentation disabled",{module:e.name,version:e.moduleVersion}),e.unpatch(e.moduleExports,e.moduleVersion));for(let n of e.files)n.moduleExports&&(this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled",{module:e.name,version:e.moduleVersion,fileName:n.name}),n.unpatch(n.moduleExports,e.moduleVersion))}}}isEnabled(){return this._enabled}};Tm.InstrumentationBase=HR;function HG(t,e,n){return typeof e>"u"?t.includes("*"):t.some(r=>(0,TAe.satisfies)(e,r,{includePrerelease:n}))}});var FG=m(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.normalize=void 0;var vAe=require("path");Object.defineProperty(Am,"normalize",{enumerable:!0,get:function(){return vAe.normalize}})});var jG=m(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.normalize=Nc.InstrumentationBase=void 0;var IAe=$G();Object.defineProperty(Nc,"InstrumentationBase",{enumerable:!0,get:function(){return IAe.InstrumentationBase}});var PAe=FG();Object.defineProperty(Nc,"normalize",{enumerable:!0,get:function(){return PAe.normalize}})});var $R=m(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.normalize=Cc.InstrumentationBase=void 0;var qG=jG();Object.defineProperty(Cc,"InstrumentationBase",{enumerable:!0,get:function(){return qG.InstrumentationBase}});Object.defineProperty(Cc,"normalize",{enumerable:!0,get:function(){return qG.normalize}})});var YG=m(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});Rm.InstrumentationNodeModuleDefinition=void 0;var FR=class{constructor(e,n,r,o,s){this.name=e,this.supportedVersions=n,this.patch=r,this.unpatch=o,this.files=s||[]}};Rm.InstrumentationNodeModuleDefinition=FR});var KG=m(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});ym.InstrumentationNodeModuleFile=void 0;var bAe=$R(),jR=class{constructor(e,n,r,o){this.supportedVersions=n,this.patch=r,this.unpatch=o,this.name=(0,bAe.normalize)(e)}};ym.InstrumentationNodeModuleFile=jR});var fe=m(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.safeExecuteInTheMiddleAsync=Wt.safeExecuteInTheMiddle=Wt.isWrapped=Wt.InstrumentationNodeModuleFile=Wt.InstrumentationNodeModuleDefinition=Wt.InstrumentationBase=Wt.registerInstrumentations=void 0;var MAe=vB();Object.defineProperty(Wt,"registerInstrumentations",{enumerable:!0,get:function(){return MAe.registerInstrumentations}});var LAe=$R();Object.defineProperty(Wt,"InstrumentationBase",{enumerable:!0,get:function(){return LAe.InstrumentationBase}});var xAe=YG();Object.defineProperty(Wt,"InstrumentationNodeModuleDefinition",{enumerable:!0,get:function(){return xAe.InstrumentationNodeModuleDefinition}});var DAe=KG();Object.defineProperty(Wt,"InstrumentationNodeModuleFile",{enumerable:!0,get:function(){return DAe.InstrumentationNodeModuleFile}});var qR=BR();Object.defineProperty(Wt,"isWrapped",{enumerable:!0,get:function(){return qR.isWrapped}});Object.defineProperty(Wt,"safeExecuteInTheMiddle",{enumerable:!0,get:function(){return qR.safeExecuteInTheMiddle}});Object.defineProperty(Wt,"safeExecuteInTheMiddleAsync",{enumerable:!0,get:function(){return qR.safeExecuteInTheMiddleAsync}})});var WG=m(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.AttributeNames=void 0;var UAe;(function(t){t.HTTP_ERROR_NAME="http.error_name",t.HTTP_ERROR_MESSAGE="http.error_message",t.HTTP_STATUS_TEXT="http.status_text"})(UAe=nd.AttributeNames||(nd.AttributeNames={}))});var XG=m((u5e,zG)=>{"use strict";var wAe=require("util");function YR(t,e){Error.captureStackTrace(this,YR),this.name=this.constructor.name,this.message=t,this.input=e}wAe.inherits(YR,Error);zG.exports=YR});var ZG=m((l5e,JG)=>{"use strict";function kAe(t){return t===34||t===40||t===41||t===44||t===47||t>=58&&t<=64||t>=91&&t<=93||t===123||t===125}function VAe(t){return t===33||t>=35&&t<=39||t===42||t===43||t===45||t===46||t>=48&&t<=57||t>=65&&t<=90||t>=94&&t<=122||t===124||t===126}function BAe(t){return t>=32&&t<=126}function GAe(t){return t>=128&&t<=255}JG.exports={isDelimiter:kAe,isTokenChar:VAe,isExtended:GAe,isPrint:BAe}});var rH=m((d5e,nH)=>{"use strict";var HAe=require("util"),vc=XG(),Om=ZG(),$Ae=Om.isDelimiter,QG=Om.isTokenChar,eH=Om.isExtended,FAe=Om.isPrint;function tH(t){return t.replace(/\\(.)/g,"$1")}function rd(t,e){return HAe.format("Unexpected character '%s' at index %d",t.charAt(e),e)}function jAe(t){for(var e=!1,n=!1,r=!1,o={},s=[],i=-1,a=-1,c,u,l=0;l<t.length;l++)if(u=t.charCodeAt(l),c===void 0){if(l!==0&&i===-1&&(u===32||u===9))continue;if(QG(u))i===-1&&(i=l);else if(u===61&&i!==-1)c=t.slice(i,l).toLowerCase(),i=-1;else throw new vc(rd(t,l),t)}else if(n&&(u===9||FAe(u)||eH(u)))n=!1;else if(QG(u)){if(a!==-1)throw new vc(rd(t,l),t);i===-1&&(i=l)}else if($Ae(u)||eH(u))if(r)u===34?(r=!1,a=l):u===92?(i===-1&&(i=l),n=e=!0):i===-1&&(i=l);else if(u===34&&t.charCodeAt(l-1)===61)r=!0;else if((u===44||u===59)&&(i!==-1||a!==-1))i!==-1?(a===-1&&(a=l),o[c]=e?tH(t.slice(i,a)):t.slice(i,a)):o[c]="",u===44&&(s.push(o),o={}),c=void 0,i=a=-1;else throw new vc(rd(t,l),t);else if(u===32||u===9){if(a!==-1)continue;if(r)i===-1&&(i=l);else if(i!==-1)a=l;else throw new vc(rd(t,l),t)}else throw new vc(rd(t,l),t);if(c===void 0||r||i===-1&&a===-1||u===32||u===9)throw new vc("Unexpected end of input",t);return i!==-1?(a===-1&&(a=l),o[c]=e?tH(t.slice(i,a)):t.slice(i,a)):o[c]="",s.push(o),s}nH.exports=jAe});var uH=m(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.headerCapture=Y.getIncomingStableRequestMetricAttributesOnResponse=Y.getIncomingRequestMetricAttributesOnResponse=Y.getIncomingRequestAttributesOnResponse=Y.getIncomingRequestMetricAttributes=Y.getIncomingRequestAttributes=Y.getRemoteClientAddress=Y.getOutgoingRequestMetricAttributesOnResponse=Y.getOutgoingRequestAttributesOnResponse=Y.setAttributesFromHttpKind=Y.getOutgoingRequestMetricAttributes=Y.getOutgoingRequestAttributes=Y.extractHostnameAndPort=Y.isValidOptionsType=Y.getRequestInfo=Y.isCompressed=Y.setResponseContentLengthAttribute=Y.setRequestContentLengthAttribute=Y.setSpanWithError=Y.satisfiesPattern=Y.parseResponseStatus=Y.getAbsoluteUrl=void 0;var od=(x(),b(B)),L=(zn(),b(Wn)),oH=Se(),qAe=require("url"),Nm=WG(),YAe=rH(),KAe=(t,e,n="http:")=>{let r=t||{},o=r.protocol||n,s=(r.port||"").toString(),i=r.path||"/",a=r.host||r.hostname||e.host||"localhost";return a.indexOf(":")===-1&&s&&s!=="80"&&s!=="443"&&(a+=`:${s}`),`${o}//${a}${i}`};Y.getAbsoluteUrl=KAe;var WAe=(t,e)=>{let n=t===od.SpanKind.CLIENT?400:500;return e&&e>=100&&e<n?od.SpanStatusCode.UNSET:od.SpanStatusCode.ERROR};Y.parseResponseStatus=WAe;var zAe=(t,e)=>{if(typeof e=="string")return e===t;if(e instanceof RegExp)return e.test(t);if(typeof e=="function")return e(t);throw new TypeError("Pattern is in unsupported datatype")};Y.satisfiesPattern=zAe;var XAe=(t,e,n)=>{let r=e.message;(n&2)===2&&(t.setAttribute(Nm.AttributeNames.HTTP_ERROR_NAME,e.name),t.setAttribute(Nm.AttributeNames.HTTP_ERROR_MESSAGE,r)),(n&1)===1&&t.setAttribute(L.ATTR_ERROR_TYPE,e.name),t.setStatus({code:od.SpanStatusCode.ERROR,message:r}),t.recordException(e)};Y.setSpanWithError=XAe;var JAe=(t,e)=>{let n=sH(t.headers);n!==null&&((0,Y.isCompressed)(t.headers)?e[L.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH]=n:e[L.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED]=n)};Y.setRequestContentLengthAttribute=JAe;var ZAe=(t,e)=>{let n=sH(t.headers);n!==null&&((0,Y.isCompressed)(t.headers)?e[L.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH]=n:e[L.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED]=n)};Y.setResponseContentLengthAttribute=ZAe;function sH(t){let e=t["content-length"];if(e===void 0)return null;let n=parseInt(e,10);return isNaN(n)?null:n}var QAe=t=>{let e=t["content-encoding"];return!!e&&e!=="identity"};Y.isCompressed=QAe;function eRe(t){let{hostname:e,pathname:n,port:r,username:o,password:s,search:i,protocol:a,hash:c,href:u,origin:l,host:d}=new URL(t),p={protocol:a,hostname:e&&e[0]==="["?e.slice(1,-1):e,hash:c,search:i,pathname:n,path:`${n||""}${i||""}`,href:u,origin:l,host:d};return r!==""&&(p.port=Number(r)),(o||s)&&(p.auth=`${decodeURIComponent(o)}:${decodeURIComponent(s)}`),p}var tRe=(t,e,n)=>{let r,o,s,i=!1;if(typeof e=="string"){try{let c=eRe(e);s=c,r=c.pathname||"/"}catch(c){i=!0,t.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:",c),s={path:e},r=s.path||"/"}o=`${s.protocol||"http:"}//${s.host}`,n!==void 0&&Object.assign(s,n)}else if(e instanceof qAe.URL)s={protocol:e.protocol,hostname:typeof e.hostname=="string"&&e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,path:`${e.pathname||""}${e.search||""}`},e.port!==""&&(s.port=Number(e.port)),(e.username||e.password)&&(s.auth=`${e.username}:${e.password}`),r=e.pathname,o=e.origin,n!==void 0&&Object.assign(s,n);else{s=Object.assign({protocol:e.host?"http:":void 0},e);let c=s.host||(s.port!=null?`${s.hostname}${s.port}`:s.hostname);if(o=`${s.protocol||"http:"}//${c}`,r=e.pathname,!r&&s.path)try{r=new URL(s.path,o).pathname||"/"}catch{r="/"}}let a=s.method?s.method.toUpperCase():"GET";return{origin:o,pathname:r,method:a,optionsParsed:s,invalidUrl:i}};Y.getRequestInfo=tRe;var nRe=t=>{if(!t)return!1;let e=typeof t;return e==="string"||e==="object"&&!Array.isArray(t)};Y.isValidOptionsType=nRe;var rRe=t=>{var e;if(t.hostname&&t.port)return{hostname:t.hostname,port:t.port};let n=((e=t.host)===null||e===void 0?void 0:e.match(/^([^:/ ]+)(:\d{1,5})?/))||null,r=t.hostname||(n===null?"localhost":n[1]),o=t.port;return o||(n&&n[2]?o=n[2].substring(1):o=t.protocol==="https:"?"443":"80"),{hostname:r,port:o}};Y.extractHostnameAndPort=rRe;var oRe=(t,e,n)=>{var r,o;let s=e.hostname,i=e.port,a=(r=t.method)!==null&&r!==void 0?r:"GET",c=aH(a),u=t.headers||{},l=u["user-agent"],d=(0,Y.getAbsoluteUrl)(t,u,`${e.component}:`),p={[L.SEMATTRS_HTTP_URL]:d,[L.SEMATTRS_HTTP_METHOD]:a,[L.SEMATTRS_HTTP_TARGET]:t.path||"/",[L.SEMATTRS_NET_PEER_NAME]:s,[L.SEMATTRS_HTTP_HOST]:(o=u.host)!==null&&o!==void 0?o:`${s}:${i}`},_={[L.ATTR_HTTP_REQUEST_METHOD]:c,[L.ATTR_SERVER_ADDRESS]:s,[L.ATTR_SERVER_PORT]:Number(i),[L.ATTR_URL_FULL]:d};switch(a!==c&&(_[L.ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=a),l!==void 0&&(p[L.SEMATTRS_HTTP_USER_AGENT]=l),n){case 1:return Object.assign(_,e.hookAttributes);case 2:return Object.assign(p,e.hookAttributes)}return Object.assign(p,_,e.hookAttributes)};Y.getOutgoingRequestAttributes=oRe;var sRe=t=>{let e={};return e[L.SEMATTRS_HTTP_METHOD]=t[L.SEMATTRS_HTTP_METHOD],e[L.SEMATTRS_NET_PEER_NAME]=t[L.SEMATTRS_NET_PEER_NAME],e};Y.getOutgoingRequestMetricAttributes=sRe;var iRe=(t,e)=>{t&&(e[L.SEMATTRS_HTTP_FLAVOR]=t,t.toUpperCase()!=="QUIC"?e[L.SEMATTRS_NET_TRANSPORT]=L.NETTRANSPORTVALUES_IP_TCP:e[L.SEMATTRS_NET_TRANSPORT]=L.NETTRANSPORTVALUES_IP_UDP)};Y.setAttributesFromHttpKind=iRe;var aRe=(t,e)=>{let{statusCode:n,statusMessage:r,httpVersion:o,socket:s}=t,i={},a={};if(n!=null&&(a[L.ATTR_HTTP_RESPONSE_STATUS_CODE]=n),s){let{remoteAddress:c,remotePort:u}=s;i[L.SEMATTRS_NET_PEER_IP]=c,i[L.SEMATTRS_NET_PEER_PORT]=u,a[L.ATTR_NETWORK_PEER_ADDRESS]=c,a[L.ATTR_NETWORK_PEER_PORT]=u,a[L.ATTR_NETWORK_PROTOCOL_VERSION]=t.httpVersion}switch((0,Y.setResponseContentLengthAttribute)(t,i),n&&(i[L.SEMATTRS_HTTP_STATUS_CODE]=n,i[Nm.AttributeNames.HTTP_STATUS_TEXT]=(r||"").toUpperCase()),(0,Y.setAttributesFromHttpKind)(o,i),e){case 1:return a;case 2:return i}return Object.assign(i,a)};Y.getOutgoingRequestAttributesOnResponse=aRe;var cRe=t=>{let e={};return e[L.SEMATTRS_NET_PEER_PORT]=t[L.SEMATTRS_NET_PEER_PORT],e[L.SEMATTRS_HTTP_STATUS_CODE]=t[L.SEMATTRS_HTTP_STATUS_CODE],e[L.SEMATTRS_HTTP_FLAVOR]=t[L.SEMATTRS_HTTP_FLAVOR],e};Y.getOutgoingRequestMetricAttributesOnResponse=cRe;function xs(t,e){let n=t.split(":");if(n.length===1)return e==="http"?{host:n[0],port:"80"}:e==="https"?{host:n[0],port:"443"}:{host:n[0]};if(n.length===2)return{host:n[0],port:n[1]};if(n[0].startsWith("[")){if(n[n.length-1].endsWith("]")){if(e==="http")return{host:t,port:"80"};if(e==="https")return{host:t,port:"443"}}else if(n[n.length-2].endsWith("]"))return{host:n.slice(0,-1).join(":"),port:n[n.length-1]}}return{host:t}}function uRe(t,e){let n=t.headers.forwarded;if(n){for(let s of cH(n))if(s.host)return xs(s.host,s.proto)}let r=t.headers["x-forwarded-host"];if(typeof r=="string")return typeof t.headers["x-forwarded-proto"]=="string"?xs(r,t.headers["x-forwarded-proto"]):Array.isArray(t.headers["x-forwarded-proto"])?xs(r,t.headers["x-forwarded-proto"][0]):xs(r);if(Array.isArray(r)&&typeof r[0]=="string"&&r[0].length>0)return typeof t.headers["x-forwarded-proto"]=="string"?xs(r[0],t.headers["x-forwarded-proto"]):Array.isArray(t.headers["x-forwarded-proto"])?xs(r[0],t.headers["x-forwarded-proto"][0]):xs(r[0]);let o=t.headers.host;return typeof o=="string"&&o.length>0?xs(o,e):null}function iH(t){let e=t.headers.forwarded;if(e){for(let o of cH(e))if(o.for)return o.for}let n=t.headers["x-forwarded-for"];if(typeof n=="string")return n;if(Array.isArray(n))return n[0];let r=t.socket.remoteAddress;return r||null}Y.getRemoteClientAddress=iH;function lRe(t,e,n){var r,o;try{if(e.headers.host)return new URL((r=e.url)!==null&&r!==void 0?r:"/",`${t}://${e.headers.host}`);{let s=new URL((o=e.url)!==null&&o!==void 0?o:"/",`${t}://localhost`);return{pathname:s.pathname,search:s.search,toString:function(){return s.pathname+s.search}}}}catch(s){return n.verbose("Unable to get URL from request",s),{}}}var dRe=(t,e,n)=>{let r=t.headers,o=r["user-agent"],s=r["x-forwarded-for"],i=t.httpVersion,a=r.host,c=a?.replace(/^(.*)(:[0-9]{1,5})/,"$1")||"localhost",u=t.method,l=aH(u),d=uRe(t,e.component),p=e.serverName,_=iH(t),f={[L.ATTR_HTTP_REQUEST_METHOD]:l,[L.ATTR_URL_SCHEME]:e.component,[L.ATTR_SERVER_ADDRESS]:d?.host,[L.ATTR_NETWORK_PEER_ADDRESS]:t.socket.remoteAddress,[L.ATTR_NETWORK_PEER_PORT]:t.socket.remotePort,[L.ATTR_NETWORK_PROTOCOL_VERSION]:t.httpVersion,[L.ATTR_USER_AGENT_ORIGINAL]:o},E=lRe(e.component,t,n);E?.pathname!=null&&(f[L.ATTR_URL_PATH]=E.pathname),_!=null&&(f[L.ATTR_CLIENT_ADDRESS]=_),d?.port!=null&&(f[L.ATTR_SERVER_PORT]=Number(d.port)),u!==l&&(f[L.ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=u);let S={[L.SEMATTRS_HTTP_URL]:E.toString(),[L.SEMATTRS_HTTP_HOST]:a,[L.SEMATTRS_NET_HOST_NAME]:c,[L.SEMATTRS_HTTP_METHOD]:u,[L.SEMATTRS_HTTP_SCHEME]:e.component};switch(typeof s=="string"&&(S[L.SEMATTRS_HTTP_CLIENT_IP]=s.split(",")[0]),typeof p=="string"&&(S[L.SEMATTRS_HTTP_SERVER_NAME]=p),E?.pathname&&(S[L.SEMATTRS_HTTP_TARGET]=E?.pathname+E?.search||"/"),o!==void 0&&(S[L.SEMATTRS_HTTP_USER_AGENT]=o),(0,Y.setRequestContentLengthAttribute)(t,S),(0,Y.setAttributesFromHttpKind)(i,S),e.semconvStability){case 1:return Object.assign(f,e.hookAttributes);case 2:return Object.assign(S,e.hookAttributes)}return Object.assign(S,f,e.hookAttributes)};Y.getIncomingRequestAttributes=dRe;var pRe=t=>{let e={};return e[L.SEMATTRS_HTTP_SCHEME]=t[L.SEMATTRS_HTTP_SCHEME],e[L.SEMATTRS_HTTP_METHOD]=t[L.SEMATTRS_HTTP_METHOD],e[L.SEMATTRS_NET_HOST_NAME]=t[L.SEMATTRS_NET_HOST_NAME],e[L.SEMATTRS_HTTP_FLAVOR]=t[L.SEMATTRS_HTTP_FLAVOR],e};Y.getIncomingRequestMetricAttributes=pRe;var _Re=(t,e,n)=>{let{socket:r}=t,{statusCode:o,statusMessage:s}=e,i={[L.ATTR_HTTP_RESPONSE_STATUS_CODE]:o},a=(0,oH.getRPCMetadata)(od.context.active()),c={};if(r){let{localAddress:u,localPort:l,remoteAddress:d,remotePort:p}=r;c[L.SEMATTRS_NET_HOST_IP]=u,c[L.SEMATTRS_NET_HOST_PORT]=l,c[L.SEMATTRS_NET_PEER_IP]=d,c[L.SEMATTRS_NET_PEER_PORT]=p}switch(c[L.SEMATTRS_HTTP_STATUS_CODE]=o,c[Nm.AttributeNames.HTTP_STATUS_TEXT]=(s||"").toUpperCase(),a?.type===oH.RPCType.HTTP&&a.route!==void 0&&(c[L.SEMATTRS_HTTP_ROUTE]=a.route,i[L.ATTR_HTTP_ROUTE]=a.route),n){case 1:return i;case 2:return c}return Object.assign(c,i)};Y.getIncomingRequestAttributesOnResponse=_Re;var fRe=t=>{let e={};return e[L.SEMATTRS_HTTP_STATUS_CODE]=t[L.SEMATTRS_HTTP_STATUS_CODE],e[L.SEMATTRS_NET_HOST_PORT]=t[L.SEMATTRS_NET_HOST_PORT],t[L.SEMATTRS_HTTP_ROUTE]!==void 0&&(e[L.SEMATTRS_HTTP_ROUTE]=t[L.SEMATTRS_HTTP_ROUTE]),e};Y.getIncomingRequestMetricAttributesOnResponse=fRe;var mRe=t=>{let e={};return t[L.ATTR_HTTP_ROUTE]!==void 0&&(e[L.ATTR_HTTP_ROUTE]=t[L.SEMATTRS_HTTP_ROUTE]),t[L.ATTR_HTTP_RESPONSE_STATUS_CODE]&&(e[L.ATTR_HTTP_RESPONSE_STATUS_CODE]=t[L.ATTR_HTTP_RESPONSE_STATUS_CODE]),e};Y.getIncomingStableRequestMetricAttributesOnResponse=mRe;function ERe(t,e){let n=new Map;for(let r=0,o=e.length;r<o;r++){let s=e[r].toLowerCase();n.set(s,s.replace(/-/g,"_"))}return(r,o)=>{for(let s of n.keys()){let i=o(s);if(i===void 0)continue;let a=n.get(s),c=`http.${t}.header.${a}`;typeof i=="string"?r.setAttribute(c,[i]):Array.isArray(i)?r.setAttribute(c,i):r.setAttribute(c,[i])}}}Y.headerCapture=ERe;var SRe=new Set(["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]);function aH(t){if(t==null)return"GET";let e=t.toUpperCase();return SRe.has(e)?e:"_OTHER"}function cH(t){try{return YAe(t)}catch{return[]}}});var dH=m(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});Cm.HttpInstrumentation=void 0;var Q=(x(),b(B)),Ic=Se(),lH=eR(),gRe=require("url"),hRe=fB(),tr=fe(),KR=Se(),WR=require("events"),je=(zn(),b(Wn)),Be=uH(),zR=class extends tr.InstrumentationBase{constructor(e={}){super("@opentelemetry/instrumentation-http",hRe.VERSION,e),this._spanNotEnded=new WeakSet,this._semconvStability=2,this._headerCapture=this._createHeaderCapture();for(let n of(0,KR.getEnv)().OTEL_SEMCONV_STABILITY_OPT_IN)if(n.toLowerCase()==="http/dup"){this._semconvStability=3;break}else n.toLowerCase()==="http"&&(this._semconvStability=1)}_updateMetricInstruments(){this._oldHttpServerDurationHistogram=this.meter.createHistogram("http.server.duration",{description:"Measures the duration of inbound HTTP requests.",unit:"ms",valueType:Q.ValueType.DOUBLE}),this._oldHttpClientDurationHistogram=this.meter.createHistogram("http.client.duration",{description:"Measures the duration of outbound HTTP requests.",unit:"ms",valueType:Q.ValueType.DOUBLE}),this._stableHttpServerDurationHistogram=this.meter.createHistogram(je.METRIC_HTTP_SERVER_REQUEST_DURATION,{description:"Duration of HTTP server requests.",unit:"s",valueType:Q.ValueType.DOUBLE,advice:{explicitBucketBoundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]}}),this._stableHttpClientDurationHistogram=this.meter.createHistogram(je.METRIC_HTTP_CLIENT_REQUEST_DURATION,{description:"Duration of HTTP client requests.",unit:"s",valueType:Q.ValueType.DOUBLE,advice:{explicitBucketBoundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]}})}_recordServerDuration(e,n,r){(this._semconvStability&2)===2&&this._oldHttpServerDurationHistogram.record(e,n),(this._semconvStability&1)===1&&this._stableHttpServerDurationHistogram.record(e/1e3,r)}_recordClientDuration(e,n,r){(this._semconvStability&2)===2&&this._oldHttpClientDurationHistogram.record(e,n),(this._semconvStability&1)===1&&this._stableHttpClientDurationHistogram.record(e/1e3,r)}setConfig(e={}){super.setConfig(e),this._headerCapture=this._createHeaderCapture()}init(){return[this._getHttpsInstrumentation(),this._getHttpInstrumentation()]}_getHttpInstrumentation(){return new tr.InstrumentationNodeModuleDefinition("http",["*"],e=>{let n=e[Symbol.toStringTag]==="Module";if(!this.getConfig().disableOutgoingRequestInstrumentation){let r=this._wrap(e,"request",this._getPatchOutgoingRequestFunction("http")),o=this._wrap(e,"get",this._getPatchOutgoingGetFunction(r));n&&(e.default.request=r,e.default.get=o)}return this.getConfig().disableIncomingRequestInstrumentation||this._wrap(e.Server.prototype,"emit",this._getPatchIncomingRequestFunction("http")),e},e=>{e!==void 0&&(this.getConfig().disableOutgoingRequestInstrumentation||(this._unwrap(e,"request"),this._unwrap(e,"get")),this.getConfig().disableIncomingRequestInstrumentation||this._unwrap(e.Server.prototype,"emit"))})}_getHttpsInstrumentation(){return new tr.InstrumentationNodeModuleDefinition("https",["*"],e=>{let n=e[Symbol.toStringTag]==="Module";if(!this.getConfig().disableOutgoingRequestInstrumentation){let r=this._wrap(e,"request",this._getPatchHttpsOutgoingRequestFunction("https")),o=this._wrap(e,"get",this._getPatchHttpsOutgoingGetFunction(r));n&&(e.default.request=r,e.default.get=o)}return this.getConfig().disableIncomingRequestInstrumentation||this._wrap(e.Server.prototype,"emit",this._getPatchIncomingRequestFunction("https")),e},e=>{e!==void 0&&(this.getConfig().disableOutgoingRequestInstrumentation||(this._unwrap(e,"request"),this._unwrap(e,"get")),this.getConfig().disableIncomingRequestInstrumentation||this._unwrap(e.Server.prototype,"emit"))})}_getPatchIncomingRequestFunction(e){return n=>this._incomingRequestFunction(e,n)}_getPatchOutgoingRequestFunction(e){return n=>this._outgoingRequestFunction(e,n)}_getPatchOutgoingGetFunction(e){return n=>function(o,...s){let i=e(o,...s);return i.end(),i}}_getPatchHttpsOutgoingRequestFunction(e){return n=>{let r=this;return function(s,...i){var a;return e==="https"&&typeof s=="object"&&((a=s?.constructor)===null||a===void 0?void 0:a.name)!=="URL"&&(s=Object.assign({},s),r._setDefaultOptions(s)),r._getPatchOutgoingRequestFunction(e)(n)(s,...i)}}}_setDefaultOptions(e){e.protocol=e.protocol||"https:",e.port=e.port||443}_getPatchHttpsOutgoingGetFunction(e){return n=>{let r=this;return function(s,...i){return r._getPatchOutgoingGetFunction(e)(n)(s,...i)}}}_traceClientRequest(e,n,r,o,s){this.getConfig().requestHook&&this._callRequestHook(n,e);let i=!1;return e.prependListener("response",a=>{this._diag.debug("outgoingRequest on response()"),e.listenerCount("response")<=1&&a.resume();let c=(0,Be.getOutgoingRequestAttributesOnResponse)(a,this._semconvStability);n.setAttributes(c),o=Object.assign(o,(0,Be.getOutgoingRequestMetricAttributesOnResponse)(c)),this.getConfig().responseHook&&this._callResponseHook(n,a),this._headerCapture.client.captureRequestHeaders(n,l=>e.getHeader(l)),this._headerCapture.client.captureResponseHeaders(n,l=>a.headers[l]),Q.context.bind(Q.context.active(),a);let u=()=>{if(this._diag.debug("outgoingRequest on end()"),i)return;i=!0;let l;a.aborted&&!a.complete?l={code:Q.SpanStatusCode.ERROR}:l={code:(0,Be.parseResponseStatus)(Q.SpanKind.CLIENT,a.statusCode)},n.setStatus(l),this.getConfig().applyCustomAttributesOnSpan&&(0,tr.safeExecuteInTheMiddle)(()=>this.getConfig().applyCustomAttributesOnSpan(n,e,a),()=>{},!0),this._closeHttpSpan(n,Q.SpanKind.CLIENT,r,o,s)};a.on("end",u),lH.lt(process.version,"16.0.0")&&a.on("close",u),a.on(WR.errorMonitor,l=>{this._diag.debug("outgoingRequest on error()",l),!i&&(i=!0,(0,Be.setSpanWithError)(n,l,this._semconvStability),n.setStatus({code:Q.SpanStatusCode.ERROR,message:l.message}),this._closeHttpSpan(n,Q.SpanKind.CLIENT,r,o,s))})}),e.on("close",()=>{this._diag.debug("outgoingRequest on request close()"),!(e.aborted||i)&&(i=!0,this._closeHttpSpan(n,Q.SpanKind.CLIENT,r,o,s))}),e.on(WR.errorMonitor,a=>{this._diag.debug("outgoingRequest on request error()",a),!i&&(i=!0,(0,Be.setSpanWithError)(n,a,this._semconvStability),this._closeHttpSpan(n,Q.SpanKind.CLIENT,r,o,s))}),this._diag.debug("http.ClientRequest return request"),e}_incomingRequestFunction(e,n){let r=this;return function(s,...i){if(s!=="request")return n.apply(this,[s,...i]);let a=i[0],c=i[1],u=a.method||"GET";if(r._diag.debug(`${e} instrumentation incomingRequest`),(0,tr.safeExecuteInTheMiddle)(()=>{var A,O;return(O=(A=r.getConfig()).ignoreIncomingRequestHook)===null||O===void 0?void 0:O.call(A,a)},A=>{A!=null&&r._diag.error("caught ignoreIncomingRequestHook error: ",A)},!0))return Q.context.with((0,Ic.suppressTracing)(Q.context.active()),()=>(Q.context.bind(Q.context.active(),a),Q.context.bind(Q.context.active(),c),n.apply(this,[s,...i])));let l=a.headers,d=(0,Be.getIncomingRequestAttributes)(a,{component:e,serverName:r.getConfig().serverName,hookAttributes:r._callStartSpanHook(a,r.getConfig().startIncomingSpanHook),semconvStability:r._semconvStability},r._diag),p={kind:Q.SpanKind.SERVER,attributes:d},_=(0,Ic.hrTime)(),f=(0,Be.getIncomingRequestMetricAttributes)(d),E={[je.ATTR_HTTP_REQUEST_METHOD]:d[je.ATTR_HTTP_REQUEST_METHOD],[je.ATTR_URL_SCHEME]:d[je.ATTR_URL_SCHEME]};d[je.ATTR_NETWORK_PROTOCOL_VERSION]&&(E[je.ATTR_NETWORK_PROTOCOL_VERSION]=d[je.ATTR_NETWORK_PROTOCOL_VERSION]);let S=Q.propagation.extract(Q.ROOT_CONTEXT,l),h=r._startHttpSpan(u,p,S),R={type:KR.RPCType.HTTP,span:h};return Q.context.with((0,KR.setRPCMetadata)(Q.trace.setSpan(S,h),R),()=>{Q.context.bind(Q.context.active(),a),Q.context.bind(Q.context.active(),c),r.getConfig().requestHook&&r._callRequestHook(h,a),r.getConfig().responseHook&&r._callResponseHook(h,c),r._headerCapture.server.captureRequestHeaders(h,O=>a.headers[O]);let A=!1;return c.on("close",()=>{A||r._onServerResponseFinish(a,c,h,f,E,_)}),c.on(WR.errorMonitor,O=>{A=!0,r._onServerResponseError(h,f,E,_,O)}),(0,tr.safeExecuteInTheMiddle)(()=>n.apply(this,[s,...i]),O=>{if(O)throw(0,Be.setSpanWithError)(h,O,r._semconvStability),r._closeHttpSpan(h,Q.SpanKind.SERVER,_,f,E),O})})}}_outgoingRequestFunction(e,n){let r=this;return function(s,...i){if(!(0,Be.isValidOptionsType)(s))return n.apply(this,[s,...i]);let a=typeof i[0]=="object"&&(typeof s=="string"||s instanceof gRe.URL)?i.shift():void 0,{method:c,invalidUrl:u,optionsParsed:l}=(0,Be.getRequestInfo)(r._diag,s,a);if(e==="http"&&lH.lt(process.version,"9.0.0")&&l.protocol==="https:")return n.apply(this,[l,...i]);if((0,tr.safeExecuteInTheMiddle)(()=>{var y,M;return(M=(y=r.getConfig()).ignoreOutgoingRequestHook)===null||M===void 0?void 0:M.call(y,l)},y=>{y!=null&&r._diag.error("caught ignoreOutgoingRequestHook error: ",y)},!0))return n.apply(this,[l,...i]);let{hostname:d,port:p}=(0,Be.extractHostnameAndPort)(l),_=(0,Be.getOutgoingRequestAttributes)(l,{component:e,port:p,hostname:d,hookAttributes:r._callStartSpanHook(l,r.getConfig().startOutgoingSpanHook)},r._semconvStability),f=(0,Ic.hrTime)(),E=(0,Be.getOutgoingRequestMetricAttributes)(_),S={[je.ATTR_HTTP_REQUEST_METHOD]:_[je.ATTR_HTTP_REQUEST_METHOD],[je.ATTR_SERVER_ADDRESS]:_[je.ATTR_SERVER_ADDRESS],[je.ATTR_SERVER_PORT]:_[je.ATTR_SERVER_PORT]};_[je.ATTR_HTTP_RESPONSE_STATUS_CODE]&&(S[je.ATTR_HTTP_RESPONSE_STATUS_CODE]=_[je.ATTR_HTTP_RESPONSE_STATUS_CODE]),_[je.ATTR_NETWORK_PROTOCOL_VERSION]&&(S[je.ATTR_NETWORK_PROTOCOL_VERSION]=_[je.ATTR_NETWORK_PROTOCOL_VERSION]);let h={kind:Q.SpanKind.CLIENT,attributes:_},R=r._startHttpSpan(c,h),A=Q.context.active(),O=Q.trace.setSpan(A,R);return l.headers?l.headers=Object.assign({},l.headers):l.headers={},Q.propagation.inject(O,l.headers),Q.context.with(O,()=>{let y=i[i.length-1];typeof y=="function"&&(i[i.length-1]=Q.context.bind(A,y));let M=(0,tr.safeExecuteInTheMiddle)(()=>u?n.apply(this,[s,...i]):n.apply(this,[l,...i]),I=>{if(I)throw(0,Be.setSpanWithError)(R,I,r._semconvStability),r._closeHttpSpan(R,Q.SpanKind.CLIENT,f,E,S),I});return r._diag.debug(`${e} instrumentation outgoingRequest`),Q.context.bind(A,M),r._traceClientRequest(M,R,f,E,S)})}}_onServerResponseFinish(e,n,r,o,s,i){let a=(0,Be.getIncomingRequestAttributesOnResponse)(e,n,this._semconvStability);o=Object.assign(o,(0,Be.getIncomingRequestMetricAttributesOnResponse)(a)),s=Object.assign(s,(0,Be.getIncomingStableRequestMetricAttributesOnResponse)(a)),this._headerCapture.server.captureResponseHeaders(r,u=>n.getHeader(u)),r.setAttributes(a).setStatus({code:(0,Be.parseResponseStatus)(Q.SpanKind.SERVER,n.statusCode)});let c=a[je.SEMATTRS_HTTP_ROUTE];c&&r.updateName(`${e.method||"GET"} ${c}`),this.getConfig().applyCustomAttributesOnSpan&&(0,tr.safeExecuteInTheMiddle)(()=>this.getConfig().applyCustomAttributesOnSpan(r,e,n),()=>{},!0),this._closeHttpSpan(r,Q.SpanKind.SERVER,i,o,s)}_onServerResponseError(e,n,r,o,s){(0,Be.setSpanWithError)(e,s,this._semconvStability),this._closeHttpSpan(e,Q.SpanKind.SERVER,o,n,r)}_startHttpSpan(e,n,r=Q.context.active()){let o=n.kind===Q.SpanKind.CLIENT?this.getConfig().requireParentforOutgoingSpans:this.getConfig().requireParentforIncomingSpans,s,i=Q.trace.getSpan(r);return o===!0&&i===void 0?s=Q.trace.wrapSpanContext(Q.INVALID_SPAN_CONTEXT):o===!0&&i?.spanContext().isRemote?s=i:s=this.tracer.startSpan(e,n,r),this._spanNotEnded.add(s),s}_closeHttpSpan(e,n,r,o,s){if(!this._spanNotEnded.has(e))return;e.end(),this._spanNotEnded.delete(e);let i=(0,Ic.hrTimeToMilliseconds)((0,Ic.hrTimeDuration)(r,(0,Ic.hrTime)()));n===Q.SpanKind.SERVER?this._recordServerDuration(i,o,s):n===Q.SpanKind.CLIENT&&this._recordClientDuration(i,o,s)}_callResponseHook(e,n){(0,tr.safeExecuteInTheMiddle)(()=>this.getConfig().responseHook(e,n),()=>{},!0)}_callRequestHook(e,n){(0,tr.safeExecuteInTheMiddle)(()=>this.getConfig().requestHook(e,n),()=>{},!0)}_callStartSpanHook(e,n){if(typeof n=="function")return(0,tr.safeExecuteInTheMiddle)(()=>n(e),()=>{},!0)}_createHeaderCapture(){var e,n,r,o,s,i,a,c,u,l,d,p;let _=this.getConfig();return{client:{captureRequestHeaders:(0,Be.headerCapture)("request",(r=(n=(e=_.headersToSpanAttributes)===null||e===void 0?void 0:e.client)===null||n===void 0?void 0:n.requestHeaders)!==null&&r!==void 0?r:[]),captureResponseHeaders:(0,Be.headerCapture)("response",(i=(s=(o=_.headersToSpanAttributes)===null||o===void 0?void 0:o.client)===null||s===void 0?void 0:s.responseHeaders)!==null&&i!==void 0?i:[])},server:{captureRequestHeaders:(0,Be.headerCapture)("request",(u=(c=(a=_.headersToSpanAttributes)===null||a===void 0?void 0:a.server)===null||c===void 0?void 0:c.requestHeaders)!==null&&u!==void 0?u:[]),captureResponseHeaders:(0,Be.headerCapture)("response",(p=(d=(l=_.headersToSpanAttributes)===null||l===void 0?void 0:l.server)===null||d===void 0?void 0:d.responseHeaders)!==null&&p!==void 0?p:[])}}}};Cm.HttpInstrumentation=zR});var pH=m(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});vm.HttpInstrumentation=void 0;var TRe=dH();Object.defineProperty(vm,"HttpInstrumentation",{enumerable:!0,get:function(){return TRe.HttpInstrumentation}})});function rt(t){let e={},n=t.length;for(let r=0;r<n;r++){let o=t[r];o&&(e[String(o).toUpperCase().replace(/[-.]/g,"_")]=o)}return e}var oO=$(()=>{});var kF,VF,BF,GF,HF,$F,FF,jF,qF,YF,KF,WF,zF,XF,JF,ZF,QF,ej,tj,nj,rj,oj,sj,ij,aj,cj,uj,lj,dj,pj,_j,fj,mj,Ej,Sj,gj,hj,Tj,Aj,Rj,yj,Oj,Nj,Cj,vj,Ij,Pj,bj,Mj,Lj,xj,Dj,Uj,wj,kj,Vj,Bj,Gj,Hj,$j,Fj,jj,qj,Yj,Kj,Wj,zj,Xj,Jj,Zj,Qj,eq,tq,nq,rq,oq,sq,iq,aq,cq,uq,lq,dq,pq,_q,fq,mq,Eq,Sq,gq,hq,Tq,Aq,Rq,yq,Oq,Nq,Cq,vq,Iq,Pq,bq,Mq,Lq,xq,Dq,Uq,wq,kq,Vq,Bq,Gq,Hq,$q,Fq,jq,qq,Yq,Kq,Wq,zq,Xq,Jq,Zq,Qq,eY,tY,nY,nNe,sO,rNe,oNe,sNe,iNe,iO,aNe,cNe,uNe,lNe,dNe,pNe,_Ne,fNe,mNe,ENe,SNe,gNe,hNe,TNe,ANe,RNe,yNe,ONe,aO,NNe,CNe,vNe,INe,PNe,bNe,MNe,LNe,xNe,DNe,UNe,wNe,kNe,VNe,BNe,GNe,HNe,$Ne,FNe,jNe,qNe,YNe,KNe,WNe,zNe,XNe,JNe,ZNe,QNe,eCe,tCe,nCe,rCe,oCe,Cd,Kc,cO,sCe,iCe,TE,aCe,cCe,uCe,lCe,dCe,pCe,_Ce,vd,fCe,mCe,ECe,SCe,gCe,hCe,TCe,ACe,RCe,yCe,OCe,NCe,CCe,vCe,ICe,PCe,bCe,MCe,LCe,xCe,DCe,UCe,wCe,uO,kCe,VCe,BCe,GCe,HCe,$Ce,FCe,jCe,qCe,YCe,KCe,WCe,zCe,XCe,JCe,ZCe,QCe,eve,tve,lO,nve,dO,rve,ove,sve,ive,ave,cve,uve,lve,dve,rY,oY,sY,iY,aY,cY,uY,lY,dY,pY,_Y,fY,mY,EY,SY,gY,hY,TY,AY,RY,yY,OY,NY,CY,vY,IY,PY,bY,MY,LY,xY,DY,UY,wY,kY,VY,BY,GY,HY,$Y,FY,jY,qY,YY,KY,WY,zY,pve,_ve,fve,mve,Eve,Sve,gve,hve,Tve,Ave,Rve,yve,Ove,Nve,Cve,vve,Ive,Pve,bve,Mve,Lve,xve,Dve,Uve,wve,kve,Vve,Bve,Gve,Hve,$ve,Fve,jve,qve,Yve,Kve,Wve,zve,Xve,Jve,Zve,Qve,eIe,tIe,nIe,rIe,oIe,sIe,XY,JY,ZY,QY,eK,tK,nK,rK,oK,sK,iK,iIe,aIe,cIe,uIe,lIe,dIe,pIe,_Ie,fIe,mIe,EIe,SIe,aK,cK,uK,lK,dK,gIe,hIe,TIe,AIe,RIe,yIe,pK,_K,fK,OIe,NIe,CIe,vIe,mK,EK,SK,gK,IIe,PIe,bIe,MIe,LIe,hK,TK,AK,RK,yK,OK,NK,xIe,DIe,UIe,wIe,kIe,VIe,BIe,GIe,CK,vK,IK,PK,bK,HIe,$Ie,FIe,jIe,qIe,YIe,MK,LK,xK,DK,UK,wK,kK,VK,BK,GK,HK,$K,FK,jK,qK,YK,KK,WK,zK,XK,JK,KIe,WIe,zIe,XIe,JIe,ZIe,QIe,ePe,tPe,nPe,rPe,oPe,sPe,iPe,aPe,cPe,uPe,lPe,dPe,pPe,_Pe,fPe,ZK,QK,eW,tW,nW,mPe,EPe,SPe,gPe,hPe,TPe,rW,oW,APe,RPe,yPe,sW,iW,OPe,NPe,CPe,aW,cW,uW,lW,dW,pW,_W,fW,mW,EW,SW,gW,hW,TW,AW,RW,yW,vPe,IPe,PPe,bPe,MPe,LPe,xPe,DPe,UPe,wPe,kPe,VPe,BPe,GPe,HPe,$Pe,FPe,jPe,OW,NW,qPe,YPe,KPe,CW=$(()=>{oO();kF="aws.lambda.invoked_arn",VF="db.system",BF="db.connection_string",GF="db.user",HF="db.jdbc.driver_classname",$F="db.name",FF="db.statement",jF="db.operation",qF="db.mssql.instance_name",YF="db.cassandra.keyspace",KF="db.cassandra.page_size",WF="db.cassandra.consistency_level",zF="db.cassandra.table",XF="db.cassandra.idempotence",JF="db.cassandra.speculative_execution_count",ZF="db.cassandra.coordinator.id",QF="db.cassandra.coordinator.dc",ej="db.hbase.namespace",tj="db.redis.database_index",nj="db.mongodb.collection",rj="db.sql.table",oj="exception.type",sj="exception.message",ij="exception.stacktrace",aj="exception.escaped",cj="faas.trigger",uj="faas.execution",lj="faas.document.collection",dj="faas.document.operation",pj="faas.document.time",_j="faas.document.name",fj="faas.time",mj="faas.cron",Ej="faas.coldstart",Sj="faas.invoked_name",gj="faas.invoked_provider",hj="faas.invoked_region",Tj="net.transport",Aj="net.peer.ip",Rj="net.peer.port",yj="net.peer.name",Oj="net.host.ip",Nj="net.host.port",Cj="net.host.name",vj="net.host.connection.type",Ij="net.host.connection.subtype",Pj="net.host.carrier.name",bj="net.host.carrier.mcc",Mj="net.host.carrier.mnc",Lj="net.host.carrier.icc",xj="peer.service",Dj="enduser.id",Uj="enduser.role",wj="enduser.scope",kj="thread.id",Vj="thread.name",Bj="code.function",Gj="code.namespace",Hj="code.filepath",$j="code.lineno",Fj="http.method",jj="http.url",qj="http.target",Yj="http.host",Kj="http.scheme",Wj="http.status_code",zj="http.flavor",Xj="http.user_agent",Jj="http.request_content_length",Zj="http.request_content_length_uncompressed",Qj="http.response_content_length",eq="http.response_content_length_uncompressed",tq="http.server_name",nq="http.route",rq="http.client_ip",oq="aws.dynamodb.table_names",sq="aws.dynamodb.consumed_capacity",iq="aws.dynamodb.item_collection_metrics",aq="aws.dynamodb.provisioned_read_capacity",cq="aws.dynamodb.provisioned_write_capacity",uq="aws.dynamodb.consistent_read",lq="aws.dynamodb.projection",dq="aws.dynamodb.limit",pq="aws.dynamodb.attributes_to_get",_q="aws.dynamodb.index_name",fq="aws.dynamodb.select",mq="aws.dynamodb.global_secondary_indexes",Eq="aws.dynamodb.local_secondary_indexes",Sq="aws.dynamodb.exclusive_start_table",gq="aws.dynamodb.table_count",hq="aws.dynamodb.scan_forward",Tq="aws.dynamodb.segment",Aq="aws.dynamodb.total_segments",Rq="aws.dynamodb.count",yq="aws.dynamodb.scanned_count",Oq="aws.dynamodb.attribute_definitions",Nq="aws.dynamodb.global_secondary_index_updates",Cq="messaging.system",vq="messaging.destination",Iq="messaging.destination_kind",Pq="messaging.temp_destination",bq="messaging.protocol",Mq="messaging.protocol_version",Lq="messaging.url",xq="messaging.message_id",Dq="messaging.conversation_id",Uq="messaging.message_payload_size_bytes",wq="messaging.message_payload_compressed_size_bytes",kq="messaging.operation",Vq="messaging.consumer_id",Bq="messaging.rabbitmq.routing_key",Gq="messaging.kafka.message_key",Hq="messaging.kafka.consumer_group",$q="messaging.kafka.client_id",Fq="messaging.kafka.partition",jq="messaging.kafka.tombstone",qq="rpc.system",Yq="rpc.service",Kq="rpc.method",Wq="rpc.grpc.status_code",zq="rpc.jsonrpc.version",Xq="rpc.jsonrpc.request_id",Jq="rpc.jsonrpc.error_code",Zq="rpc.jsonrpc.error_message",Qq="message.type",eY="message.id",tY="message.compressed_size",nY="message.uncompressed_size",nNe=kF,sO=VF,rNe=BF,oNe=GF,sNe=HF,iNe=$F,iO=FF,aNe=jF,cNe=qF,uNe=YF,lNe=KF,dNe=WF,pNe=zF,_Ne=XF,fNe=JF,mNe=ZF,ENe=QF,SNe=ej,gNe=tj,hNe=nj,TNe=rj,ANe=oj,RNe=sj,yNe=ij,ONe=aj,aO=cj,NNe=uj,CNe=lj,vNe=dj,INe=pj,PNe=_j,bNe=fj,MNe=mj,LNe=Ej,xNe=Sj,DNe=gj,UNe=hj,wNe=Tj,kNe=Aj,VNe=Rj,BNe=yj,GNe=Oj,HNe=Nj,$Ne=Cj,FNe=vj,jNe=Ij,qNe=Pj,YNe=bj,KNe=Mj,WNe=Lj,zNe=xj,XNe=Dj,JNe=Uj,ZNe=wj,QNe=kj,eCe=Vj,tCe=Bj,nCe=Gj,rCe=Hj,oCe=$j,Cd=Fj,Kc=jj,cO=qj,sCe=Yj,iCe=Kj,TE=Wj,aCe=zj,cCe=Xj,uCe=Jj,lCe=Zj,dCe=Qj,pCe=eq,_Ce=tq,vd=nq,fCe=rq,mCe=oq,ECe=sq,SCe=iq,gCe=aq,hCe=cq,TCe=uq,ACe=lq,RCe=dq,yCe=pq,OCe=_q,NCe=fq,CCe=mq,vCe=Eq,ICe=Sq,PCe=gq,bCe=hq,MCe=Tq,LCe=Aq,xCe=Rq,DCe=yq,UCe=Oq,wCe=Nq,uO=Cq,kCe=vq,VCe=Iq,BCe=Pq,GCe=bq,HCe=Mq,$Ce=Lq,FCe=xq,jCe=Dq,qCe=Uq,YCe=wq,KCe=kq,WCe=Vq,zCe=Bq,XCe=Gq,JCe=Hq,ZCe=$q,QCe=Fq,eve=jq,tve=qq,lO=Yq,nve=Kq,dO=Wq,rve=zq,ove=Xq,sve=Jq,ive=Zq,ave=Qq,cve=eY,uve=tY,lve=nY,dve=rt([kF,VF,BF,GF,HF,$F,FF,jF,qF,YF,KF,WF,zF,XF,JF,ZF,QF,ej,tj,nj,rj,oj,sj,ij,aj,cj,uj,lj,dj,pj,_j,fj,mj,Ej,Sj,gj,hj,Tj,Aj,Rj,yj,Oj,Nj,Cj,vj,Ij,Pj,bj,Mj,Lj,xj,Dj,Uj,wj,kj,Vj,Bj,Gj,Hj,$j,Fj,jj,qj,Yj,Kj,Wj,zj,Xj,Jj,Zj,Qj,eq,tq,nq,rq,oq,sq,iq,aq,cq,uq,lq,dq,pq,_q,fq,mq,Eq,Sq,gq,hq,Tq,Aq,Rq,yq,Oq,Nq,Cq,vq,Iq,Pq,bq,Mq,Lq,xq,Dq,Uq,wq,kq,Vq,Bq,Gq,Hq,$q,Fq,jq,qq,Yq,Kq,Wq,zq,Xq,Jq,Zq,Qq,eY,tY,nY]),rY="other_sql",oY="mssql",sY="mysql",iY="oracle",aY="db2",cY="postgresql",uY="redshift",lY="hive",dY="cloudscape",pY="hsqldb",_Y="progress",fY="maxdb",mY="hanadb",EY="ingres",SY="firstsql",gY="edb",hY="cache",TY="adabas",AY="firebird",RY="derby",yY="filemaker",OY="informix",NY="instantdb",CY="interbase",vY="mariadb",IY="netezza",PY="pervasive",bY="pointbase",MY="sqlite",LY="sybase",xY="teradata",DY="vertica",UY="h2",wY="coldfusion",kY="cassandra",VY="hbase",BY="mongodb",GY="redis",HY="couchbase",$Y="couchdb",FY="cosmosdb",jY="dynamodb",qY="neo4j",YY="geode",KY="elasticsearch",WY="memcached",zY="cockroachdb",pve=rY,_ve=oY,fve=sY,mve=iY,Eve=aY,Sve=cY,gve=uY,hve=lY,Tve=dY,Ave=pY,Rve=_Y,yve=fY,Ove=mY,Nve=EY,Cve=SY,vve=gY,Ive=hY,Pve=TY,bve=AY,Mve=RY,Lve=yY,xve=OY,Dve=NY,Uve=CY,wve=vY,kve=IY,Vve=PY,Bve=bY,Gve=MY,Hve=LY,$ve=xY,Fve=DY,jve=UY,qve=wY,Yve=kY,Kve=VY,Wve=BY,zve=GY,Xve=HY,Jve=$Y,Zve=FY,Qve=jY,eIe=qY,tIe=YY,nIe=KY,rIe=WY,oIe=zY,sIe=rt([rY,oY,sY,iY,aY,cY,uY,lY,dY,pY,_Y,fY,mY,EY,SY,gY,hY,TY,AY,RY,yY,OY,NY,CY,vY,IY,PY,bY,MY,LY,xY,DY,UY,wY,kY,VY,BY,GY,HY,$Y,FY,jY,qY,YY,KY,WY,zY]),XY="all",JY="each_quorum",ZY="quorum",QY="local_quorum",eK="one",tK="two",nK="three",rK="local_one",oK="any",sK="serial",iK="local_serial",iIe=XY,aIe=JY,cIe=ZY,uIe=QY,lIe=eK,dIe=tK,pIe=nK,_Ie=rK,fIe=oK,mIe=sK,EIe=iK,SIe=rt([XY,JY,ZY,QY,eK,tK,nK,rK,oK,sK,iK]),aK="datasource",cK="http",uK="pubsub",lK="timer",dK="other",gIe=aK,hIe=cK,TIe=uK,AIe=lK,RIe=dK,yIe=rt([aK,cK,uK,lK,dK]),pK="insert",_K="edit",fK="delete",OIe=pK,NIe=_K,CIe=fK,vIe=rt([pK,_K,fK]),mK="alibaba_cloud",EK="aws",SK="azure",gK="gcp",IIe=mK,PIe=EK,bIe=SK,MIe=gK,LIe=rt([mK,EK,SK,gK]),hK="ip_tcp",TK="ip_udp",AK="ip",RK="unix",yK="pipe",OK="inproc",NK="other",xIe=hK,DIe=TK,UIe=AK,wIe=RK,kIe=yK,VIe=OK,BIe=NK,GIe=rt([hK,TK,AK,RK,yK,OK,NK]),CK="wifi",vK="wired",IK="cell",PK="unavailable",bK="unknown",HIe=CK,$Ie=vK,FIe=IK,jIe=PK,qIe=bK,YIe=rt([CK,vK,IK,PK,bK]),MK="gprs",LK="edge",xK="umts",DK="cdma",UK="evdo_0",wK="evdo_a",kK="cdma2000_1xrtt",VK="hsdpa",BK="hsupa",GK="hspa",HK="iden",$K="evdo_b",FK="lte",jK="ehrpd",qK="hspap",YK="gsm",KK="td_scdma",WK="iwlan",zK="nr",XK="nrnsa",JK="lte_ca",KIe=MK,WIe=LK,zIe=xK,XIe=DK,JIe=UK,ZIe=wK,QIe=kK,ePe=VK,tPe=BK,nPe=GK,rPe=HK,oPe=$K,sPe=FK,iPe=jK,aPe=qK,cPe=YK,uPe=KK,lPe=WK,dPe=zK,pPe=XK,_Pe=JK,fPe=rt([MK,LK,xK,DK,UK,wK,kK,VK,BK,GK,HK,$K,FK,jK,qK,YK,KK,WK,zK,XK,JK]),ZK="1.0",QK="1.1",eW="2.0",tW="SPDY",nW="QUIC",mPe=ZK,EPe=QK,SPe=eW,gPe=tW,hPe=nW,TPe={HTTP_1_0:ZK,HTTP_1_1:QK,HTTP_2_0:eW,SPDY:tW,QUIC:nW},rW="queue",oW="topic",APe=rW,RPe=oW,yPe=rt([rW,oW]),sW="receive",iW="process",OPe=sW,NPe=iW,CPe=rt([sW,iW]),aW=0,cW=1,uW=2,lW=3,dW=4,pW=5,_W=6,fW=7,mW=8,EW=9,SW=10,gW=11,hW=12,TW=13,AW=14,RW=15,yW=16,vPe=aW,IPe=cW,PPe=uW,bPe=lW,MPe=dW,LPe=pW,xPe=_W,DPe=fW,UPe=mW,wPe=EW,kPe=SW,VPe=gW,BPe=hW,GPe=TW,HPe=AW,$Pe=RW,FPe=yW,jPe={OK:aW,CANCELLED:cW,UNKNOWN:uW,INVALID_ARGUMENT:lW,DEADLINE_EXCEEDED:dW,NOT_FOUND:pW,ALREADY_EXISTS:_W,PERMISSION_DENIED:fW,RESOURCE_EXHAUSTED:mW,FAILED_PRECONDITION:EW,ABORTED:SW,OUT_OF_RANGE:gW,UNIMPLEMENTED:hW,INTERNAL:TW,UNAVAILABLE:AW,DATA_LOSS:RW,UNAUTHENTICATED:yW},OW="SENT",NW="RECEIVED",qPe=OW,YPe=NW,KPe=rt([OW,NW])});var vW=$(()=>{CW()});var IW,PW,bW,MW,LW,xW,DW,UW,wW,kW,VW,BW,GW,HW,$W,FW,jW,qW,YW,KW,WW,zW,XW,JW,ZW,QW,e2,t2,n2,r2,o2,s2,i2,a2,c2,u2,l2,d2,p2,_2,f2,m2,E2,S2,g2,h2,T2,A2,R2,y2,O2,N2,C2,v2,I2,P2,b2,M2,L2,x2,D2,U2,w2,k2,V2,B2,G2,H2,$2,F2,j2,q2,Y2,K2,W2,z2,X2,J2,Z2,Q2,e4,WPe,zPe,XPe,JPe,ZPe,QPe,ebe,tbe,nbe,rbe,obe,sbe,ibe,abe,cbe,ube,lbe,dbe,pbe,_be,fbe,mbe,Ebe,Sbe,gbe,hbe,Tbe,Abe,Rbe,ybe,Obe,Nbe,Cbe,vbe,Ibe,Pbe,bbe,Mbe,Lbe,xbe,Dbe,Ube,wbe,kbe,Vbe,Bbe,Gbe,Hbe,$be,Fbe,jbe,qbe,Ybe,Kbe,Wbe,zbe,Xbe,Jbe,Zbe,Qbe,eMe,tMe,nMe,rMe,oMe,sMe,iMe,aMe,cMe,uMe,lMe,pO,dMe,pMe,_Me,fMe,mMe,EMe,SMe,gMe,hMe,TMe,t4,n4,r4,o4,AMe,RMe,yMe,OMe,NMe,s4,i4,a4,c4,u4,l4,d4,p4,_4,f4,m4,E4,S4,g4,h4,T4,A4,CMe,vMe,IMe,PMe,bMe,MMe,LMe,xMe,DMe,UMe,wMe,kMe,VMe,BMe,GMe,HMe,$Me,FMe,R4,y4,jMe,qMe,YMe,O4,N4,C4,v4,I4,P4,b4,KMe,WMe,zMe,XMe,JMe,ZMe,QMe,eLe,M4,L4,x4,D4,U4,w4,k4,V4,B4,G4,H4,tLe,nLe,rLe,oLe,sLe,iLe,aLe,cLe,uLe,lLe,dLe,pLe,$4,F4,j4,q4,Y4,K4,W4,z4,X4,J4,_Le,fLe,mLe,ELe,SLe,gLe,hLe,TLe,ALe,RLe,yLe,Z4=$(()=>{oO();IW="cloud.provider",PW="cloud.account.id",bW="cloud.region",MW="cloud.availability_zone",LW="cloud.platform",xW="aws.ecs.container.arn",DW="aws.ecs.cluster.arn",UW="aws.ecs.launchtype",wW="aws.ecs.task.arn",kW="aws.ecs.task.family",VW="aws.ecs.task.revision",BW="aws.eks.cluster.arn",GW="aws.log.group.names",HW="aws.log.group.arns",$W="aws.log.stream.names",FW="aws.log.stream.arns",jW="container.name",qW="container.id",YW="container.runtime",KW="container.image.name",WW="container.image.tag",zW="deployment.environment",XW="device.id",JW="device.model.identifier",ZW="device.model.name",QW="faas.name",e2="faas.id",t2="faas.version",n2="faas.instance",r2="faas.max_memory",o2="host.id",s2="host.name",i2="host.type",a2="host.arch",c2="host.image.name",u2="host.image.id",l2="host.image.version",d2="k8s.cluster.name",p2="k8s.node.name",_2="k8s.node.uid",f2="k8s.namespace.name",m2="k8s.pod.uid",E2="k8s.pod.name",S2="k8s.container.name",g2="k8s.replicaset.uid",h2="k8s.replicaset.name",T2="k8s.deployment.uid",A2="k8s.deployment.name",R2="k8s.statefulset.uid",y2="k8s.statefulset.name",O2="k8s.daemonset.uid",N2="k8s.daemonset.name",C2="k8s.job.uid",v2="k8s.job.name",I2="k8s.cronjob.uid",P2="k8s.cronjob.name",b2="os.type",M2="os.description",L2="os.name",x2="os.version",D2="process.pid",U2="process.executable.name",w2="process.executable.path",k2="process.command",V2="process.command_line",B2="process.command_args",G2="process.owner",H2="process.runtime.name",$2="process.runtime.version",F2="process.runtime.description",j2="service.name",q2="service.namespace",Y2="service.instance.id",K2="service.version",W2="telemetry.sdk.name",z2="telemetry.sdk.language",X2="telemetry.sdk.version",J2="telemetry.auto.version",Z2="webengine.name",Q2="webengine.version",e4="webengine.description",WPe=IW,zPe=PW,XPe=bW,JPe=MW,ZPe=LW,QPe=xW,ebe=DW,tbe=UW,nbe=wW,rbe=kW,obe=VW,sbe=BW,ibe=GW,abe=HW,cbe=$W,ube=FW,lbe=jW,dbe=qW,pbe=YW,_be=KW,fbe=WW,mbe=zW,Ebe=XW,Sbe=JW,gbe=ZW,hbe=QW,Tbe=e2,Abe=t2,Rbe=n2,ybe=r2,Obe=o2,Nbe=s2,Cbe=i2,vbe=a2,Ibe=c2,Pbe=u2,bbe=l2,Mbe=d2,Lbe=p2,xbe=_2,Dbe=f2,Ube=m2,wbe=E2,kbe=S2,Vbe=g2,Bbe=h2,Gbe=T2,Hbe=A2,$be=R2,Fbe=y2,jbe=O2,qbe=N2,Ybe=C2,Kbe=v2,Wbe=I2,zbe=P2,Xbe=b2,Jbe=M2,Zbe=L2,Qbe=x2,eMe=D2,tMe=U2,nMe=w2,rMe=k2,oMe=V2,sMe=B2,iMe=G2,aMe=H2,cMe=$2,uMe=F2,lMe=j2,pO=q2,dMe=Y2,pMe=K2,_Me=W2,fMe=z2,mMe=X2,EMe=J2,SMe=Z2,gMe=Q2,hMe=e4,TMe=rt([IW,PW,bW,MW,LW,xW,DW,UW,wW,kW,VW,BW,GW,HW,$W,FW,jW,qW,YW,KW,WW,zW,XW,JW,ZW,QW,e2,t2,n2,r2,o2,s2,i2,a2,c2,u2,l2,d2,p2,_2,f2,m2,E2,S2,g2,h2,T2,A2,R2,y2,O2,N2,C2,v2,I2,P2,b2,M2,L2,x2,D2,U2,w2,k2,V2,B2,G2,H2,$2,F2,j2,q2,Y2,K2,W2,z2,X2,J2,Z2,Q2,e4]),t4="alibaba_cloud",n4="aws",r4="azure",o4="gcp",AMe=t4,RMe=n4,yMe=r4,OMe=o4,NMe=rt([t4,n4,r4,o4]),s4="alibaba_cloud_ecs",i4="alibaba_cloud_fc",a4="aws_ec2",c4="aws_ecs",u4="aws_eks",l4="aws_lambda",d4="aws_elastic_beanstalk",p4="azure_vm",_4="azure_container_instances",f4="azure_aks",m4="azure_functions",E4="azure_app_service",S4="gcp_compute_engine",g4="gcp_cloud_run",h4="gcp_kubernetes_engine",T4="gcp_cloud_functions",A4="gcp_app_engine",CMe=s4,vMe=i4,IMe=a4,PMe=c4,bMe=u4,MMe=l4,LMe=d4,xMe=p4,DMe=_4,UMe=f4,wMe=m4,kMe=E4,VMe=S4,BMe=g4,GMe=h4,HMe=T4,$Me=A4,FMe=rt([s4,i4,a4,c4,u4,l4,d4,p4,_4,f4,m4,E4,S4,g4,h4,T4,A4]),R4="ec2",y4="fargate",jMe=R4,qMe=y4,YMe=rt([R4,y4]),O4="amd64",N4="arm32",C4="arm64",v4="ia64",I4="ppc32",P4="ppc64",b4="x86",KMe=O4,WMe=N4,zMe=C4,XMe=v4,JMe=I4,ZMe=P4,QMe=b4,eLe=rt([O4,N4,C4,v4,I4,P4,b4]),M4="windows",L4="linux",x4="darwin",D4="freebsd",U4="netbsd",w4="openbsd",k4="dragonflybsd",V4="hpux",B4="aix",G4="solaris",H4="z_os",tLe=M4,nLe=L4,rLe=x4,oLe=D4,sLe=U4,iLe=w4,aLe=k4,cLe=V4,uLe=B4,lLe=G4,dLe=H4,pLe=rt([M4,L4,x4,D4,U4,w4,k4,V4,B4,G4,H4]),$4="cpp",F4="dotnet",j4="erlang",q4="go",Y4="java",K4="nodejs",W4="php",z4="python",X4="ruby",J4="webjs",_Le=$4,fLe=F4,mLe=j4,ELe=q4,SLe=Y4,gLe=K4,hLe=W4,TLe=z4,ALe=X4,RLe=J4,yLe=rt([$4,F4,j4,q4,Y4,K4,W4,z4,X4,J4])});var Q4=$(()=>{Z4()});var OLe,NLe,CLe,vLe,ILe,PLe,bLe,MLe,LLe,xLe,DLe,ULe,wLe,kLe,VLe,BLe,GLe,HLe,$Le,FLe,jLe,qLe,YLe,KLe,WLe,zLe,_O,XLe,fO,JLe,mO,EO,ZLe,SO,QLe,exe,txe,nxe,rxe,oxe,sxe,ixe,yZe,OZe,gO,axe,cxe,uxe,lxe,dxe,pxe,ma,_xe,fxe,mxe,NZe,Exe,Sxe,gxe,hxe,CZe,Txe,Axe,Rxe,yxe,Ks,io,Oxe,Nxe,Cxe,vxe,Ixe,Pxe,bxe,Mxe,Lxe,vZe,xxe,Dxe,Uxe,wxe,kxe,Vxe,Bxe,Gxe,Hxe,$xe,Fxe,jxe,qxe,IZe,PZe,Yxe,Kxe,Wxe,zxe,Xxe,Jxe,Zxe,Qxe,bZe,e0e,hO,TO,t0e,wn,n0e,AO,r0e,o0e,s0e,i0e,a0e,c0e,u0e,l0e,d0e,MZe,p0e,_0e,LZe,f0e,m0e,xZe,E0e,S0e,g0e,h0e,T0e,A0e,R0e,y0e,Wc,O0e,N0e,C0e,v0e,e5=$(()=>{OLe="aspnetcore.diagnostics.exception.result",NLe="aborted",CLe="handled",vLe="skipped",ILe="unhandled",PLe="aspnetcore.diagnostics.handler.type",bLe="aspnetcore.rate_limiting.policy",MLe="aspnetcore.rate_limiting.result",LLe="acquired",xLe="endpoint_limiter",DLe="global_limiter",ULe="request_canceled",wLe="aspnetcore.request.is_unhandled",kLe="aspnetcore.routing.is_fallback",VLe="aspnetcore.routing.match_status",BLe="failure",GLe="success",HLe="aspnetcore.user.is_authenticated",$Le="client.address",FLe="client.port",jLe="code.column.number",qLe="code.file.path",YLe="code.function.name",KLe="code.line.number",WLe="code.stacktrace",zLe="db.collection.name",_O="db.namespace",XLe="db.operation.batch.size",fO="db.operation.name",JLe="db.query.summary",mO="db.query.text",EO="db.response.status_code",ZLe="db.stored_procedure.name",SO="db.system.name",QLe="mariadb",exe="microsoft.sql_server",txe="mysql",nxe="postgresql",rxe="dotnet.gc.heap.generation",oxe="gen0",sxe="gen1",ixe="gen2",yZe="loh",OZe="poh",gO="error.type",axe="_OTHER",cxe="exception.escaped",uxe="exception.message",lxe="exception.stacktrace",dxe="exception.type",pxe=t=>`http.request.header.${t}`,ma="http.request.method",_xe="_OTHER",fxe="CONNECT",mxe="DELETE",NZe="GET",Exe="HEAD",Sxe="OPTIONS",gxe="PATCH",hxe="POST",CZe="PUT",Txe="TRACE",Axe="http.request.method_original",Rxe="http.request.resend_count",yxe=t=>`http.response.header.${t}`,Ks="http.response.status_code",io="http.route",Oxe="jvm.gc.action",Nxe="jvm.gc.name",Cxe="jvm.memory.pool.name",vxe="jvm.memory.type",Ixe="heap",Pxe="non_heap",bxe="jvm.thread.daemon",Mxe="jvm.thread.state",Lxe="blocked",vZe="new",xxe="runnable",Dxe="terminated",Uxe="timed_waiting",wxe="waiting",kxe="network.local.address",Vxe="network.local.port",Bxe="network.peer.address",Gxe="network.peer.port",Hxe="network.protocol.name",$xe="network.protocol.version",Fxe="network.transport",jxe="pipe",qxe="quic",IZe="tcp",PZe="udp",Yxe="unix",Kxe="network.type",Wxe="ipv4",zxe="ipv6",Xxe="otel.scope.name",Jxe="otel.scope.version",Zxe="otel.status_code",Qxe="ERROR",bZe="OK",e0e="otel.status_description",hO="server.address",TO="server.port",t0e="service.instance.id",wn="service.name",n0e="service.namespace",AO="service.version",r0e="signalr.connection.status",o0e="app_shutdown",s0e="normal_closure",i0e="timeout",a0e="signalr.transport",c0e="long_polling",u0e="server_sent_events",l0e="web_sockets",d0e="telemetry.sdk.language",MZe="cpp",p0e="dotnet",_0e="erlang",LZe="go",f0e="java",m0e="nodejs",xZe="php",E0e="python",S0e="ruby",g0e="rust",h0e="swift",T0e="webjs",A0e="telemetry.sdk.name",R0e="telemetry.sdk.version",y0e="url.fragment",Wc="url.full",O0e="url.path",N0e="url.query",C0e="url.scheme",v0e="user_agent.original"});var I0e,P0e,b0e,M0e,L0e,x0e,D0e,U0e,w0e,k0e,V0e,B0e,G0e,H0e,$0e,F0e,j0e,q0e,Y0e,K0e,W0e,z0e,X0e,J0e,Z0e,Q0e,eDe,tDe,nDe,rDe,oDe,sDe,iDe,aDe,cDe,uDe,lDe,dDe,pDe,_De,fDe,mDe,EDe,SDe,gDe,hDe,TDe,ADe,RDe,yDe,ODe,t5=$(()=>{I0e="aspnetcore.diagnostics.exceptions",P0e="aspnetcore.rate_limiting.active_request_leases",b0e="aspnetcore.rate_limiting.queued_requests",M0e="aspnetcore.rate_limiting.request.time_in_queue",L0e="aspnetcore.rate_limiting.request_lease.duration",x0e="aspnetcore.rate_limiting.requests",D0e="aspnetcore.routing.match_attempts",U0e="db.client.operation.duration",w0e="dotnet.assembly.count",k0e="dotnet.exceptions",V0e="dotnet.gc.collections",B0e="dotnet.gc.heap.total_allocated",G0e="dotnet.gc.last_collection.heap.fragmentation.size",H0e="dotnet.gc.last_collection.heap.size",$0e="dotnet.gc.last_collection.memory.committed_size",F0e="dotnet.gc.pause.time",j0e="dotnet.jit.compilation.time",q0e="dotnet.jit.compiled_il.size",Y0e="dotnet.jit.compiled_methods",K0e="dotnet.monitor.lock_contentions",W0e="dotnet.process.cpu.count",z0e="dotnet.process.cpu.time",X0e="dotnet.process.memory.working_set",J0e="dotnet.thread_pool.queue.length",Z0e="dotnet.thread_pool.thread.count",Q0e="dotnet.thread_pool.work_item.count",eDe="dotnet.timer.count",tDe="http.client.request.duration",nDe="http.server.request.duration",rDe="jvm.class.count",oDe="jvm.class.loaded",sDe="jvm.class.unloaded",iDe="jvm.cpu.count",aDe="jvm.cpu.recent_utilization",cDe="jvm.cpu.time",uDe="jvm.gc.duration",lDe="jvm.memory.committed",dDe="jvm.memory.limit",pDe="jvm.memory.used",_De="jvm.memory.used_after_last_gc",fDe="jvm.thread.count",mDe="kestrel.active_connections",EDe="kestrel.active_tls_handshakes",SDe="kestrel.connection.duration",gDe="kestrel.queued_connections",hDe="kestrel.queued_requests",TDe="kestrel.rejected_connections",ADe="kestrel.tls_handshake.duration",RDe="kestrel.upgraded_connections",yDe="signalr.server.active_connections",ODe="signalr.server.connection.duration"});var NDe,n5=$(()=>{NDe="exception"});var ot={};Lp(ot,{ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>NLe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>CLe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>vLe,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>ILe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>LLe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>xLe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>DLe,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ULe,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>BLe,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>GLe,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>OLe,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>PLe,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>bLe,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>MLe,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>wLe,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>kLe,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>VLe,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED:()=>HLe,ATTR_CLIENT_ADDRESS:()=>$Le,ATTR_CLIENT_PORT:()=>FLe,ATTR_CODE_COLUMN_NUMBER:()=>jLe,ATTR_CODE_FILE_PATH:()=>qLe,ATTR_CODE_FUNCTION_NAME:()=>YLe,ATTR_CODE_LINE_NUMBER:()=>KLe,ATTR_CODE_STACKTRACE:()=>WLe,ATTR_DB_COLLECTION_NAME:()=>zLe,ATTR_DB_NAMESPACE:()=>_O,ATTR_DB_OPERATION_BATCH_SIZE:()=>XLe,ATTR_DB_OPERATION_NAME:()=>fO,ATTR_DB_QUERY_SUMMARY:()=>JLe,ATTR_DB_QUERY_TEXT:()=>mO,ATTR_DB_RESPONSE_STATUS_CODE:()=>EO,ATTR_DB_STORED_PROCEDURE_NAME:()=>ZLe,ATTR_DB_SYSTEM_NAME:()=>SO,ATTR_DOTNET_GC_HEAP_GENERATION:()=>rxe,ATTR_ERROR_TYPE:()=>gO,ATTR_EXCEPTION_ESCAPED:()=>cxe,ATTR_EXCEPTION_MESSAGE:()=>uxe,ATTR_EXCEPTION_STACKTRACE:()=>lxe,ATTR_EXCEPTION_TYPE:()=>dxe,ATTR_HTTP_REQUEST_HEADER:()=>pxe,ATTR_HTTP_REQUEST_METHOD:()=>ma,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>Axe,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>Rxe,ATTR_HTTP_RESPONSE_HEADER:()=>yxe,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>Ks,ATTR_HTTP_ROUTE:()=>io,ATTR_JVM_GC_ACTION:()=>Oxe,ATTR_JVM_GC_NAME:()=>Nxe,ATTR_JVM_MEMORY_POOL_NAME:()=>Cxe,ATTR_JVM_MEMORY_TYPE:()=>vxe,ATTR_JVM_THREAD_DAEMON:()=>bxe,ATTR_JVM_THREAD_STATE:()=>Mxe,ATTR_NETWORK_LOCAL_ADDRESS:()=>kxe,ATTR_NETWORK_LOCAL_PORT:()=>Vxe,ATTR_NETWORK_PEER_ADDRESS:()=>Bxe,ATTR_NETWORK_PEER_PORT:()=>Gxe,ATTR_NETWORK_PROTOCOL_NAME:()=>Hxe,ATTR_NETWORK_PROTOCOL_VERSION:()=>$xe,ATTR_NETWORK_TRANSPORT:()=>Fxe,ATTR_NETWORK_TYPE:()=>Kxe,ATTR_OTEL_SCOPE_NAME:()=>Xxe,ATTR_OTEL_SCOPE_VERSION:()=>Jxe,ATTR_OTEL_STATUS_CODE:()=>Zxe,ATTR_OTEL_STATUS_DESCRIPTION:()=>e0e,ATTR_SERVER_ADDRESS:()=>hO,ATTR_SERVER_PORT:()=>TO,ATTR_SERVICE_INSTANCE_ID:()=>t0e,ATTR_SERVICE_NAME:()=>wn,ATTR_SERVICE_NAMESPACE:()=>n0e,ATTR_SERVICE_VERSION:()=>AO,ATTR_SIGNALR_CONNECTION_STATUS:()=>r0e,ATTR_SIGNALR_TRANSPORT:()=>a0e,ATTR_TELEMETRY_SDK_LANGUAGE:()=>d0e,ATTR_TELEMETRY_SDK_NAME:()=>A0e,ATTR_TELEMETRY_SDK_VERSION:()=>R0e,ATTR_URL_FRAGMENT:()=>y0e,ATTR_URL_FULL:()=>Wc,ATTR_URL_PATH:()=>O0e,ATTR_URL_QUERY:()=>N0e,ATTR_URL_SCHEME:()=>C0e,ATTR_USER_AGENT_ORIGINAL:()=>v0e,AWSECSLAUNCHTYPEVALUES_EC2:()=>jMe,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>qMe,AwsEcsLaunchtypeValues:()=>YMe,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>CMe,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>vMe,CLOUDPLATFORMVALUES_AWS_EC2:()=>IMe,CLOUDPLATFORMVALUES_AWS_ECS:()=>PMe,CLOUDPLATFORMVALUES_AWS_EKS:()=>bMe,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>LMe,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>MMe,CLOUDPLATFORMVALUES_AZURE_AKS:()=>UMe,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>kMe,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>DMe,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>wMe,CLOUDPLATFORMVALUES_AZURE_VM:()=>xMe,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>$Me,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>HMe,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>BMe,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>VMe,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>GMe,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>AMe,CLOUDPROVIDERVALUES_AWS:()=>RMe,CLOUDPROVIDERVALUES_AZURE:()=>yMe,CLOUDPROVIDERVALUES_GCP:()=>OMe,CloudPlatformValues:()=>FMe,CloudProviderValues:()=>NMe,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>iIe,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>fIe,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>aIe,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>_Ie,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>uIe,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>EIe,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>lIe,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>cIe,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>mIe,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>pIe,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>dIe,DBSYSTEMVALUES_ADABAS:()=>Pve,DBSYSTEMVALUES_CACHE:()=>Ive,DBSYSTEMVALUES_CASSANDRA:()=>Yve,DBSYSTEMVALUES_CLOUDSCAPE:()=>Tve,DBSYSTEMVALUES_COCKROACHDB:()=>oIe,DBSYSTEMVALUES_COLDFUSION:()=>qve,DBSYSTEMVALUES_COSMOSDB:()=>Zve,DBSYSTEMVALUES_COUCHBASE:()=>Xve,DBSYSTEMVALUES_COUCHDB:()=>Jve,DBSYSTEMVALUES_DB2:()=>Eve,DBSYSTEMVALUES_DERBY:()=>Mve,DBSYSTEMVALUES_DYNAMODB:()=>Qve,DBSYSTEMVALUES_EDB:()=>vve,DBSYSTEMVALUES_ELASTICSEARCH:()=>nIe,DBSYSTEMVALUES_FILEMAKER:()=>Lve,DBSYSTEMVALUES_FIREBIRD:()=>bve,DBSYSTEMVALUES_FIRSTSQL:()=>Cve,DBSYSTEMVALUES_GEODE:()=>tIe,DBSYSTEMVALUES_H2:()=>jve,DBSYSTEMVALUES_HANADB:()=>Ove,DBSYSTEMVALUES_HBASE:()=>Kve,DBSYSTEMVALUES_HIVE:()=>hve,DBSYSTEMVALUES_HSQLDB:()=>Ave,DBSYSTEMVALUES_INFORMIX:()=>xve,DBSYSTEMVALUES_INGRES:()=>Nve,DBSYSTEMVALUES_INSTANTDB:()=>Dve,DBSYSTEMVALUES_INTERBASE:()=>Uve,DBSYSTEMVALUES_MARIADB:()=>wve,DBSYSTEMVALUES_MAXDB:()=>yve,DBSYSTEMVALUES_MEMCACHED:()=>rIe,DBSYSTEMVALUES_MONGODB:()=>Wve,DBSYSTEMVALUES_MSSQL:()=>_ve,DBSYSTEMVALUES_MYSQL:()=>fve,DBSYSTEMVALUES_NEO4J:()=>eIe,DBSYSTEMVALUES_NETEZZA:()=>kve,DBSYSTEMVALUES_ORACLE:()=>mve,DBSYSTEMVALUES_OTHER_SQL:()=>pve,DBSYSTEMVALUES_PERVASIVE:()=>Vve,DBSYSTEMVALUES_POINTBASE:()=>Bve,DBSYSTEMVALUES_POSTGRESQL:()=>Sve,DBSYSTEMVALUES_PROGRESS:()=>Rve,DBSYSTEMVALUES_REDIS:()=>zve,DBSYSTEMVALUES_REDSHIFT:()=>gve,DBSYSTEMVALUES_SQLITE:()=>Gve,DBSYSTEMVALUES_SYBASE:()=>Hve,DBSYSTEMVALUES_TERADATA:()=>$ve,DBSYSTEMVALUES_VERTICA:()=>Fve,DB_SYSTEM_NAME_VALUE_MARIADB:()=>QLe,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER:()=>exe,DB_SYSTEM_NAME_VALUE_MYSQL:()=>txe,DB_SYSTEM_NAME_VALUE_POSTGRESQL:()=>nxe,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0:()=>oxe,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1:()=>sxe,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2:()=>ixe,DOTNET_GC_HEAP_GENERATION_VALUE_LOH:()=>yZe,DOTNET_GC_HEAP_GENERATION_VALUE_POH:()=>OZe,DbCassandraConsistencyLevelValues:()=>SIe,DbSystemValues:()=>sIe,ERROR_TYPE_VALUE_OTHER:()=>axe,EVENT_EXCEPTION:()=>NDe,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>CIe,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>NIe,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>OIe,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>IIe,FAASINVOKEDPROVIDERVALUES_AWS:()=>PIe,FAASINVOKEDPROVIDERVALUES_AZURE:()=>bIe,FAASINVOKEDPROVIDERVALUES_GCP:()=>MIe,FAASTRIGGERVALUES_DATASOURCE:()=>gIe,FAASTRIGGERVALUES_HTTP:()=>hIe,FAASTRIGGERVALUES_OTHER:()=>RIe,FAASTRIGGERVALUES_PUBSUB:()=>TIe,FAASTRIGGERVALUES_TIMER:()=>AIe,FaasDocumentOperationValues:()=>vIe,FaasInvokedProviderValues:()=>LIe,FaasTriggerValues:()=>yIe,HOSTARCHVALUES_AMD64:()=>KMe,HOSTARCHVALUES_ARM32:()=>WMe,HOSTARCHVALUES_ARM64:()=>zMe,HOSTARCHVALUES_IA64:()=>XMe,HOSTARCHVALUES_PPC32:()=>JMe,HOSTARCHVALUES_PPC64:()=>ZMe,HOSTARCHVALUES_X86:()=>QMe,HTTPFLAVORVALUES_HTTP_1_0:()=>mPe,HTTPFLAVORVALUES_HTTP_1_1:()=>EPe,HTTPFLAVORVALUES_HTTP_2_0:()=>SPe,HTTPFLAVORVALUES_QUIC:()=>hPe,HTTPFLAVORVALUES_SPDY:()=>gPe,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>fxe,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>mxe,HTTP_REQUEST_METHOD_VALUE_GET:()=>NZe,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>Exe,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>Sxe,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>_xe,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>gxe,HTTP_REQUEST_METHOD_VALUE_POST:()=>hxe,HTTP_REQUEST_METHOD_VALUE_PUT:()=>CZe,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>Txe,HostArchValues:()=>eLe,HttpFlavorValues:()=>TPe,JVM_MEMORY_TYPE_VALUE_HEAP:()=>Ixe,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>Pxe,JVM_THREAD_STATE_VALUE_BLOCKED:()=>Lxe,JVM_THREAD_STATE_VALUE_NEW:()=>vZe,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>xxe,JVM_THREAD_STATE_VALUE_TERMINATED:()=>Dxe,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>Uxe,JVM_THREAD_STATE_VALUE_WAITING:()=>wxe,MESSAGETYPEVALUES_RECEIVED:()=>YPe,MESSAGETYPEVALUES_SENT:()=>qPe,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>APe,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>RPe,MESSAGINGOPERATIONVALUES_PROCESS:()=>NPe,MESSAGINGOPERATIONVALUES_RECEIVE:()=>OPe,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>I0e,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>P0e,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>b0e,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>x0e,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>L0e,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>M0e,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>D0e,METRIC_DB_CLIENT_OPERATION_DURATION:()=>U0e,METRIC_DOTNET_ASSEMBLY_COUNT:()=>w0e,METRIC_DOTNET_EXCEPTIONS:()=>k0e,METRIC_DOTNET_GC_COLLECTIONS:()=>V0e,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED:()=>B0e,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE:()=>G0e,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE:()=>H0e,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE:()=>$0e,METRIC_DOTNET_GC_PAUSE_TIME:()=>F0e,METRIC_DOTNET_JIT_COMPILATION_TIME:()=>j0e,METRIC_DOTNET_JIT_COMPILED_IL_SIZE:()=>q0e,METRIC_DOTNET_JIT_COMPILED_METHODS:()=>Y0e,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS:()=>K0e,METRIC_DOTNET_PROCESS_CPU_COUNT:()=>W0e,METRIC_DOTNET_PROCESS_CPU_TIME:()=>z0e,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET:()=>X0e,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH:()=>J0e,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT:()=>Z0e,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT:()=>Q0e,METRIC_DOTNET_TIMER_COUNT:()=>eDe,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>tDe,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>nDe,METRIC_JVM_CLASS_COUNT:()=>rDe,METRIC_JVM_CLASS_LOADED:()=>oDe,METRIC_JVM_CLASS_UNLOADED:()=>sDe,METRIC_JVM_CPU_COUNT:()=>iDe,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>aDe,METRIC_JVM_CPU_TIME:()=>cDe,METRIC_JVM_GC_DURATION:()=>uDe,METRIC_JVM_MEMORY_COMMITTED:()=>lDe,METRIC_JVM_MEMORY_LIMIT:()=>dDe,METRIC_JVM_MEMORY_USED:()=>pDe,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>_De,METRIC_JVM_THREAD_COUNT:()=>fDe,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>mDe,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>EDe,METRIC_KESTREL_CONNECTION_DURATION:()=>SDe,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>gDe,METRIC_KESTREL_QUEUED_REQUESTS:()=>hDe,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>TDe,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>ADe,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>RDe,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>yDe,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>ODe,MessageTypeValues:()=>KPe,MessagingDestinationKindValues:()=>yPe,MessagingOperationValues:()=>CPe,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>XIe,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>QIe,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>WIe,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>iPe,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>JIe,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>ZIe,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>oPe,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>KIe,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>cPe,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>ePe,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>nPe,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>aPe,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>tPe,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>rPe,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>lPe,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>sPe,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>_Pe,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>dPe,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>pPe,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>uPe,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>zIe,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>FIe,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>jIe,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>qIe,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>HIe,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>$Ie,NETTRANSPORTVALUES_INPROC:()=>VIe,NETTRANSPORTVALUES_IP:()=>UIe,NETTRANSPORTVALUES_IP_TCP:()=>xIe,NETTRANSPORTVALUES_IP_UDP:()=>DIe,NETTRANSPORTVALUES_OTHER:()=>BIe,NETTRANSPORTVALUES_PIPE:()=>kIe,NETTRANSPORTVALUES_UNIX:()=>wIe,NETWORK_TRANSPORT_VALUE_PIPE:()=>jxe,NETWORK_TRANSPORT_VALUE_QUIC:()=>qxe,NETWORK_TRANSPORT_VALUE_TCP:()=>IZe,NETWORK_TRANSPORT_VALUE_UDP:()=>PZe,NETWORK_TRANSPORT_VALUE_UNIX:()=>Yxe,NETWORK_TYPE_VALUE_IPV4:()=>Wxe,NETWORK_TYPE_VALUE_IPV6:()=>zxe,NetHostConnectionSubtypeValues:()=>fPe,NetHostConnectionTypeValues:()=>YIe,NetTransportValues:()=>GIe,OSTYPEVALUES_AIX:()=>uLe,OSTYPEVALUES_DARWIN:()=>rLe,OSTYPEVALUES_DRAGONFLYBSD:()=>aLe,OSTYPEVALUES_FREEBSD:()=>oLe,OSTYPEVALUES_HPUX:()=>cLe,OSTYPEVALUES_LINUX:()=>nLe,OSTYPEVALUES_NETBSD:()=>sLe,OSTYPEVALUES_OPENBSD:()=>iLe,OSTYPEVALUES_SOLARIS:()=>lLe,OSTYPEVALUES_WINDOWS:()=>tLe,OSTYPEVALUES_Z_OS:()=>dLe,OTEL_STATUS_CODE_VALUE_ERROR:()=>Qxe,OTEL_STATUS_CODE_VALUE_OK:()=>bZe,OsTypeValues:()=>pLe,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>kPe,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>xPe,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>IPe,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>$Pe,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>MPe,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>wPe,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>GPe,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>bPe,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>LPe,RPCGRPCSTATUSCODEVALUES_OK:()=>vPe,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>VPe,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>DPe,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>UPe,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>FPe,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>HPe,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>BPe,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>PPe,RpcGrpcStatusCodeValues:()=>jPe,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>yCe,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>UCe,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>TCe,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>ECe,SEMATTRS_AWS_DYNAMODB_COUNT:()=>xCe,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>ICe,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>CCe,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>wCe,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>OCe,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>SCe,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>RCe,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>vCe,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>ACe,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>gCe,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>hCe,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>DCe,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>bCe,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>MCe,SEMATTRS_AWS_DYNAMODB_SELECT:()=>NCe,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>PCe,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>mCe,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>LCe,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>nNe,SEMATTRS_CODE_FILEPATH:()=>rCe,SEMATTRS_CODE_FUNCTION:()=>tCe,SEMATTRS_CODE_LINENO:()=>oCe,SEMATTRS_CODE_NAMESPACE:()=>nCe,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>dNe,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>ENe,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>mNe,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>_Ne,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>uNe,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>lNe,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>fNe,SEMATTRS_DB_CASSANDRA_TABLE:()=>pNe,SEMATTRS_DB_CONNECTION_STRING:()=>rNe,SEMATTRS_DB_HBASE_NAMESPACE:()=>SNe,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>sNe,SEMATTRS_DB_MONGODB_COLLECTION:()=>hNe,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>cNe,SEMATTRS_DB_NAME:()=>iNe,SEMATTRS_DB_OPERATION:()=>aNe,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>gNe,SEMATTRS_DB_SQL_TABLE:()=>TNe,SEMATTRS_DB_STATEMENT:()=>iO,SEMATTRS_DB_SYSTEM:()=>sO,SEMATTRS_DB_USER:()=>oNe,SEMATTRS_ENDUSER_ID:()=>XNe,SEMATTRS_ENDUSER_ROLE:()=>JNe,SEMATTRS_ENDUSER_SCOPE:()=>ZNe,SEMATTRS_EXCEPTION_ESCAPED:()=>ONe,SEMATTRS_EXCEPTION_MESSAGE:()=>RNe,SEMATTRS_EXCEPTION_STACKTRACE:()=>yNe,SEMATTRS_EXCEPTION_TYPE:()=>ANe,SEMATTRS_FAAS_COLDSTART:()=>LNe,SEMATTRS_FAAS_CRON:()=>MNe,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>CNe,SEMATTRS_FAAS_DOCUMENT_NAME:()=>PNe,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>vNe,SEMATTRS_FAAS_DOCUMENT_TIME:()=>INe,SEMATTRS_FAAS_EXECUTION:()=>NNe,SEMATTRS_FAAS_INVOKED_NAME:()=>xNe,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>DNe,SEMATTRS_FAAS_INVOKED_REGION:()=>UNe,SEMATTRS_FAAS_TIME:()=>bNe,SEMATTRS_FAAS_TRIGGER:()=>aO,SEMATTRS_HTTP_CLIENT_IP:()=>fCe,SEMATTRS_HTTP_FLAVOR:()=>aCe,SEMATTRS_HTTP_HOST:()=>sCe,SEMATTRS_HTTP_METHOD:()=>Cd,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>uCe,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>lCe,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>dCe,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>pCe,SEMATTRS_HTTP_ROUTE:()=>vd,SEMATTRS_HTTP_SCHEME:()=>iCe,SEMATTRS_HTTP_SERVER_NAME:()=>_Ce,SEMATTRS_HTTP_STATUS_CODE:()=>TE,SEMATTRS_HTTP_TARGET:()=>cO,SEMATTRS_HTTP_URL:()=>Kc,SEMATTRS_HTTP_USER_AGENT:()=>cCe,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>uve,SEMATTRS_MESSAGE_ID:()=>cve,SEMATTRS_MESSAGE_TYPE:()=>ave,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>lve,SEMATTRS_MESSAGING_CONSUMER_ID:()=>WCe,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>jCe,SEMATTRS_MESSAGING_DESTINATION:()=>kCe,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>VCe,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>ZCe,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>JCe,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>XCe,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>QCe,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>eve,SEMATTRS_MESSAGING_MESSAGE_ID:()=>FCe,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>YCe,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>qCe,SEMATTRS_MESSAGING_OPERATION:()=>KCe,SEMATTRS_MESSAGING_PROTOCOL:()=>GCe,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>HCe,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>zCe,SEMATTRS_MESSAGING_SYSTEM:()=>uO,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>BCe,SEMATTRS_MESSAGING_URL:()=>$Ce,SEMATTRS_NET_HOST_CARRIER_ICC:()=>WNe,SEMATTRS_NET_HOST_CARRIER_MCC:()=>YNe,SEMATTRS_NET_HOST_CARRIER_MNC:()=>KNe,SEMATTRS_NET_HOST_CARRIER_NAME:()=>qNe,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>jNe,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>FNe,SEMATTRS_NET_HOST_IP:()=>GNe,SEMATTRS_NET_HOST_NAME:()=>$Ne,SEMATTRS_NET_HOST_PORT:()=>HNe,SEMATTRS_NET_PEER_IP:()=>kNe,SEMATTRS_NET_PEER_NAME:()=>BNe,SEMATTRS_NET_PEER_PORT:()=>VNe,SEMATTRS_NET_TRANSPORT:()=>wNe,SEMATTRS_PEER_SERVICE:()=>zNe,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>dO,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>sve,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>ive,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>ove,SEMATTRS_RPC_JSONRPC_VERSION:()=>rve,SEMATTRS_RPC_METHOD:()=>nve,SEMATTRS_RPC_SERVICE:()=>lO,SEMATTRS_RPC_SYSTEM:()=>tve,SEMATTRS_THREAD_ID:()=>QNe,SEMATTRS_THREAD_NAME:()=>eCe,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>ebe,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>QPe,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>tbe,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>nbe,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>rbe,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>obe,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>sbe,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>abe,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>ibe,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>ube,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>cbe,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>zPe,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>JPe,SEMRESATTRS_CLOUD_PLATFORM:()=>ZPe,SEMRESATTRS_CLOUD_PROVIDER:()=>WPe,SEMRESATTRS_CLOUD_REGION:()=>XPe,SEMRESATTRS_CONTAINER_ID:()=>dbe,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>_be,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>fbe,SEMRESATTRS_CONTAINER_NAME:()=>lbe,SEMRESATTRS_CONTAINER_RUNTIME:()=>pbe,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>mbe,SEMRESATTRS_DEVICE_ID:()=>Ebe,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>Sbe,SEMRESATTRS_DEVICE_MODEL_NAME:()=>gbe,SEMRESATTRS_FAAS_ID:()=>Tbe,SEMRESATTRS_FAAS_INSTANCE:()=>Rbe,SEMRESATTRS_FAAS_MAX_MEMORY:()=>ybe,SEMRESATTRS_FAAS_NAME:()=>hbe,SEMRESATTRS_FAAS_VERSION:()=>Abe,SEMRESATTRS_HOST_ARCH:()=>vbe,SEMRESATTRS_HOST_ID:()=>Obe,SEMRESATTRS_HOST_IMAGE_ID:()=>Pbe,SEMRESATTRS_HOST_IMAGE_NAME:()=>Ibe,SEMRESATTRS_HOST_IMAGE_VERSION:()=>bbe,SEMRESATTRS_HOST_NAME:()=>Nbe,SEMRESATTRS_HOST_TYPE:()=>Cbe,SEMRESATTRS_K8S_CLUSTER_NAME:()=>Mbe,SEMRESATTRS_K8S_CONTAINER_NAME:()=>kbe,SEMRESATTRS_K8S_CRONJOB_NAME:()=>zbe,SEMRESATTRS_K8S_CRONJOB_UID:()=>Wbe,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>qbe,SEMRESATTRS_K8S_DAEMONSET_UID:()=>jbe,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>Hbe,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>Gbe,SEMRESATTRS_K8S_JOB_NAME:()=>Kbe,SEMRESATTRS_K8S_JOB_UID:()=>Ybe,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>Dbe,SEMRESATTRS_K8S_NODE_NAME:()=>Lbe,SEMRESATTRS_K8S_NODE_UID:()=>xbe,SEMRESATTRS_K8S_POD_NAME:()=>wbe,SEMRESATTRS_K8S_POD_UID:()=>Ube,SEMRESATTRS_K8S_REPLICASET_NAME:()=>Bbe,SEMRESATTRS_K8S_REPLICASET_UID:()=>Vbe,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>Fbe,SEMRESATTRS_K8S_STATEFULSET_UID:()=>$be,SEMRESATTRS_OS_DESCRIPTION:()=>Jbe,SEMRESATTRS_OS_NAME:()=>Zbe,SEMRESATTRS_OS_TYPE:()=>Xbe,SEMRESATTRS_OS_VERSION:()=>Qbe,SEMRESATTRS_PROCESS_COMMAND:()=>rMe,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>sMe,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>oMe,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>tMe,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>nMe,SEMRESATTRS_PROCESS_OWNER:()=>iMe,SEMRESATTRS_PROCESS_PID:()=>eMe,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>uMe,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>aMe,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>cMe,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>dMe,SEMRESATTRS_SERVICE_NAME:()=>lMe,SEMRESATTRS_SERVICE_NAMESPACE:()=>pO,SEMRESATTRS_SERVICE_VERSION:()=>pMe,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>EMe,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>fMe,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>_Me,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>mMe,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>hMe,SEMRESATTRS_WEBENGINE_NAME:()=>SMe,SEMRESATTRS_WEBENGINE_VERSION:()=>gMe,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>o0e,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>s0e,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>i0e,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>c0e,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>u0e,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>l0e,SemanticAttributes:()=>dve,SemanticResourceAttributes:()=>TMe,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>_Le,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>fLe,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>mLe,TELEMETRYSDKLANGUAGEVALUES_GO:()=>ELe,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>SLe,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>gLe,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>hLe,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>TLe,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>ALe,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>RLe,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>MZe,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>p0e,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>_0e,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>LZe,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>f0e,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>m0e,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>xZe,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>E0e,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>S0e,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>g0e,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>h0e,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>T0e,TelemetrySdkLanguageValues:()=>yLe});var ve=$(()=>{vW();Q4();e5();t5();n5()});var r5=m(AE=>{"use strict";Object.defineProperty(AE,"__esModule",{value:!0});AE.ExceptionEventName=void 0;AE.ExceptionEventName="exception"});var yO=m(RE=>{"use strict";Object.defineProperty(RE,"__esModule",{value:!0});RE.Span=void 0;var rr=(x(),b(B)),zt=Se(),Ea=(zn(),b(Wn)),CDe=r5(),RO=class{constructor(e,n,r,o,s,i,a=[],c,u,l){this.attributes={},this.links=[],this.events=[],this._droppedAttributesCount=0,this._droppedEventsCount=0,this._droppedLinksCount=0,this.status={code:rr.SpanStatusCode.UNSET},this.endTime=[0,0],this._ended=!1,this._duration=[-1,-1],this.name=r,this._spanContext=o,this.parentSpanId=i,this.kind=s,this.links=a;let d=Date.now();this._performanceStartTime=zt.otperformance.now(),this._performanceOffset=d-(this._performanceStartTime+(0,zt.getTimeOrigin)()),this._startTimeProvided=c!=null,this.startTime=this._getTime(c??d),this.resource=e.resource,this.instrumentationLibrary=e.instrumentationLibrary,this._spanLimits=e.getSpanLimits(),this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,l!=null&&this.setAttributes(l),this._spanProcessor=e.getActiveSpanProcessor(),this._spanProcessor.onStart(this,n)}spanContext(){return this._spanContext}setAttribute(e,n){return n==null||this._isSpanEnded()?this:e.length===0?(rr.diag.warn(`Invalid attribute key: ${e}`),this):(0,zt.isAttributeValue)(n)?Object.keys(this.attributes).length>=this._spanLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(n),this):(rr.diag.warn(`Invalid attribute value set for key: ${e}`),this)}setAttributes(e){for(let[n,r]of Object.entries(e))this.setAttribute(n,r);return this}addEvent(e,n,r){if(this._isSpanEnded())return this;if(this._spanLimits.eventCountLimit===0)return rr.diag.warn("No events allowed."),this._droppedEventsCount++,this;this.events.length>=this._spanLimits.eventCountLimit&&(this._droppedEventsCount===0&&rr.diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),(0,zt.isTimeInput)(n)&&((0,zt.isTimeInput)(r)||(r=n),n=void 0);let o=(0,zt.sanitizeAttributes)(n);return this.events.push({name:e,attributes:o,time:this._getTime(r),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()?this:(this.status=Object.assign({},e),this.status.message!=null&&typeof e.message!="string"&&(rr.diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message),this)}updateName(e){return this._isSpanEnded()?this:(this.name=e,this)}end(e){if(this._isSpanEnded()){rr.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this._ended=!0,this.endTime=this._getTime(e),this._duration=(0,zt.hrTimeDuration)(this.startTime,this.endTime),this._duration[0]<0&&(rr.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&rr.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e=="number"&&e<=zt.otperformance.now())return(0,zt.hrTime)(e+this._performanceOffset);if(typeof e=="number")return(0,zt.millisToHrTime)(e);if(e instanceof Date)return(0,zt.millisToHrTime)(e.getTime());if((0,zt.isTimeInputHrTime)(e))return e;if(this._startTimeProvided)return(0,zt.millisToHrTime)(Date.now());let n=zt.otperformance.now()-this._performanceStartTime;return(0,zt.addHrTimes)(this.startTime,(0,zt.millisToHrTime)(n))}isRecording(){return this._ended===!1}recordException(e,n){let r={};typeof e=="string"?r[Ea.SEMATTRS_EXCEPTION_MESSAGE]=e:e&&(e.code?r[Ea.SEMATTRS_EXCEPTION_TYPE]=e.code.toString():e.name&&(r[Ea.SEMATTRS_EXCEPTION_TYPE]=e.name),e.message&&(r[Ea.SEMATTRS_EXCEPTION_MESSAGE]=e.message),e.stack&&(r[Ea.SEMATTRS_EXCEPTION_STACKTRACE]=e.stack)),r[Ea.SEMATTRS_EXCEPTION_TYPE]||r[Ea.SEMATTRS_EXCEPTION_MESSAGE]?this.addEvent(CDe.ExceptionEventName,r,n):rr.diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){return this._ended&&rr.diag.warn(`Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`),this._ended}_truncateToLimitUtil(e,n){return e.length<=n?e:e.substring(0,n)}_truncateToSize(e){let n=this._attributeValueLengthLimit;return n<=0?(rr.diag.warn(`Attribute value limit must be positive, got ${n}`),e):typeof e=="string"?this._truncateToLimitUtil(e,n):Array.isArray(e)?e.map(r=>typeof r=="string"?this._truncateToLimitUtil(r,n):r):e}};RE.Span=RO});var Pd=m(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.SamplingDecision=void 0;var vDe;(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(vDe=Id.SamplingDecision||(Id.SamplingDecision={}))});var OE=m(yE=>{"use strict";Object.defineProperty(yE,"__esModule",{value:!0});yE.AlwaysOffSampler=void 0;var IDe=Pd(),OO=class{shouldSample(){return{decision:IDe.SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}};yE.AlwaysOffSampler=OO});var CE=m(NE=>{"use strict";Object.defineProperty(NE,"__esModule",{value:!0});NE.AlwaysOnSampler=void 0;var PDe=Pd(),NO=class{shouldSample(){return{decision:PDe.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}};NE.AlwaysOnSampler=NO});var IO=m(IE=>{"use strict";Object.defineProperty(IE,"__esModule",{value:!0});IE.ParentBasedSampler=void 0;var vE=(x(),b(B)),bDe=Se(),o5=OE(),CO=CE(),vO=class{constructor(e){var n,r,o,s;this._root=e.root,this._root||((0,bDe.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new CO.AlwaysOnSampler),this._remoteParentSampled=(n=e.remoteParentSampled)!==null&&n!==void 0?n:new CO.AlwaysOnSampler,this._remoteParentNotSampled=(r=e.remoteParentNotSampled)!==null&&r!==void 0?r:new o5.AlwaysOffSampler,this._localParentSampled=(o=e.localParentSampled)!==null&&o!==void 0?o:new CO.AlwaysOnSampler,this._localParentNotSampled=(s=e.localParentNotSampled)!==null&&s!==void 0?s:new o5.AlwaysOffSampler}shouldSample(e,n,r,o,s,i){let a=vE.trace.getSpanContext(e);return!a||!(0,vE.isSpanContextValid)(a)?this._root.shouldSample(e,n,r,o,s,i):a.isRemote?a.traceFlags&vE.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,n,r,o,s,i):this._remoteParentNotSampled.shouldSample(e,n,r,o,s,i):a.traceFlags&vE.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,n,r,o,s,i):this._localParentNotSampled.shouldSample(e,n,r,o,s,i)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}};IE.ParentBasedSampler=vO});var bO=m(PE=>{"use strict";Object.defineProperty(PE,"__esModule",{value:!0});PE.TraceIdRatioBasedSampler=void 0;var MDe=(x(),b(B)),s5=Pd(),PO=class{constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,n){return{decision:(0,MDe.isValidTraceId)(n)&&this._accumulate(n)<this._upperBound?s5.SamplingDecision.RECORD_AND_SAMPLED:s5.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!="number"||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let n=0;for(let r=0;r<e.length/8;r++){let o=r*8,s=parseInt(e.slice(o,o+8),16);n=(n^s)>>>0}return n}};PE.TraceIdRatioBasedSampler=PO});var xO=m(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.buildSamplerFromEnv=Xc.loadDefaultConfig=void 0;var bE=(x(),b(B)),Go=Se(),i5=OE(),MO=CE(),LO=IO(),a5=bO(),LDe=Go.TracesSamplerValues.AlwaysOn,zc=1;function xDe(){let t=(0,Go.getEnv)();return{sampler:u5(t),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:t.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,attributeCountLimit:t.OTEL_ATTRIBUTE_COUNT_LIMIT},spanLimits:{attributeValueLengthLimit:t.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,attributeCountLimit:t.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,linkCountLimit:t.OTEL_SPAN_LINK_COUNT_LIMIT,eventCountLimit:t.OTEL_SPAN_EVENT_COUNT_LIMIT,attributePerEventCountLimit:t.OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,attributePerLinkCountLimit:t.OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT},mergeResourceWithDefaults:!0}}Xc.loadDefaultConfig=xDe;function u5(t=(0,Go.getEnv)()){switch(t.OTEL_TRACES_SAMPLER){case Go.TracesSamplerValues.AlwaysOn:return new MO.AlwaysOnSampler;case Go.TracesSamplerValues.AlwaysOff:return new i5.AlwaysOffSampler;case Go.TracesSamplerValues.ParentBasedAlwaysOn:return new LO.ParentBasedSampler({root:new MO.AlwaysOnSampler});case Go.TracesSamplerValues.ParentBasedAlwaysOff:return new LO.ParentBasedSampler({root:new i5.AlwaysOffSampler});case Go.TracesSamplerValues.TraceIdRatio:return new a5.TraceIdRatioBasedSampler(c5(t));case Go.TracesSamplerValues.ParentBasedTraceIdRatio:return new LO.ParentBasedSampler({root:new a5.TraceIdRatioBasedSampler(c5(t))});default:return bE.diag.error(`OTEL_TRACES_SAMPLER value "${t.OTEL_TRACES_SAMPLER} invalid, defaulting to ${LDe}".`),new MO.AlwaysOnSampler}}Xc.buildSamplerFromEnv=u5;function c5(t){if(t.OTEL_TRACES_SAMPLER_ARG===void 0||t.OTEL_TRACES_SAMPLER_ARG==="")return bE.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${zc}.`),zc;let e=Number(t.OTEL_TRACES_SAMPLER_ARG);return isNaN(e)?(bE.diag.error(`OTEL_TRACES_SAMPLER_ARG=${t.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${zc}.`),zc):e<0||e>1?(bE.diag.error(`OTEL_TRACES_SAMPLER_ARG=${t.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${zc}.`),zc):e}});var UO=m(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.reconfigureLimits=Jc.mergeConfig=void 0;var l5=xO(),DO=Se();function DDe(t){let e={sampler:(0,l5.buildSamplerFromEnv)()},n=(0,l5.loadDefaultConfig)(),r=Object.assign({},n,e,t);return r.generalLimits=Object.assign({},n.generalLimits,t.generalLimits||{}),r.spanLimits=Object.assign({},n.spanLimits,t.spanLimits||{}),r}Jc.mergeConfig=DDe;function UDe(t){var e,n,r,o,s,i,a,c,u,l,d,p;let _=Object.assign({},t.spanLimits),f=(0,DO.getEnvWithoutDefaults)();return _.attributeCountLimit=(i=(s=(o=(n=(e=t.spanLimits)===null||e===void 0?void 0:e.attributeCountLimit)!==null&&n!==void 0?n:(r=t.generalLimits)===null||r===void 0?void 0:r.attributeCountLimit)!==null&&o!==void 0?o:f.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT)!==null&&s!==void 0?s:f.OTEL_ATTRIBUTE_COUNT_LIMIT)!==null&&i!==void 0?i:DO.DEFAULT_ATTRIBUTE_COUNT_LIMIT,_.attributeValueLengthLimit=(p=(d=(l=(c=(a=t.spanLimits)===null||a===void 0?void 0:a.attributeValueLengthLimit)!==null&&c!==void 0?c:(u=t.generalLimits)===null||u===void 0?void 0:u.attributeValueLengthLimit)!==null&&l!==void 0?l:f.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT)!==null&&d!==void 0?d:f.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT)!==null&&p!==void 0?p:DO.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},t,{spanLimits:_})}Jc.reconfigureLimits=UDe});var d5=m(ME=>{"use strict";Object.defineProperty(ME,"__esModule",{value:!0});ME.BatchSpanProcessorBase=void 0;var Zc=(x(),b(B)),Sa=Se(),wO=class{constructor(e,n){this._exporter=e,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;let r=(0,Sa.getEnv)();this._maxExportBatchSize=typeof n?.maxExportBatchSize=="number"?n.maxExportBatchSize:r.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof n?.maxQueueSize=="number"?n.maxQueueSize:r.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof n?.scheduledDelayMillis=="number"?n.scheduledDelayMillis:r.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof n?.exportTimeoutMillis=="number"?n.exportTimeoutMillis:r.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new Sa.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(Zc.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,n){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&Zc.TraceFlags.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&Zc.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(Zc.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,n)=>{let r=[],o=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let s=0,i=o;s<i;s++)r.push(this._flushOneBatch());Promise.all(r).then(()=>{e()}).catch(n)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,n)=>{let r=setTimeout(()=>{n(new Error("Timeout"))},this._exportTimeoutMillis);Zc.context.with((0,Sa.suppressTracing)(Zc.context.active()),()=>{let o;this._finishedSpans.length<=this._maxExportBatchSize?(o=this._finishedSpans,this._finishedSpans=[]):o=this._finishedSpans.splice(0,this._maxExportBatchSize);let s=()=>this._exporter.export(o,a=>{var c;clearTimeout(r),a.code===Sa.ExportResultCode.SUCCESS?e():n((c=a.error)!==null&&c!==void 0?c:new Error("BatchSpanProcessor: span export failed"))}),i=null;for(let a=0,c=o.length;a<c;a++){let u=o[a];u.resource.asyncAttributesPending&&u.resource.waitForAsyncAttributes&&(i??(i=[]),i.push(u.resource.waitForAsyncAttributes()))}i===null?s():Promise.all(i).then(s,a=>{(0,Sa.globalErrorHandler)(a),n(a)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(n=>{this._isExporting=!1,(0,Sa.globalErrorHandler)(n)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),(0,Sa.unrefTimer)(this._timer))}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}};ME.BatchSpanProcessorBase=wO});var p5=m(LE=>{"use strict";Object.defineProperty(LE,"__esModule",{value:!0});LE.BatchSpanProcessor=void 0;var wDe=d5(),kO=class extends wDe.BatchSpanProcessorBase{onShutdown(){}};LE.BatchSpanProcessor=kO});var m5=m(DE=>{"use strict";Object.defineProperty(DE,"__esModule",{value:!0});DE.RandomIdGenerator=void 0;var kDe=8,f5=16,VO=class{constructor(){this.generateTraceId=_5(f5),this.generateSpanId=_5(kDe)}};DE.RandomIdGenerator=VO;var xE=Buffer.allocUnsafe(f5);function _5(t){return function(){for(let n=0;n<t/4;n++)xE.writeUInt32BE(Math.random()*2**32>>>0,n*4);for(let n=0;n<t&&!(xE[n]>0);n++)n===t-1&&(xE[t-1]=1);return xE.toString("hex",0,t)}}});var E5=m(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.RandomIdGenerator=Qc.BatchSpanProcessor=void 0;var VDe=p5();Object.defineProperty(Qc,"BatchSpanProcessor",{enumerable:!0,get:function(){return VDe.BatchSpanProcessor}});var BDe=m5();Object.defineProperty(Qc,"RandomIdGenerator",{enumerable:!0,get:function(){return BDe.RandomIdGenerator}})});var UE=m(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.RandomIdGenerator=eu.BatchSpanProcessor=void 0;var S5=E5();Object.defineProperty(eu,"BatchSpanProcessor",{enumerable:!0,get:function(){return S5.BatchSpanProcessor}});Object.defineProperty(eu,"RandomIdGenerator",{enumerable:!0,get:function(){return S5.RandomIdGenerator}})});var GO=m(kE=>{"use strict";Object.defineProperty(kE,"__esModule",{value:!0});kE.Tracer=void 0;var Ut=(x(),b(B)),wE=Se(),GDe=yO(),HDe=UO(),$De=UE(),BO=class{constructor(e,n,r){this._tracerProvider=r;let o=(0,HDe.mergeConfig)(n);this._sampler=o.sampler,this._generalLimits=o.generalLimits,this._spanLimits=o.spanLimits,this._idGenerator=n.idGenerator||new $De.RandomIdGenerator,this.resource=r.resource,this.instrumentationLibrary=e}startSpan(e,n={},r=Ut.context.active()){var o,s,i;n.root&&(r=Ut.trace.deleteSpan(r));let a=Ut.trace.getSpan(r);if((0,wE.isTracingSuppressed)(r))return Ut.diag.debug("Instrumentation suppressed, returning Noop Span"),Ut.trace.wrapSpanContext(Ut.INVALID_SPAN_CONTEXT);let c=a?.spanContext(),u=this._idGenerator.generateSpanId(),l,d,p;!c||!Ut.trace.isSpanContextValid(c)?l=this._idGenerator.generateTraceId():(l=c.traceId,d=c.traceState,p=c.spanId);let _=(o=n.kind)!==null&&o!==void 0?o:Ut.SpanKind.INTERNAL,f=((s=n.links)!==null&&s!==void 0?s:[]).map(y=>({context:y.context,attributes:(0,wE.sanitizeAttributes)(y.attributes)})),E=(0,wE.sanitizeAttributes)(n.attributes),S=this._sampler.shouldSample(r,l,e,_,E,f);d=(i=S.traceState)!==null&&i!==void 0?i:d;let h=S.decision===Ut.SamplingDecision.RECORD_AND_SAMPLED?Ut.TraceFlags.SAMPLED:Ut.TraceFlags.NONE,R={traceId:l,spanId:u,traceFlags:h,traceState:d};if(S.decision===Ut.SamplingDecision.NOT_RECORD)return Ut.diag.debug("Recording is off, propagating context in a non-recording span"),Ut.trace.wrapSpanContext(R);let A=(0,wE.sanitizeAttributes)(Object.assign(E,S.attributes));return new GDe.Span(this,r,e,R,_,p,f,n.startTime,void 0,A)}startActiveSpan(e,n,r,o){let s,i,a;if(arguments.length<2)return;arguments.length===2?a=n:arguments.length===3?(s=n,a=r):(s=n,i=r,a=o);let c=i??Ut.context.active(),u=this.startSpan(e,s,c),l=Ut.trace.setSpan(c,u);return Ut.context.with(l,a,void 0,u)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}getActiveSpanProcessor(){return this._tracerProvider.getActiveSpanProcessor()}};kE.Tracer=BO});var g5=m(VE=>{"use strict";Object.defineProperty(VE,"__esModule",{value:!0});VE.defaultServiceName=void 0;function FDe(){return`unknown_service:${process.argv0}`}VE.defaultServiceName=FDe});var h5=m(BE=>{"use strict";Object.defineProperty(BE,"__esModule",{value:!0});BE.defaultServiceName=void 0;var jDe=g5();Object.defineProperty(BE,"defaultServiceName",{enumerable:!0,get:function(){return jDe.defaultServiceName}})});var HO=m(GE=>{"use strict";Object.defineProperty(GE,"__esModule",{value:!0});GE.defaultServiceName=void 0;var qDe=h5();Object.defineProperty(GE,"defaultServiceName",{enumerable:!0,get:function(){return qDe.defaultServiceName}})});var Ho=m(HE=>{"use strict";Object.defineProperty(HE,"__esModule",{value:!0});HE.Resource=void 0;var T5=(x(),b(B)),ga=(zn(),b(Wn)),$O=Se(),YDe=HO(),bd=class t{constructor(e,n){var r;this._attributes=e,this.asyncAttributesPending=n!=null,this._syncAttributes=(r=this._attributes)!==null&&r!==void 0?r:{},this._asyncAttributesPromise=n?.then(o=>(this._attributes=Object.assign({},this._attributes,o),this.asyncAttributesPending=!1,o),o=>(T5.diag.debug("a resource's async attributes promise rejected: %s",o),this.asyncAttributesPending=!1,{}))}static empty(){return t.EMPTY}static default(){return new t({[ga.SEMRESATTRS_SERVICE_NAME]:(0,YDe.defaultServiceName)(),[ga.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:$O.SDK_INFO[ga.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE],[ga.SEMRESATTRS_TELEMETRY_SDK_NAME]:$O.SDK_INFO[ga.SEMRESATTRS_TELEMETRY_SDK_NAME],[ga.SEMRESATTRS_TELEMETRY_SDK_VERSION]:$O.SDK_INFO[ga.SEMRESATTRS_TELEMETRY_SDK_VERSION]})}get attributes(){var e;return this.asyncAttributesPending&&T5.diag.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}}async waitForAsyncAttributes(){this.asyncAttributesPending&&await this._asyncAttributesPromise}merge(e){var n;if(!e)return this;let r=Object.assign(Object.assign({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(r);let o=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(([s,i])=>{var a;return Object.assign(Object.assign(Object.assign(Object.assign({},this._syncAttributes),s),(a=e._syncAttributes)!==null&&a!==void 0?a:e.attributes),i)});return new t(r,o)}};HE.Resource=bd;bd.EMPTY=new bd({})});var FO=m(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.normalizeType=tu.normalizeArch=void 0;var KDe=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};tu.normalizeArch=KDe;var WDe=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};tu.normalizeType=WDe});var FE=m($E=>{"use strict";Object.defineProperty($E,"__esModule",{value:!0});$E.execAsync=void 0;var zDe=require("child_process"),XDe=require("util");$E.execAsync=XDe.promisify(zDe.exec)});var A5=m(jE=>{"use strict";Object.defineProperty(jE,"__esModule",{value:!0});jE.getMachineId=void 0;var JDe=FE(),ZDe=(x(),b(B));async function QDe(){try{let e=(await(0,JDe.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
6
- `).find(r=>r.includes("IOPlatformUUID"));if(!e)return"";let n=e.split('" = "');if(n.length===2)return n[1].slice(0,-1)}catch(t){ZDe.diag.debug(`error reading machine id: ${t}`)}return""}jE.getMachineId=QDe});var R5=m(qE=>{"use strict";Object.defineProperty(qE,"__esModule",{value:!0});qE.getMachineId=void 0;var eUe=require("fs"),tUe=(x(),b(B));async function nUe(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await eUe.promises.readFile(e,{encoding:"utf8"})).trim()}catch(n){tUe.diag.debug(`error reading machine id: ${n}`)}return""}qE.getMachineId=nUe});var O5=m(YE=>{"use strict";Object.defineProperty(YE,"__esModule",{value:!0});YE.getMachineId=void 0;var rUe=require("fs"),oUe=FE(),y5=(x(),b(B));async function sUe(){try{return(await rUe.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){y5.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,oUe.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){y5.diag.debug(`error reading machine id: ${t}`)}return""}YE.getMachineId=sUe});var C5=m(KE=>{"use strict";Object.defineProperty(KE,"__esModule",{value:!0});KE.getMachineId=void 0;var N5=require("process"),iUe=FE(),aUe=(x(),b(B));async function cUe(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";N5.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in N5.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let r=(await(0,iUe.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(r.length===2)return r[1].trim()}catch(n){aUe.diag.debug(`error reading machine id: ${n}`)}return""}KE.getMachineId=cUe});var v5=m(WE=>{"use strict";Object.defineProperty(WE,"__esModule",{value:!0});WE.getMachineId=void 0;var uUe=(x(),b(B));async function lUe(){return uUe.diag.debug("could not read machine-id: unsupported platform"),""}WE.getMachineId=lUe});var I5=m($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.getMachineId=void 0;var dUe=require("process"),nu;$o.getMachineId=nu;switch(dUe.platform){case"darwin":$o.getMachineId=nu=A5().getMachineId;break;case"linux":$o.getMachineId=nu=R5().getMachineId;break;case"freebsd":$o.getMachineId=nu=O5().getMachineId;break;case"win32":$o.getMachineId=nu=C5().getMachineId;break;default:$o.getMachineId=nu=v5().getMachineId}});var YO=m(zE=>{"use strict";Object.defineProperty(zE,"__esModule",{value:!0});zE.hostDetectorSync=void 0;var jO=(zn(),b(Wn)),pUe=Ho(),P5=require("os"),_Ue=FO(),fUe=I5(),qO=class{detect(e){let n={[jO.SEMRESATTRS_HOST_NAME]:(0,P5.hostname)(),[jO.SEMRESATTRS_HOST_ARCH]:(0,_Ue.normalizeArch)((0,P5.arch)())};return new pUe.Resource(n,this._getAsyncAttributes())}_getAsyncAttributes(){return(0,fUe.getMachineId)().then(e=>{let n={};return e&&(n[jO.SEMRESATTRS_HOST_ID]=e),n})}};zE.hostDetectorSync=new qO});var b5=m(XE=>{"use strict";Object.defineProperty(XE,"__esModule",{value:!0});XE.hostDetector=void 0;var mUe=YO(),KO=class{detect(e){return Promise.resolve(mUe.hostDetectorSync.detect(e))}};XE.hostDetector=new KO});var zO=m(JE=>{"use strict";Object.defineProperty(JE,"__esModule",{value:!0});JE.osDetectorSync=void 0;var M5=(zn(),b(Wn)),EUe=Ho(),L5=require("os"),SUe=FO(),WO=class{detect(e){let n={[M5.SEMRESATTRS_OS_TYPE]:(0,SUe.normalizeType)((0,L5.platform)()),[M5.SEMRESATTRS_OS_VERSION]:(0,L5.release)()};return new EUe.Resource(n)}};JE.osDetectorSync=new WO});var x5=m(ZE=>{"use strict";Object.defineProperty(ZE,"__esModule",{value:!0});ZE.osDetector=void 0;var gUe=zO(),XO=class{detect(e){return Promise.resolve(gUe.osDetectorSync.detect(e))}};ZE.osDetector=new XO});var ZO=m(QE=>{"use strict";Object.defineProperty(QE,"__esModule",{value:!0});QE.processDetectorSync=void 0;var hUe=(x(),b(B)),Fo=(zn(),b(Wn)),TUe=Ho(),AUe=require("os"),JO=class{detect(e){let n={[Fo.SEMRESATTRS_PROCESS_PID]:process.pid,[Fo.SEMRESATTRS_PROCESS_EXECUTABLE_NAME]:process.title,[Fo.SEMRESATTRS_PROCESS_EXECUTABLE_PATH]:process.execPath,[Fo.SEMRESATTRS_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[Fo.SEMRESATTRS_PROCESS_RUNTIME_VERSION]:process.versions.node,[Fo.SEMRESATTRS_PROCESS_RUNTIME_NAME]:"nodejs",[Fo.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(n[Fo.SEMRESATTRS_PROCESS_COMMAND]=process.argv[1]);try{let r=AUe.userInfo();n[Fo.SEMRESATTRS_PROCESS_OWNER]=r.username}catch(r){hUe.diag.debug(`error obtaining process owner: ${r}`)}return new TUe.Resource(n)}};QE.processDetectorSync=new JO});var D5=m(eS=>{"use strict";Object.defineProperty(eS,"__esModule",{value:!0});eS.processDetector=void 0;var RUe=ZO(),QO=class{detect(e){return Promise.resolve(RUe.processDetectorSync.detect(e))}};eS.processDetector=new QO});var U5=m(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});tS.serviceInstanceIdDetectorSync=void 0;var yUe=(zn(),b(Wn)),OUe=Ho(),NUe=require("crypto"),eN=class{detect(e){let n={[yUe.SEMRESATTRS_SERVICE_INSTANCE_ID]:(0,NUe.randomUUID)()};return new OUe.Resource(n)}};tS.serviceInstanceIdDetectorSync=new eN});var w5=m(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.serviceInstanceIdDetectorSync=Xt.processDetectorSync=Xt.processDetector=Xt.osDetectorSync=Xt.osDetector=Xt.hostDetectorSync=Xt.hostDetector=void 0;var CUe=b5();Object.defineProperty(Xt,"hostDetector",{enumerable:!0,get:function(){return CUe.hostDetector}});var vUe=YO();Object.defineProperty(Xt,"hostDetectorSync",{enumerable:!0,get:function(){return vUe.hostDetectorSync}});var IUe=x5();Object.defineProperty(Xt,"osDetector",{enumerable:!0,get:function(){return IUe.osDetector}});var PUe=zO();Object.defineProperty(Xt,"osDetectorSync",{enumerable:!0,get:function(){return PUe.osDetectorSync}});var bUe=D5();Object.defineProperty(Xt,"processDetector",{enumerable:!0,get:function(){return bUe.processDetector}});var MUe=ZO();Object.defineProperty(Xt,"processDetectorSync",{enumerable:!0,get:function(){return MUe.processDetectorSync}});var LUe=U5();Object.defineProperty(Xt,"serviceInstanceIdDetectorSync",{enumerable:!0,get:function(){return LUe.serviceInstanceIdDetectorSync}})});var k5=m(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.serviceInstanceIdDetectorSync=Jt.processDetectorSync=Jt.processDetector=Jt.osDetectorSync=Jt.osDetector=Jt.hostDetectorSync=Jt.hostDetector=void 0;var ha=w5();Object.defineProperty(Jt,"hostDetector",{enumerable:!0,get:function(){return ha.hostDetector}});Object.defineProperty(Jt,"hostDetectorSync",{enumerable:!0,get:function(){return ha.hostDetectorSync}});Object.defineProperty(Jt,"osDetector",{enumerable:!0,get:function(){return ha.osDetector}});Object.defineProperty(Jt,"osDetectorSync",{enumerable:!0,get:function(){return ha.osDetectorSync}});Object.defineProperty(Jt,"processDetector",{enumerable:!0,get:function(){return ha.processDetector}});Object.defineProperty(Jt,"processDetectorSync",{enumerable:!0,get:function(){return ha.processDetectorSync}});Object.defineProperty(Jt,"serviceInstanceIdDetectorSync",{enumerable:!0,get:function(){return ha.serviceInstanceIdDetectorSync}})});var rN=m(rS=>{"use strict";Object.defineProperty(rS,"__esModule",{value:!0});rS.browserDetectorSync=void 0;var nS=(zn(),b(Wn)),xUe=(x(),b(B)),tN=Ho(),nN=class{detect(e){var n,r,o;if(!(typeof navigator<"u"&&((r=(n=global.process)===null||n===void 0?void 0:n.versions)===null||r===void 0?void 0:r.node)===void 0&&((o=global.Bun)===null||o===void 0?void 0:o.version)===void 0))return tN.Resource.empty();let i={[nS.SEMRESATTRS_PROCESS_RUNTIME_NAME]:"browser",[nS.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION]:"Web Browser",[nS.SEMRESATTRS_PROCESS_RUNTIME_VERSION]:navigator.userAgent};return this._getResourceAttributes(i,e)}_getResourceAttributes(e,n){return e[nS.SEMRESATTRS_PROCESS_RUNTIME_VERSION]===""?(xUe.diag.debug("BrowserDetector failed: Unable to find required browser resources. "),tN.Resource.empty()):new tN.Resource(Object.assign({},e))}};rS.browserDetectorSync=new nN});var V5=m(oS=>{"use strict";Object.defineProperty(oS,"__esModule",{value:!0});oS.browserDetector=void 0;var DUe=rN(),oN=class{detect(e){return Promise.resolve(DUe.browserDetectorSync.detect(e))}};oS.browserDetector=new oN});var iN=m(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});sS.envDetectorSync=void 0;var UUe=(x(),b(B)),wUe=Se(),kUe=(zn(),b(Wn)),VUe=Ho(),sN=class{constructor(){this._MAX_LENGTH=255,this._COMMA_SEPARATOR=",",this._LABEL_KEY_VALUE_SPLITTER="=",this._ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.",this._ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters."}detect(e){let n={},r=(0,wUe.getEnv)(),o=r.OTEL_RESOURCE_ATTRIBUTES,s=r.OTEL_SERVICE_NAME;if(o)try{let i=this._parseResourceAttributes(o);Object.assign(n,i)}catch(i){UUe.diag.debug(`EnvDetector failed: ${i.message}`)}return s&&(n[kUe.SEMRESATTRS_SERVICE_NAME]=s),new VUe.Resource(n)}_parseResourceAttributes(e){if(!e)return{};let n={},r=e.split(this._COMMA_SEPARATOR,-1);for(let o of r){let s=o.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(s.length!==2)continue;let[i,a]=s;if(i=i.trim(),a=a.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(i))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(a))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);n[i]=decodeURIComponent(a)}return n}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<33||r===44||r===59||r===92||r>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}};sS.envDetectorSync=new sN});var B5=m(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});iS.envDetector=void 0;var BUe=iN(),aN=class{detect(e){return Promise.resolve(BUe.envDetectorSync.detect(e))}};iS.envDetector=new aN});var G5=m(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.envDetectorSync=ke.browserDetectorSync=ke.envDetector=ke.browserDetector=ke.serviceInstanceIdDetectorSync=ke.processDetectorSync=ke.processDetector=ke.osDetectorSync=ke.osDetector=ke.hostDetectorSync=ke.hostDetector=void 0;var Ta=k5();Object.defineProperty(ke,"hostDetector",{enumerable:!0,get:function(){return Ta.hostDetector}});Object.defineProperty(ke,"hostDetectorSync",{enumerable:!0,get:function(){return Ta.hostDetectorSync}});Object.defineProperty(ke,"osDetector",{enumerable:!0,get:function(){return Ta.osDetector}});Object.defineProperty(ke,"osDetectorSync",{enumerable:!0,get:function(){return Ta.osDetectorSync}});Object.defineProperty(ke,"processDetector",{enumerable:!0,get:function(){return Ta.processDetector}});Object.defineProperty(ke,"processDetectorSync",{enumerable:!0,get:function(){return Ta.processDetectorSync}});Object.defineProperty(ke,"serviceInstanceIdDetectorSync",{enumerable:!0,get:function(){return Ta.serviceInstanceIdDetectorSync}});var GUe=V5();Object.defineProperty(ke,"browserDetector",{enumerable:!0,get:function(){return GUe.browserDetector}});var HUe=B5();Object.defineProperty(ke,"envDetector",{enumerable:!0,get:function(){return HUe.envDetector}});var $Ue=rN();Object.defineProperty(ke,"browserDetectorSync",{enumerable:!0,get:function(){return $Ue.browserDetectorSync}});var FUe=iN();Object.defineProperty(ke,"envDetectorSync",{enumerable:!0,get:function(){return FUe.envDetectorSync}})});var H5=m(aS=>{"use strict";Object.defineProperty(aS,"__esModule",{value:!0});aS.isPromiseLike=void 0;var jUe=t=>t!==null&&typeof t=="object"&&typeof t.then=="function";aS.isPromiseLike=jUe});var F5=m(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.detectResourcesSync=ou.detectResources=void 0;var Md=Ho(),ru=(x(),b(B)),qUe=H5(),YUe=async(t={})=>{let e=await Promise.all((t.detectors||[]).map(async n=>{try{let r=await n.detect(t);return ru.diag.debug(`${n.constructor.name} found resource.`,r),r}catch(r){return ru.diag.debug(`${n.constructor.name} failed: ${r.message}`),Md.Resource.empty()}}));return $5(e),e.reduce((n,r)=>n.merge(r),Md.Resource.empty())};ou.detectResources=YUe;var KUe=(t={})=>{var e;let n=((e=t.detectors)!==null&&e!==void 0?e:[]).map(o=>{try{let s=o.detect(t),i;if((0,qUe.isPromiseLike)(s)){let a=async()=>{var c;let u=await s;return await((c=u.waitForAsyncAttributes)===null||c===void 0?void 0:c.call(u)),u.attributes};i=new Md.Resource({},a())}else i=s;return i.waitForAsyncAttributes?i.waitForAsyncAttributes().then(()=>ru.diag.debug(`${o.constructor.name} found resource.`,i)):ru.diag.debug(`${o.constructor.name} found resource.`,i),i}catch(s){return ru.diag.error(`${o.constructor.name} failed: ${s.message}`),Md.Resource.empty()}}),r=n.reduce((o,s)=>o.merge(s),Md.Resource.empty());return r.waitForAsyncAttributes&&r.waitForAsyncAttributes().then(()=>{$5(n)}),r};ou.detectResourcesSync=KUe;var $5=t=>{t.forEach(e=>{if(Object.keys(e.attributes).length>0){let n=JSON.stringify(e.attributes,null,4);ru.diag.verbose(n)}})}});var cN=m(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.detectResources=ge.detectResourcesSync=ge.serviceInstanceIdDetectorSync=ge.processDetectorSync=ge.processDetector=ge.osDetectorSync=ge.osDetector=ge.hostDetectorSync=ge.hostDetector=ge.envDetectorSync=ge.envDetector=ge.browserDetectorSync=ge.browserDetector=ge.defaultServiceName=ge.Resource=void 0;var WUe=Ho();Object.defineProperty(ge,"Resource",{enumerable:!0,get:function(){return WUe.Resource}});var zUe=HO();Object.defineProperty(ge,"defaultServiceName",{enumerable:!0,get:function(){return zUe.defaultServiceName}});var Mr=G5();Object.defineProperty(ge,"browserDetector",{enumerable:!0,get:function(){return Mr.browserDetector}});Object.defineProperty(ge,"browserDetectorSync",{enumerable:!0,get:function(){return Mr.browserDetectorSync}});Object.defineProperty(ge,"envDetector",{enumerable:!0,get:function(){return Mr.envDetector}});Object.defineProperty(ge,"envDetectorSync",{enumerable:!0,get:function(){return Mr.envDetectorSync}});Object.defineProperty(ge,"hostDetector",{enumerable:!0,get:function(){return Mr.hostDetector}});Object.defineProperty(ge,"hostDetectorSync",{enumerable:!0,get:function(){return Mr.hostDetectorSync}});Object.defineProperty(ge,"osDetector",{enumerable:!0,get:function(){return Mr.osDetector}});Object.defineProperty(ge,"osDetectorSync",{enumerable:!0,get:function(){return Mr.osDetectorSync}});Object.defineProperty(ge,"processDetector",{enumerable:!0,get:function(){return Mr.processDetector}});Object.defineProperty(ge,"processDetectorSync",{enumerable:!0,get:function(){return Mr.processDetectorSync}});Object.defineProperty(ge,"serviceInstanceIdDetectorSync",{enumerable:!0,get:function(){return Mr.serviceInstanceIdDetectorSync}});var j5=F5();Object.defineProperty(ge,"detectResourcesSync",{enumerable:!0,get:function(){return j5.detectResourcesSync}});Object.defineProperty(ge,"detectResources",{enumerable:!0,get:function(){return j5.detectResources}})});var q5=m(cS=>{"use strict";Object.defineProperty(cS,"__esModule",{value:!0});cS.MultiSpanProcessor=void 0;var XUe=Se(),uN=class{constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let n of this._spanProcessors)e.push(n.forceFlush());return new Promise(n=>{Promise.all(e).then(()=>{n()}).catch(r=>{(0,XUe.globalErrorHandler)(r||new Error("MultiSpanProcessor: forceFlush failed")),n()})})}onStart(e,n){for(let r of this._spanProcessors)r.onStart(e,n)}onEnd(e){for(let n of this._spanProcessors)n.onEnd(e)}shutdown(){let e=[];for(let n of this._spanProcessors)e.push(n.shutdown());return new Promise((n,r)=>{Promise.all(e).then(()=>{n()},r)})}};cS.MultiSpanProcessor=uN});var dN=m(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});uS.NoopSpanProcessor=void 0;var lN=class{onStart(e,n){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}};uS.NoopSpanProcessor=lN});var W5=m(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.BasicTracerProvider=Aa.ForceFlushState=void 0;var su=(x(),b(B)),au=Se(),Y5=cN(),JUe=GO(),ZUe=xO(),K5=q5(),QUe=dN(),ewe=UE(),twe=UO(),iu;(function(t){t[t.resolved=0]="resolved",t[t.timeout=1]="timeout",t[t.error=2]="error",t[t.unresolved=3]="unresolved"})(iu=Aa.ForceFlushState||(Aa.ForceFlushState={}));var Ld=class{constructor(e={}){var n,r;this._registeredSpanProcessors=[],this._tracers=new Map;let o=(0,au.merge)({},(0,ZUe.loadDefaultConfig)(),(0,twe.reconfigureLimits)(e));if(this.resource=(n=o.resource)!==null&&n!==void 0?n:Y5.Resource.empty(),o.mergeResourceWithDefaults&&(this.resource=Y5.Resource.default().merge(this.resource)),this._config=Object.assign({},o,{resource:this.resource}),!((r=e.spanProcessors)===null||r===void 0)&&r.length)this._registeredSpanProcessors=[...e.spanProcessors],this.activeSpanProcessor=new K5.MultiSpanProcessor(this._registeredSpanProcessors);else{let s=this._buildExporterFromEnv();if(s!==void 0){let i=new ewe.BatchSpanProcessor(s);this.activeSpanProcessor=i}else this.activeSpanProcessor=new QUe.NoopSpanProcessor}}getTracer(e,n,r){let o=`${e}@${n||""}:${r?.schemaUrl||""}`;return this._tracers.has(o)||this._tracers.set(o,new JUe.Tracer({name:e,version:n,schemaUrl:r?.schemaUrl},this._config,this)),this._tracers.get(o)}addSpanProcessor(e){this._registeredSpanProcessors.length===0&&this.activeSpanProcessor.shutdown().catch(n=>su.diag.error("Error while trying to shutdown current span processor",n)),this._registeredSpanProcessors.push(e),this.activeSpanProcessor=new K5.MultiSpanProcessor(this._registeredSpanProcessors)}getActiveSpanProcessor(){return this.activeSpanProcessor}register(e={}){su.trace.setGlobalTracerProvider(this),e.propagator===void 0&&(e.propagator=this._buildPropagatorFromEnv()),e.contextManager&&su.context.setGlobalContextManager(e.contextManager),e.propagator&&su.propagation.setGlobalPropagator(e.propagator)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,n=this._registeredSpanProcessors.map(r=>new Promise(o=>{let s,i=setTimeout(()=>{o(new Error(`Span processor did not completed within timeout period of ${e} ms`)),s=iu.timeout},e);r.forceFlush().then(()=>{clearTimeout(i),s!==iu.timeout&&(s=iu.resolved,o(s))}).catch(a=>{clearTimeout(i),s=iu.error,o(a)})}));return new Promise((r,o)=>{Promise.all(n).then(s=>{let i=s.filter(a=>a!==iu.resolved);i.length>0?o(i):r()}).catch(s=>o([s]))})}shutdown(){return this.activeSpanProcessor.shutdown()}_getPropagator(e){var n;return(n=this.constructor._registeredPropagators.get(e))===null||n===void 0?void 0:n()}_getSpanExporter(e){var n;return(n=this.constructor._registeredExporters.get(e))===null||n===void 0?void 0:n()}_buildPropagatorFromEnv(){let e=Array.from(new Set((0,au.getEnv)().OTEL_PROPAGATORS)),r=e.map(o=>{let s=this._getPropagator(o);return s||su.diag.warn(`Propagator "${o}" requested through environment variable is unavailable.`),s}).reduce((o,s)=>(s&&o.push(s),o),[]);if(r.length!==0)return e.length===1?r[0]:new au.CompositePropagator({propagators:r})}_buildExporterFromEnv(){let e=(0,au.getEnv)().OTEL_TRACES_EXPORTER;if(e==="none"||e==="")return;let n=this._getSpanExporter(e);return n||su.diag.error(`Exporter "${e}" requested through environment variable is unavailable.`),n}};Aa.BasicTracerProvider=Ld;Ld._registeredPropagators=new Map([["tracecontext",()=>new au.W3CTraceContextPropagator],["baggage",()=>new au.W3CBaggagePropagator]]);Ld._registeredExporters=new Map});var z5=m(lS=>{"use strict";Object.defineProperty(lS,"__esModule",{value:!0});lS.ConsoleSpanExporter=void 0;var pN=Se(),_N=class{export(e,n){return this._sendSpans(e,n)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){var n;return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationLibrary,traceId:e.spanContext().traceId,parentId:e.parentSpanId,traceState:(n=e.spanContext().traceState)===null||n===void 0?void 0:n.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:(0,pN.hrTimeToMicroseconds)(e.startTime),duration:(0,pN.hrTimeToMicroseconds)(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,n){for(let r of e)console.dir(this._exportInfo(r),{depth:3});if(n)return n({code:pN.ExportResultCode.SUCCESS})}};lS.ConsoleSpanExporter=_N});var J5=m(dS=>{"use strict";Object.defineProperty(dS,"__esModule",{value:!0});dS.InMemorySpanExporter=void 0;var X5=Se(),fN=class{constructor(){this._finishedSpans=[],this._stopped=!1}export(e,n){if(this._stopped)return n({code:X5.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...e),setTimeout(()=>n({code:X5.ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}};dS.InMemorySpanExporter=fN});var Z5=m(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.SimpleSpanProcessor=void 0;var nwe=(x(),b(B)),cu=Se(),mN=class{constructor(e){this._exporter=e,this._shutdownOnce=new cu.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,n){}onEnd(e){var n,r;if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&nwe.TraceFlags.SAMPLED)===0)return;let o=()=>cu.internal._export(this._exporter,[e]).then(s=>{var i;s.code!==cu.ExportResultCode.SUCCESS&&(0,cu.globalErrorHandler)((i=s.error)!==null&&i!==void 0?i:new Error(`SimpleSpanProcessor: span export failed (status ${s})`))}).catch(s=>{(0,cu.globalErrorHandler)(s)});if(e.resource.asyncAttributesPending){let s=(r=(n=e.resource).waitForAsyncAttributes)===null||r===void 0?void 0:r.call(n).then(()=>(s!=null&&this._unresolvedExports.delete(s),o()),i=>(0,cu.globalErrorHandler)(i));s!=null&&this._unresolvedExports.add(s)}else o()}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}};pS.SimpleSpanProcessor=mN});var EN=m(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.Span=he.SamplingDecision=he.TraceIdRatioBasedSampler=he.ParentBasedSampler=he.AlwaysOnSampler=he.AlwaysOffSampler=he.NoopSpanProcessor=he.SimpleSpanProcessor=he.InMemorySpanExporter=he.ConsoleSpanExporter=he.RandomIdGenerator=he.BatchSpanProcessor=he.ForceFlushState=he.BasicTracerProvider=he.Tracer=void 0;var rwe=GO();Object.defineProperty(he,"Tracer",{enumerable:!0,get:function(){return rwe.Tracer}});var Q5=W5();Object.defineProperty(he,"BasicTracerProvider",{enumerable:!0,get:function(){return Q5.BasicTracerProvider}});Object.defineProperty(he,"ForceFlushState",{enumerable:!0,get:function(){return Q5.ForceFlushState}});var e3=UE();Object.defineProperty(he,"BatchSpanProcessor",{enumerable:!0,get:function(){return e3.BatchSpanProcessor}});Object.defineProperty(he,"RandomIdGenerator",{enumerable:!0,get:function(){return e3.RandomIdGenerator}});var owe=z5();Object.defineProperty(he,"ConsoleSpanExporter",{enumerable:!0,get:function(){return owe.ConsoleSpanExporter}});var swe=J5();Object.defineProperty(he,"InMemorySpanExporter",{enumerable:!0,get:function(){return swe.InMemorySpanExporter}});var iwe=Z5();Object.defineProperty(he,"SimpleSpanProcessor",{enumerable:!0,get:function(){return iwe.SimpleSpanProcessor}});var awe=dN();Object.defineProperty(he,"NoopSpanProcessor",{enumerable:!0,get:function(){return awe.NoopSpanProcessor}});var cwe=OE();Object.defineProperty(he,"AlwaysOffSampler",{enumerable:!0,get:function(){return cwe.AlwaysOffSampler}});var uwe=CE();Object.defineProperty(he,"AlwaysOnSampler",{enumerable:!0,get:function(){return uwe.AlwaysOnSampler}});var lwe=IO();Object.defineProperty(he,"ParentBasedSampler",{enumerable:!0,get:function(){return lwe.ParentBasedSampler}});var dwe=bO();Object.defineProperty(he,"TraceIdRatioBasedSampler",{enumerable:!0,get:function(){return dwe.TraceIdRatioBasedSampler}});var pwe=Pd();Object.defineProperty(he,"SamplingDecision",{enumerable:!0,get:function(){return pwe.SamplingDecision}});var _we=yO();Object.defineProperty(he,"Span",{enumerable:!0,get:function(){return _we.Span}})});var jN=m(RS=>{"use strict";Object.defineProperty(RS,"__esModule",{value:!0});RS.AbstractAsyncHooksContextManager=void 0;var uke=require("events"),lke=["addListener","on","once","prependListener","prependOnceListener"],FN=class{constructor(){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1}bind(e,n){return n instanceof uke.EventEmitter?this._bindEventEmitter(e,n):typeof n=="function"?this._bindFunction(e,n):n}_bindFunction(e,n){let r=this,o=function(...s){return r.with(e,()=>n.apply(this,s))};return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:n.length}),o}_bindEventEmitter(e,n){return this._getPatchMap(n)!==void 0||(this._createPatchMap(n),lke.forEach(o=>{n[o]!==void 0&&(n[o]=this._patchAddListener(n,n[o],e))}),typeof n.removeListener=="function"&&(n.removeListener=this._patchRemoveListener(n,n.removeListener)),typeof n.off=="function"&&(n.off=this._patchRemoveListener(n,n.off)),typeof n.removeAllListeners=="function"&&(n.removeAllListeners=this._patchRemoveAllListeners(n,n.removeAllListeners))),n}_patchRemoveListener(e,n){let r=this;return function(o,s){var i;let a=(i=r._getPatchMap(e))===null||i===void 0?void 0:i[o];if(a===void 0)return n.call(this,o,s);let c=a.get(s);return n.call(this,o,c||s)}}_patchRemoveAllListeners(e,n){let r=this;return function(o){let s=r._getPatchMap(e);return s!==void 0&&(arguments.length===0?r._createPatchMap(e):s[o]!==void 0&&delete s[o]),n.apply(this,arguments)}}_patchAddListener(e,n,r){let o=this;return function(s,i){if(o._wrapped)return n.call(this,s,i);let a=o._getPatchMap(e);a===void 0&&(a=o._createPatchMap(e));let c=a[s];c===void 0&&(c=new WeakMap,a[s]=c);let u=o.bind(r,i);c.set(i,u),o._wrapped=!0;try{return n.call(this,s,u)}finally{o._wrapped=!1}}}_createPatchMap(e){let n=Object.create(null);return e[this._kOtListeners]=n,n}_getPatchMap(e){return e[this._kOtListeners]}};RS.AbstractAsyncHooksContextManager=FN});var fz=m(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.AsyncHooksContextManager=void 0;var dke=(x(),b(B)),pke=require("async_hooks"),_ke=jN(),qN=class extends _ke.AbstractAsyncHooksContextManager{constructor(){super(),this._contexts=new Map,this._stack=[],this._asyncHook=pke.createHook({init:this._init.bind(this),before:this._before.bind(this),after:this._after.bind(this),destroy:this._destroy.bind(this),promiseResolve:this._destroy.bind(this)})}active(){var e;return(e=this._stack[this._stack.length-1])!==null&&e!==void 0?e:dke.ROOT_CONTEXT}with(e,n,r,...o){this._enterContext(e);try{return n.call(r,...o)}finally{this._exitContext()}}enable(){return this._asyncHook.enable(),this}disable(){return this._asyncHook.disable(),this._contexts.clear(),this._stack=[],this}_init(e,n){if(n==="TIMERWRAP")return;let r=this._stack[this._stack.length-1];r!==void 0&&this._contexts.set(e,r)}_destroy(e){this._contexts.delete(e)}_before(e){let n=this._contexts.get(e);n!==void 0&&this._enterContext(n)}_after(){this._exitContext()}_enterContext(e){this._stack.push(e)}_exitContext(){this._stack.pop()}};yS.AsyncHooksContextManager=qN});var mz=m(OS=>{"use strict";Object.defineProperty(OS,"__esModule",{value:!0});OS.AsyncLocalStorageContextManager=void 0;var fke=(x(),b(B)),mke=require("async_hooks"),Eke=jN(),YN=class extends Eke.AbstractAsyncHooksContextManager{constructor(){super(),this._asyncLocalStorage=new mke.AsyncLocalStorage}active(){var e;return(e=this._asyncLocalStorage.getStore())!==null&&e!==void 0?e:fke.ROOT_CONTEXT}with(e,n,r,...o){let s=r==null?n:n.bind(r);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};OS.AsyncLocalStorageContextManager=YN});var Ez=m(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.AsyncLocalStorageContextManager=Eu.AsyncHooksContextManager=void 0;var Ske=fz();Object.defineProperty(Eu,"AsyncHooksContextManager",{enumerable:!0,get:function(){return Ske.AsyncHooksContextManager}});var gke=mz();Object.defineProperty(Eu,"AsyncLocalStorageContextManager",{enumerable:!0,get:function(){return gke.AsyncLocalStorageContextManager}})});var wz=m(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.PACKAGE_NAME=Su.PACKAGE_VERSION=void 0;Su.PACKAGE_VERSION="0.10.1";Su.PACKAGE_NAME="@opentelemetry/instrumentation-undici"});var kz=m(LS=>{"use strict";Object.defineProperty(LS,"__esModule",{value:!0});LS.SemanticAttributes=void 0;LS.SemanticAttributes={HTTP_CONNECTION_STATE:"http.connection.state",ERROR_TYPE:"error.type",HTTP_REQUEST_BODY_SIZE:"http.request.body.size",HTTP_REQUEST_METHOD:"http.request.method",HTTP_REQUEST_METHOD_ORIGINAL:"http.request.method_original",HTTP_REQUEST_RESEND_COUNT:"http.request.resend_count",HTTP_RESPONSE_BODY_SIZE:"http.response.body.size",HTTP_RESPONSE_STATUS_CODE:"http.response.status_code",HTTP_ROUTE:"http.route",NETWORK_PEER_ADDRESS:"network.peer.address",NETWORK_PEER_PORT:"network.peer.port",NETWORK_PROTOCOL_NAME:"network.protocol.name",NETWORK_PROTOCOL_VERSION:"network.protocol.version",SERVER_ADDRESS:"server.address",SERVER_PORT:"server.port",URL_FULL:"url.full",URL_PATH:"url.path",URL_QUERY:"url.query",URL_SCHEME:"url.scheme",USER_AGENT_ORIGINAL:"user_agent.original"}});var Bz=m(DS=>{"use strict";Object.defineProperty(DS,"__esModule",{value:!0});DS.UndiciInstrumentation=void 0;var qd=require("diagnostics_channel"),$ke=require("url"),Yd=fe(),kn=(x(),b(B)),Vz=wz(),gt=kz(),xS=Se(),eC=class extends Yd.InstrumentationBase{constructor(e={}){super(Vz.PACKAGE_NAME,Vz.PACKAGE_VERSION,e),this._recordFromReq=new WeakMap}init(){}disable(){super.disable(),this._channelSubs.forEach(e=>e.unsubscribe()),this._channelSubs.length=0}enable(){super.enable(),this._channelSubs=this._channelSubs||[],!(this._channelSubs.length>0)&&(this.subscribeToChannel("undici:request:create",this.onRequestCreated.bind(this)),this.subscribeToChannel("undici:client:sendHeaders",this.onRequestHeaders.bind(this)),this.subscribeToChannel("undici:request:headers",this.onResponseHeaders.bind(this)),this.subscribeToChannel("undici:request:trailers",this.onDone.bind(this)),this.subscribeToChannel("undici:request:error",this.onError.bind(this)))}_updateMetricInstruments(){this._httpClientDurationHistogram=this.meter.createHistogram("http.client.request.duration",{description:"Measures the duration of outbound HTTP requests.",unit:"s",valueType:kn.ValueType.DOUBLE,advice:{explicitBucketBoundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]}})}subscribeToChannel(e,n){var r;let[o,s]=process.version.replace("v","").split(".").map(c=>Number(c)),i=o>18||o===18&&s>=19,a;if(i)(r=qd.subscribe)===null||r===void 0||r.call(qd,e,n),a=()=>{var c;return(c=qd.unsubscribe)===null||c===void 0?void 0:c.call(qd,e,n)};else{let c=qd.channel(e);c.subscribe(n),a=()=>c.unsubscribe(n)}this._channelSubs.push({name:e,unsubscribe:a})}onRequestCreated({request:e}){let n=this.getConfig(),r=n.enabled!==!1;if((0,Yd.safeExecuteInTheMiddle)(()=>{var y;return!r||e.method==="CONNECT"||((y=n.ignoreRequestHook)===null||y===void 0?void 0:y.call(n,e))},y=>y&&this._diag.error("caught ignoreRequestHook error: ",y),!0))return;let s=(0,xS.hrTime)(),i;try{i=new $ke.URL(e.path,e.origin)}catch(y){this._diag.warn("could not determine url.full:",y);return}let a=i.protocol.replace(":",""),c=this.getRequestMethod(e.method),u={[gt.SemanticAttributes.HTTP_REQUEST_METHOD]:c,[gt.SemanticAttributes.HTTP_REQUEST_METHOD_ORIGINAL]:e.method,[gt.SemanticAttributes.URL_FULL]:i.toString(),[gt.SemanticAttributes.URL_PATH]:i.pathname,[gt.SemanticAttributes.URL_QUERY]:i.search,[gt.SemanticAttributes.URL_SCHEME]:a},l={https:"443",http:"80"},d=i.hostname,p=i.port||l[a];u[gt.SemanticAttributes.SERVER_ADDRESS]=d,p&&!isNaN(Number(p))&&(u[gt.SemanticAttributes.SERVER_PORT]=Number(p));let _;if(Array.isArray(e.headers)){let y=e.headers.findIndex(M=>M.toLowerCase()==="user-agent");y>=0&&(_=e.headers[y+1])}else if(typeof e.headers=="string"){let M=e.headers.split(`\r
7
- `).find(I=>I.toLowerCase().startsWith("user-agent"));_=M&&M.substring(M.indexOf(":")+1).trim()}_&&(u[gt.SemanticAttributes.USER_AGENT_ORIGINAL]=_);let f=(0,Yd.safeExecuteInTheMiddle)(()=>{var y;return(y=n.startSpanHook)===null||y===void 0?void 0:y.call(n,e)},y=>y&&this._diag.error("caught startSpanHook error: ",y),!0);f&&Object.entries(f).forEach(([y,M])=>{u[y]=M});let E=kn.context.active(),S=kn.trace.getSpan(E),h;n.requireParentforSpans&&(!S||!kn.trace.isSpanContextValid(S.spanContext()))?h=kn.trace.wrapSpanContext(kn.INVALID_SPAN_CONTEXT):h=this.tracer.startSpan(c==="_OTHER"?"HTTP":c,{kind:kn.SpanKind.CLIENT,attributes:u},E),(0,Yd.safeExecuteInTheMiddle)(()=>{var y;return(y=n.requestHook)===null||y===void 0?void 0:y.call(n,h,e)},y=>y&&this._diag.error("caught requestHook error: ",y),!0);let R=kn.trace.setSpan(kn.context.active(),h),A={};kn.propagation.inject(R,A);let O=Object.entries(A);for(let y=0;y<O.length;y++){let[M,I]=O[y];typeof e.addHeader=="function"?e.addHeader(M,I):typeof e.headers=="string"?e.headers+=`${M}: ${I}\r
8
- `:Array.isArray(e.headers)&&e.headers.push(M,I)}this._recordFromReq.set(e,{span:h,attributes:u,startTime:s})}onRequestHeaders({request:e,socket:n}){var r;let o=this._recordFromReq.get(e);if(!o)return;let s=this.getConfig(),{span:i}=o,{remoteAddress:a,remotePort:c}=n,u={[gt.SemanticAttributes.NETWORK_PEER_ADDRESS]:a,[gt.SemanticAttributes.NETWORK_PEER_PORT]:c};if(!((r=s.headersToSpanAttributes)===null||r===void 0)&&r.requestHeaders){let l=new Set(s.headersToSpanAttributes.requestHeaders.map(p=>p.toLowerCase())),d=Array.isArray(e.headers)?e.headers:e.headers.split(`\r
9
- `);d.forEach((p,_)=>{let f=p.indexOf(":"),E=f!==-1,S=(E?p.substring(0,f):p).toLowerCase(),h=E?p.substring(f+1):d[_+1];l.has(S)&&(u[`http.request.header.${S}`]=h.trim())})}i.setAttributes(u)}onResponseHeaders({request:e,response:n}){var r,o;let s=this._recordFromReq.get(e);if(!s)return;let{span:i,attributes:a}=s,c={[gt.SemanticAttributes.HTTP_RESPONSE_STATUS_CODE]:n.statusCode},u=this.getConfig();(0,Yd.safeExecuteInTheMiddle)(()=>{var d;return(d=u.responseHook)===null||d===void 0?void 0:d.call(u,i,{request:e,response:n})},d=>d&&this._diag.error("caught responseHook error: ",d),!0);let l=new Set;!((r=u.headersToSpanAttributes)===null||r===void 0)&&r.responseHeaders&&((o=u.headersToSpanAttributes)===null||o===void 0||o.responseHeaders.forEach(d=>l.add(d.toLowerCase())));for(let d=0;d<n.headers.length;d=d+2){let p=n.headers[d].toString().toLowerCase(),_=n.headers[d+1];if(l.has(p)&&(c[`http.response.header.${p}`]=_.toString()),p==="content-length"){let f=Number(_.toString());isNaN(f)||(c["http.response.header.content-length"]=f)}}i.setAttributes(c),i.setStatus({code:n.statusCode>=400?kn.SpanStatusCode.ERROR:kn.SpanStatusCode.UNSET}),s.attributes=Object.assign(a,c)}onDone({request:e}){let n=this._recordFromReq.get(e);if(!n)return;let{span:r,attributes:o,startTime:s}=n;r.end(),this._recordFromReq.delete(e),this.recordRequestDuration(o,s)}onError({request:e,error:n}){let r=this._recordFromReq.get(e);if(!r)return;let{span:o,attributes:s,startTime:i}=r;o.recordException(n),o.setStatus({code:kn.SpanStatusCode.ERROR,message:n.message}),o.end(),this._recordFromReq.delete(e),s[gt.SemanticAttributes.ERROR_TYPE]=n.message,this.recordRequestDuration(s,i)}recordRequestDuration(e,n){let r={};[gt.SemanticAttributes.HTTP_RESPONSE_STATUS_CODE,gt.SemanticAttributes.HTTP_REQUEST_METHOD,gt.SemanticAttributes.SERVER_ADDRESS,gt.SemanticAttributes.SERVER_PORT,gt.SemanticAttributes.URL_SCHEME,gt.SemanticAttributes.ERROR_TYPE].forEach(i=>{i in e&&(r[i]=e[i])});let s=(0,xS.hrTimeToMilliseconds)((0,xS.hrTimeDuration)(n,(0,xS.hrTime)()))/1e3;this._httpClientDurationHistogram.record(s,r)}getRequestMethod(e){let n={CONNECT:!0,OPTIONS:!0,HEAD:!0,GET:!0,POST:!0,PUT:!0,PATCH:!0,DELETE:!0,TRACE:!0};return e.toUpperCase()in n?e.toUpperCase():"_OTHER"}};DS.UndiciInstrumentation=eC});var Hz=m(Gz=>{"use strict";Object.defineProperty(Gz,"__esModule",{value:!0})});var Fz=m(zs=>{"use strict";var Fke=zs&&zs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$z=zs&&zs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Fke(e,t,n)};Object.defineProperty(zs,"__esModule",{value:!0});$z(Bz(),zs);$z(Hz(),zs)});var US=m(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});Kd.ExpressLayerType=void 0;var Xke;(function(t){t.ROUTER="router",t.MIDDLEWARE="middleware",t.REQUEST_HANDLER="request_handler"})(Xke=Kd.ExpressLayerType||(Kd.ExpressLayerType={}))});var wS=m(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});Wd.AttributeNames=void 0;var Jke;(function(t){t.EXPRESS_TYPE="express.type",t.EXPRESS_NAME="express.name"})(Jke=Wd.AttributeNames||(Wd.AttributeNames={}))});var tC=m(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu._LAYERS_STORE_PROPERTY=gu.kLayerPatched=void 0;gu.kLayerPatched=Symbol("express-layer-patched");gu._LAYERS_STORE_PROPERTY="__ot_middlewares"});var Wz=m(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getLayerPath=Zt.asErrorAndMessage=Zt.isLayerIgnored=Zt.getLayerMetadata=Zt.getRouterPath=Zt.storeLayerPath=void 0;var nC=US(),hu=wS(),rC=tC(),Zke=(t,e)=>{Array.isArray(t[rC._LAYERS_STORE_PROPERTY])===!1&&Object.defineProperty(t,rC._LAYERS_STORE_PROPERTY,{enumerable:!1,value:[]}),e!==void 0&&t[rC._LAYERS_STORE_PROPERTY].push(e)};Zt.storeLayerPath=Zke;var Qke=(t,e)=>{var n,r,o,s;let i=(r=(n=e.handle)===null||n===void 0?void 0:n.stack)===null||r===void 0?void 0:r[0];return!((o=i?.route)===null||o===void 0)&&o.path?`${t}${i.route.path}`:!((s=i?.handle)===null||s===void 0)&&s.stack?(0,Zt.getRouterPath)(t,i):t};Zt.getRouterPath=Qke;var eVe=(t,e,n)=>{var r;if(e.name==="router"){let o=(0,Zt.getRouterPath)("",e),s=o||n||t||"/";return{attributes:{[hu.AttributeNames.EXPRESS_NAME]:s,[hu.AttributeNames.EXPRESS_TYPE]:nC.ExpressLayerType.ROUTER},name:`router - ${s}`}}else return e.name==="bound dispatch"?{attributes:{[hu.AttributeNames.EXPRESS_NAME]:(r=t||n)!==null&&r!==void 0?r:"request handler",[hu.AttributeNames.EXPRESS_TYPE]:nC.ExpressLayerType.REQUEST_HANDLER},name:`request handler${e.path?` - ${t||n}`:""}`}:{attributes:{[hu.AttributeNames.EXPRESS_NAME]:e.name,[hu.AttributeNames.EXPRESS_TYPE]:nC.ExpressLayerType.MIDDLEWARE},name:`middleware - ${e.name}`}};Zt.getLayerMetadata=eVe;var tVe=(t,e)=>{if(typeof e=="string")return e===t;if(e instanceof RegExp)return e.test(t);if(typeof e=="function")return e(t);throw new TypeError("Pattern is in unsupported datatype")},nVe=(t,e,n)=>{var r;if(Array.isArray(n?.ignoreLayersType)&&(!((r=n?.ignoreLayersType)===null||r===void 0)&&r.includes(e)))return!0;if(Array.isArray(n?.ignoreLayers)===!1)return!1;try{for(let o of n.ignoreLayers)if(tVe(t,o))return!0}catch{}return!1};Zt.isLayerIgnored=nVe;var rVe=t=>t instanceof Error?[t,t.message]:[String(t),String(t)];Zt.asErrorAndMessage=rVe;var oVe=t=>{let e=t[0];return Array.isArray(e)?e.map(n=>Kz(n)||"").join(","):Kz(e)};Zt.getLayerPath=oVe;var Kz=t=>{if(typeof t=="string")return t;if(t instanceof RegExp||typeof t=="number")return t.toString()}});var zz=m(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.PACKAGE_NAME=Tu.PACKAGE_VERSION=void 0;Tu.PACKAGE_VERSION="0.47.1";Tu.PACKAGE_NAME="@opentelemetry/instrumentation-express"});var eX=m(kS=>{"use strict";Object.defineProperty(kS,"__esModule",{value:!0});kS.ExpressInstrumentation=void 0;var Xz=Se(),Na=(x(),b(B)),Jz=US(),Zz=wS(),Xs=Wz(),Qz=zz(),Au=fe(),sVe=(ve(),b(ot)),zd=tC(),oC=class extends Au.InstrumentationBase{constructor(e={}){super(Qz.PACKAGE_NAME,Qz.PACKAGE_VERSION,e)}init(){return[new Au.InstrumentationNodeModuleDefinition("express",[">=4.0.0 <5"],e=>{let n=e.Router;return(0,Au.isWrapped)(n.route)&&this._unwrap(n,"route"),this._wrap(n,"route",this._getRoutePatch()),(0,Au.isWrapped)(n.use)&&this._unwrap(n,"use"),this._wrap(n,"use",this._getRouterUsePatch()),(0,Au.isWrapped)(e.application.use)&&this._unwrap(e.application,"use"),this._wrap(e.application,"use",this._getAppUsePatch()),e},e=>{if(e===void 0)return;let n=e.Router;this._unwrap(n,"route"),this._unwrap(n,"use"),this._unwrap(e.application,"use")})]}_getRoutePatch(){let e=this;return function(n){return function(...o){let s=n.apply(this,o),i=this.stack[this.stack.length-1];return e._applyPatch(i,(0,Xs.getLayerPath)(o)),s}}}_getRouterUsePatch(){let e=this;return function(n){return function(...o){let s=n.apply(this,o),i=this.stack[this.stack.length-1];return e._applyPatch(i,(0,Xs.getLayerPath)(o)),s}}}_getAppUsePatch(){let e=this;return function(n){return function(...o){let s=n.apply(this,o),i=this._router.stack[this._router.stack.length-1];return e._applyPatch(i,(0,Xs.getLayerPath)(o)),s}}}_applyPatch(e,n){let r=this;e[zd.kLayerPatched]!==!0&&(e[zd.kLayerPatched]=!0,this._wrap(e,"handle",o=>{if(o.length===4)return o;let s=function(i,a){(0,Xs.storeLayerPath)(i,n);let c=i[zd._LAYERS_STORE_PROPERTY].filter(O=>O!=="/"&&O!=="/*").join("").replace(/\/{2,}/g,"/"),u={[sVe.SEMATTRS_HTTP_ROUTE]:c.length>0?c:"/"},l=(0,Xs.getLayerMetadata)(c,e,n),d=l.attributes[Zz.AttributeNames.EXPRESS_TYPE],p=(0,Xz.getRPCMetadata)(Na.context.active());if(p?.type===Xz.RPCType.HTTP&&(p.route=c||"/"),(0,Xs.isLayerIgnored)(l.name,d,r.getConfig()))return d===Jz.ExpressLayerType.MIDDLEWARE&&i[zd._LAYERS_STORE_PROPERTY].pop(),o.apply(this,arguments);if(Na.trace.getSpan(Na.context.active())===void 0)return o.apply(this,arguments);let _=r._getSpanName({request:i,layerType:d,route:c},l.name),f=r.tracer.startSpan(_,{attributes:Object.assign(u,l.attributes)}),{requestHook:E}=r.getConfig();E&&(0,Au.safeExecuteInTheMiddle)(()=>E(f,{request:i,layerType:d,route:c}),O=>{O&&Na.diag.error("express instrumentation: request hook failed",O)},!0);let S=!1;l.attributes[Zz.AttributeNames.EXPRESS_TYPE]!==Jz.ExpressLayerType.MIDDLEWARE&&(f.end(),S=!0);let h=()=>{S===!1&&(S=!0,f.end())},R=Array.from(arguments),A=R.findIndex(O=>typeof O=="function");A>=0&&(arguments[A]=function(){var O;let y=arguments[0],M=![void 0,null,"route","router"].includes(y);if(!S&&M){let[J,H]=(0,Xs.asErrorAndMessage)(y);f.recordException(J),f.setStatus({code:Na.SpanStatusCode.ERROR,message:H})}return S===!1&&(S=!0,(O=i.res)===null||O===void 0||O.removeListener("finish",h),f.end()),i.route&&M||i[zd._LAYERS_STORE_PROPERTY].pop(),R[A].apply(this,arguments)});try{return o.apply(this,arguments)}catch(O){let[y,M]=(0,Xs.asErrorAndMessage)(O);throw f.recordException(y),f.setStatus({code:Na.SpanStatusCode.ERROR,message:M}),O}finally{S||a.once("finish",h)}};for(let i in o)Object.defineProperty(s,i,{get(){return o[i]},set(a){o[i]=a}});return s}))}_getSpanName(e,n){var r;let{spanNameHook:o}=this.getConfig();if(!(o instanceof Function))return n;try{return(r=o(e,n))!==null&&r!==void 0?r:n}catch(s){return Na.diag.error("express instrumentation: error calling span name rewrite hook",s),n}}};kS.ExpressInstrumentation=oC});var nX=m(tX=>{"use strict";Object.defineProperty(tX,"__esModule",{value:!0})});var rX=m(po=>{"use strict";var iVe=po&&po.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),VS=po&&po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iVe(e,t,n)};Object.defineProperty(po,"__esModule",{value:!0});VS(eX(),po);VS(US(),po);VS(wS(),po);VS(nX(),po)});var hX=m((tnt,gX)=>{"use strict";gX.exports=EX;function EX(t,e,n){t instanceof RegExp&&(t=mX(t,n)),e instanceof RegExp&&(e=mX(e,n));var r=SX(t,e,n);return r&&{start:r[0],end:r[1],pre:n.slice(0,r[0]),body:n.slice(r[0]+t.length,r[1]),post:n.slice(r[1]+e.length)}}function mX(t,e){var n=e.match(t);return n?n[0]:null}EX.range=SX;function SX(t,e,n){var r,o,s,i,a,c=n.indexOf(t),u=n.indexOf(e,c+1),l=c;if(c>=0&&u>0){if(t===e)return[c,u];for(r=[],s=n.length;l>=0&&!a;)l==c?(r.push(l),c=n.indexOf(t,l+1)):r.length==1?a=[r.pop(),u]:(o=r.pop(),o<s&&(s=o,i=u),u=n.indexOf(e,l+1)),l=c<u&&c>=0?c:u;r.length&&(a=[s,i])}return a}});var vX=m((nnt,CX)=>{var TX=hX();CX.exports=fVe;var AX="\0SLASH"+Math.random()+"\0",RX="\0OPEN"+Math.random()+"\0",lC="\0CLOSE"+Math.random()+"\0",yX="\0COMMA"+Math.random()+"\0",OX="\0PERIOD"+Math.random()+"\0";function uC(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function pVe(t){return t.split("\\\\").join(AX).split("\\{").join(RX).split("\\}").join(lC).split("\\,").join(yX).split("\\.").join(OX)}function _Ve(t){return t.split(AX).join("\\").split(RX).join("{").split(lC).join("}").split(yX).join(",").split(OX).join(".")}function NX(t){if(!t)return[""];var e=[],n=TX("{","}",t);if(!n)return t.split(",");var r=n.pre,o=n.body,s=n.post,i=r.split(",");i[i.length-1]+="{"+o+"}";var a=NX(s);return s.length&&(i[i.length-1]+=a.shift(),i.push.apply(i,a)),e.push.apply(e,i),e}function fVe(t,e){if(!t)return[];e=e||{};var n=e.max==null?1/0:e.max;return t.substr(0,2)==="{}"&&(t="\\{\\}"+t.substr(2)),Xd(pVe(t),n,!0).map(_Ve)}function mVe(t){return"{"+t+"}"}function EVe(t){return/^-?0\d/.test(t)}function SVe(t,e){return t<=e}function gVe(t,e){return t>=e}function Xd(t,e,n){var r=[],o=TX("{","}",t);if(!o)return[t];var s=o.pre,i=o.post.length?Xd(o.post,e,!1):[""];if(/\$$/.test(o.pre))for(var a=0;a<i.length&&a<e;a++){var c=s+"{"+o.body+"}"+i[a];r.push(c)}else{var u=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(o.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(o.body),d=u||l,p=o.body.indexOf(",")>=0;if(!d&&!p)return o.post.match(/,(?!,).*\}/)?(t=o.pre+"{"+o.body+lC+o.post,Xd(t,e,!0)):[t];var _;if(d)_=o.body.split(/\.\./);else if(_=NX(o.body),_.length===1&&(_=Xd(_[0],e,!1).map(mVe),_.length===1))return i.map(function(G){return o.pre+_[0]+G});var f;if(d){var E=uC(_[0]),S=uC(_[1]),h=Math.max(_[0].length,_[1].length),R=_.length==3?Math.max(Math.abs(uC(_[2])),1):1,A=SVe,O=S<E;O&&(R*=-1,A=gVe);var y=_.some(EVe);f=[];for(var M=E;A(M,S);M+=R){var I;if(l)I=String.fromCharCode(M),I==="\\"&&(I="");else if(I=String(M),y){var J=h-I.length;if(J>0){var H=new Array(J+1).join("0");M<0?I="-"+H+I.slice(1):I=H+I}}f.push(I)}}else{f=[];for(var me=0;me<_.length;me++)f.push.apply(f,Xd(_[me],e,!1))}for(var me=0;me<f.length;me++)for(var a=0;a<i.length&&r.length<e;a++){var c=s+f[me]+i[a];(!n||d||c)&&r.push(c)}}return r}});var SC=m(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.SpanNames=Lr.TokenKind=Lr.AllowedOperationTypes=void 0;var SBe;(function(t){t.QUERY="query",t.MUTATION="mutation",t.SUBSCRIPTION="subscription"})(SBe=Lr.AllowedOperationTypes||(Lr.AllowedOperationTypes={}));var gBe;(function(t){t.SOF="<SOF>",t.EOF="<EOF>",t.BANG="!",t.DOLLAR="$",t.AMP="&",t.PAREN_L="(",t.PAREN_R=")",t.SPREAD="...",t.COLON=":",t.EQUALS="=",t.AT="@",t.BRACKET_L="[",t.BRACKET_R="]",t.BRACE_L="{",t.PIPE="|",t.BRACE_R="}",t.NAME="Name",t.INT="Int",t.FLOAT="Float",t.STRING="String",t.BLOCK_STRING="BlockString",t.COMMENT="Comment"})(gBe=Lr.TokenKind||(Lr.TokenKind={}));var hBe;(function(t){t.EXECUTE="graphql.execute",t.PARSE="graphql.parse",t.RESOLVE="graphql.resolve",t.VALIDATE="graphql.validate",t.SCHEMA_VALIDATE="graphql.validateSchema",t.SCHEMA_PARSE="graphql.parseSchema"})(hBe=Lr.SpanNames||(Lr.SpanNames={}))});var gC=m(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});rp.AttributeNames=void 0;var TBe;(function(t){t.SOURCE="graphql.source",t.FIELD_NAME="graphql.field.name",t.FIELD_PATH="graphql.field.path",t.FIELD_TYPE="graphql.field.type",t.OPERATION_TYPE="graphql.operation.type",t.OPERATION_NAME="graphql.operation.name",t.VARIABLES="graphql.variables.",t.ERROR_VALIDATION_NAME="graphql.validation.error"})(TBe=rp.AttributeNames||(rp.AttributeNames={}))});var zS=m(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.OTEL_GRAPHQL_DATA_SYMBOL=yu.OTEL_PATCHED_SYMBOL=void 0;yu.OTEL_PATCHED_SYMBOL=Symbol.for("opentelemetry.patched");yu.OTEL_GRAPHQL_DATA_SYMBOL=Symbol.for("opentelemetry.graphql_data")});var r9=m(XS=>{"use strict";Object.defineProperty(XS,"__esModule",{value:!0});XS.OPERATION_NOT_SUPPORTED=void 0;var $nt=zS();XS.OPERATION_NOT_SUPPORTED="Operation$operationName$not supported"});var m9=m(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.wrapFieldResolver=ht.wrapFields=ht.getSourceFromLocation=ht.getOperation=ht.endSpan=ht.addSpanSource=ht.addInputVariableAttributes=ht.isPromise=void 0;var Nu=(x(),b(B)),ti=SC(),Ou=gC(),Wo=zS(),o9=Object.values(ti.AllowedOperationTypes),ABe=t=>typeof t?.then=="function";ht.isPromise=ABe;var RBe=t=>typeof t=="object"&&t!==null;function hC(t,e,n){Array.isArray(n)?n.forEach((r,o)=>{hC(t,`${e}.${o}`,r)}):n instanceof Object?Object.entries(n).forEach(([r,o])=>{hC(t,`${e}.${r}`,o)}):t.setAttribute(`${Ou.AttributeNames.VARIABLES}${String(e)}`,n)}function yBe(t,e){Object.entries(e).forEach(([n,r])=>{hC(t,n,r)})}ht.addInputVariableAttributes=yBe;function c9(t,e,n,r,o){let s=p9(e,n,r,o);t.setAttribute(Ou.AttributeNames.SOURCE,s)}ht.addSpanSource=c9;function OBe(t,e,n,r,o){let s=u9(n,o),i=!1;if(!s){i=!0;let a=l9(n,o);s={parent:a,span:NBe(t,e,n,r,o,a.span),error:null},IBe(n,o,s)}return{spanAdded:i,field:s}}function NBe(t,e,n,r,o,s){var i,a;let c={[Ou.AttributeNames.FIELD_NAME]:r.fieldName,[Ou.AttributeNames.FIELD_PATH]:o.join("."),[Ou.AttributeNames.FIELD_TYPE]:r.returnType.toString()},u=t.startSpan(`${ti.SpanNames.RESOLVE} ${c[Ou.AttributeNames.FIELD_PATH]}`,{attributes:c},s?Nu.trace.setSpan(Nu.context.active(),s):void 0),l=n[Wo.OTEL_GRAPHQL_DATA_SYMBOL].source,d=r.fieldNodes.find(p=>p.kind==="Field");return d&&c9(u,l.loc,e().allowValues,(i=d.loc)===null||i===void 0?void 0:i.start,(a=d.loc)===null||a===void 0?void 0:a.end),u}function CBe(t,e){e&&t.recordException(e),t.end()}ht.endSpan=CBe;function vBe(t,e){if(!(!t||!Array.isArray(t.definitions)))return e?t.definitions.filter(n=>{var r;return o9.indexOf((r=n)===null||r===void 0?void 0:r.operation)!==-1}).find(n=>{var r,o;return e===((o=(r=n)===null||r===void 0?void 0:r.name)===null||o===void 0?void 0:o.value)}):t.definitions.find(n=>{var r;return o9.indexOf((r=n)===null||r===void 0?void 0:r.operation)!==-1})}ht.getOperation=vBe;function IBe(t,e,n){return t[Wo.OTEL_GRAPHQL_DATA_SYMBOL].fields[e.join(".")]=n}function u9(t,e){return t[Wo.OTEL_GRAPHQL_DATA_SYMBOL].fields[e.join(".")]}function l9(t,e){for(let n=e.length-1;n>0;n--){let r=u9(t,e.slice(0,n));if(r)return r}return{span:t[Wo.OTEL_GRAPHQL_DATA_SYMBOL].span}}function PBe(t,e){let n=[],r=e;for(;r;){let o=r.key;t&&typeof o=="number"&&(o="*"),n.push(String(o)),r=r.prev}return n.reverse()}function bBe(t){return d9(`
10
- `,t)}function s9(t){return d9(" ",t)}function d9(t,e){let n="";for(let r=0;r<e;r++)n+=t;return n}var MBe=[ti.TokenKind.FLOAT,ti.TokenKind.STRING,ti.TokenKind.INT,ti.TokenKind.BLOCK_STRING];function p9(t,e=!1,n,r){var o,s;let i="";if(t?.startToken){let a=typeof n=="number"?n:t.start,c=typeof r=="number"?r:t.end,u=t.startToken.next,l=1;for(;u;){if(u.start<a){u=u.next,l=u?.line;continue}if(u.end>c){u=u.next,l=u?.line;continue}let d=u.value||u.kind,p="";!e&&MBe.indexOf(u.kind)>=0&&(d="*"),u.kind===ti.TokenKind.STRING&&(d=`"${d}"`),u.kind===ti.TokenKind.EOF&&(d=""),u.line>l?(i+=bBe(u.line-l),l=u.line,p=s9(u.column-1)):u.line===((o=u.prev)===null||o===void 0?void 0:o.line)&&(p=s9(u.start-(((s=u.prev)===null||s===void 0?void 0:s.end)||0))),i+=p+d,u&&(u=u.next)}}return i}ht.getSourceFromLocation=p9;function _9(t,e,n){if(!t||typeof t.getFields!="function"||t[Wo.OTEL_PATCHED_SYMBOL])return;let r=t.getFields();t[Wo.OTEL_PATCHED_SYMBOL]=!0,Object.keys(r).forEach(o=>{let s=r[o];if(s&&(s.resolve&&(s.resolve=f9(e,n,s.resolve)),s.type)){let i=s.type;for(;i.ofType;)i=i.ofType;_9(i,e,n)}})}ht.wrapFields=_9;var i9=(t,e,n)=>{n&&(t.recordException(e),t.setStatus({code:Nu.SpanStatusCode.ERROR,message:e.message}),t.end())},a9=(t,e)=>{e&&t.end()};function f9(t,e,n,r=!1){if(o[Wo.OTEL_PATCHED_SYMBOL]||typeof n!="function")return n;function o(s,i,a,c){if(!n)return;let u=e();if(u.ignoreTrivialResolveSpans&&r&&(RBe(s)||typeof s=="function")&&typeof s[c.fieldName]!="function")return n.call(this,s,i,a,c);if(!a[Wo.OTEL_GRAPHQL_DATA_SYMBOL])return n.call(this,s,i,a,c);let l=PBe(u.mergeItems,c&&c.path),d=l.filter(f=>typeof f=="string").length,p,_=!1;if(u.depth>=0&&u.depth<d)p=l9(a,l);else{let f=OBe(t,e,a,c,l);p=f.field,_=f.spanAdded}return Nu.context.with(Nu.trace.setSpan(Nu.context.active(),p.span),()=>{try{let f=n.call(this,s,i,a,c);return(0,ht.isPromise)(f)?f.then(E=>(a9(p.span,_),E),E=>{throw i9(p.span,E,_),E}):(a9(p.span,_),f)}catch(f){throw i9(p.span,f,_),f}})}return o[Wo.OTEL_PATCHED_SYMBOL]=!0,o}ht.wrapFieldResolver=f9});var E9=m(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});Cu.PACKAGE_NAME=Cu.PACKAGE_VERSION=void 0;Cu.PACKAGE_VERSION="0.47.1";Cu.PACKAGE_NAME="@opentelemetry/instrumentation-graphql"});var h9=m(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0});QS.GraphQLInstrumentation=void 0;var zo=(x(),b(B)),ar=fe(),op=SC(),JS=gC(),TC=zS(),LBe=r9(),en=m9(),S9=E9(),g9={mergeItems:!1,depth:-1,allowValues:!1,ignoreResolveSpans:!1},ZS=[">=14.0.0 <17"],AC=class extends ar.InstrumentationBase{constructor(e={}){super(S9.PACKAGE_NAME,S9.PACKAGE_VERSION,Object.assign(Object.assign({},g9),e))}setConfig(e={}){super.setConfig(Object.assign(Object.assign({},g9),e))}init(){let e=new ar.InstrumentationNodeModuleDefinition("graphql",ZS);return e.files.push(this._addPatchingExecute()),e.files.push(this._addPatchingParser()),e.files.push(this._addPatchingValidate()),e}_addPatchingExecute(){return new ar.InstrumentationNodeModuleFile("graphql/execution/execute.js",ZS,e=>((0,ar.isWrapped)(e.execute)&&this._unwrap(e,"execute"),this._wrap(e,"execute",this._patchExecute(e.defaultFieldResolver)),e),e=>{e&&this._unwrap(e,"execute")})}_addPatchingParser(){return new ar.InstrumentationNodeModuleFile("graphql/language/parser.js",ZS,e=>((0,ar.isWrapped)(e.parse)&&this._unwrap(e,"parse"),this._wrap(e,"parse",this._patchParse()),e),e=>{e&&this._unwrap(e,"parse")})}_addPatchingValidate(){return new ar.InstrumentationNodeModuleFile("graphql/validation/validate.js",ZS,e=>((0,ar.isWrapped)(e.validate)&&this._unwrap(e,"validate"),this._wrap(e,"validate",this._patchValidate()),e),e=>{e&&this._unwrap(e,"validate")})}_patchExecute(e){let n=this;return function(o){return function(){let i;if(arguments.length>=2){let u=arguments;i=n._wrapExecuteArgs(u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],e)}else{let u=arguments[0];i=n._wrapExecuteArgs(u.schema,u.document,u.rootValue,u.contextValue,u.variableValues,u.operationName,u.fieldResolver,u.typeResolver,e)}let a=(0,en.getOperation)(i.document,i.operationName),c=n._createExecuteSpan(a,i);return i.contextValue[TC.OTEL_GRAPHQL_DATA_SYMBOL]={source:i.document?i.document||i.document[TC.OTEL_GRAPHQL_DATA_SYMBOL]:void 0,span:c,fields:{}},zo.context.with(zo.trace.setSpan(zo.context.active(),c),()=>(0,ar.safeExecuteInTheMiddle)(()=>o.apply(this,[i]),(u,l)=>{n._handleExecutionResult(c,u,l)}))}}}_handleExecutionResult(e,n,r){let o=this.getConfig();if(r===void 0||n){(0,en.endSpan)(e,n);return}if((0,en.isPromise)(r))r.then(s=>{if(typeof o.responseHook!="function"){(0,en.endSpan)(e);return}this._executeResponseHook(e,s)},s=>{(0,en.endSpan)(e,s)});else{if(typeof o.responseHook!="function"){(0,en.endSpan)(e);return}this._executeResponseHook(e,r)}}_executeResponseHook(e,n){let{responseHook:r}=this.getConfig();r&&(0,ar.safeExecuteInTheMiddle)(()=>{r(e,n)},o=>{o&&this._diag.error("Error running response hook",o),(0,en.endSpan)(e,void 0)},!0)}_patchParse(){let e=this;return function(r){return function(s,i){return e._parse(this,r,s,i)}}}_patchValidate(){let e=this;return function(r){return function(s,i,a,c,u){return e._validate(this,r,s,i,a,u,c)}}}_parse(e,n,r,o){let s=this.getConfig(),i=this.tracer.startSpan(op.SpanNames.PARSE);return zo.context.with(zo.trace.setSpan(zo.context.active(),i),()=>(0,ar.safeExecuteInTheMiddle)(()=>n.call(e,r,o),(a,c)=>{c&&((0,en.getOperation)(c)?c.loc&&(0,en.addSpanSource)(i,c.loc,s.allowValues):i.updateName(op.SpanNames.SCHEMA_PARSE)),(0,en.endSpan)(i,a)}))}_validate(e,n,r,o,s,i,a){let c=this.tracer.startSpan(op.SpanNames.VALIDATE,{});return zo.context.with(zo.trace.setSpan(zo.context.active(),c),()=>(0,ar.safeExecuteInTheMiddle)(()=>n.call(e,r,o,s,a,i),(u,l)=>{o.loc||c.updateName(op.SpanNames.SCHEMA_VALIDATE),l&&l.length&&c.recordException({name:JS.AttributeNames.ERROR_VALIDATION_NAME,message:JSON.stringify(l)}),(0,en.endSpan)(c,u)}))}_createExecuteSpan(e,n){var r;let o=this.getConfig(),s=this.tracer.startSpan(op.SpanNames.EXECUTE,{});if(e){let{operation:i,name:a}=e;s.setAttribute(JS.AttributeNames.OPERATION_TYPE,i);let c=a?.value;c?(s.setAttribute(JS.AttributeNames.OPERATION_NAME,c),s.updateName(`${i} ${c}`)):s.updateName(i)}else{let i=" ";n.operationName&&(i=` "${n.operationName}" `),i=LBe.OPERATION_NOT_SUPPORTED.replace("$operationName$",i),s.setAttribute(JS.AttributeNames.OPERATION_NAME,i)}return!((r=n.document)===null||r===void 0)&&r.loc&&(0,en.addSpanSource)(s,n.document.loc,o.allowValues),n.variableValues&&o.allowValues&&(0,en.addInputVariableAttributes)(s,n.variableValues),s}_wrapExecuteArgs(e,n,r,o,s,i,a,c,u){if(o||(o={}),o[TC.OTEL_GRAPHQL_DATA_SYMBOL]||this.getConfig().ignoreResolveSpans)return{schema:e,document:n,rootValue:r,contextValue:o,variableValues:s,operationName:i,fieldResolver:a,typeResolver:c};let l=a==null,d=a??u;return a=(0,en.wrapFieldResolver)(this.tracer,()=>this.getConfig(),d,l),e&&((0,en.wrapFields)(e.getQueryType(),this.tracer,()=>this.getConfig()),(0,en.wrapFields)(e.getMutationType(),this.tracer,()=>this.getConfig())),{schema:e,document:n,rootValue:r,contextValue:o,variableValues:s,operationName:i,fieldResolver:a,typeResolver:c}}};QS.GraphQLInstrumentation=AC});var A9=m(T9=>{"use strict";Object.defineProperty(T9,"__esModule",{value:!0})});var y9=m(ni=>{"use strict";var xBe=ni&&ni.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),R9=ni&&ni.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xBe(e,t,n)};Object.defineProperty(ni,"__esModule",{value:!0});R9(h9(),ni);R9(A9(),ni)});var P9=m(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.PACKAGE_NAME=vu.PACKAGE_VERSION=void 0;vu.PACKAGE_VERSION="0.7.1";vu.PACKAGE_NAME="@opentelemetry/instrumentation-kafkajs"});var b9=m(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});eg.bufferTextMapGetter=void 0;eg.bufferTextMapGetter={get(t,e){var n;if(!t)return;let r=Object.keys(t);for(let o of r)if(o===e||o.toLowerCase()===e)return(n=t[o])===null||n===void 0?void 0:n.toString()},keys(t){return t?Object.keys(t):[]}}});var x9=m(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});tg.KafkaJsInstrumentation=void 0;var kt=(x(),b(B)),ri=(ve(),b(ot)),M9=P9(),L9=b9(),xr=fe(),RC=class extends xr.InstrumentationBase{constructor(e={}){super(M9.PACKAGE_NAME,M9.PACKAGE_VERSION,e)}init(){let e=r=>{var o,s;(0,xr.isWrapped)((o=r?.Kafka)===null||o===void 0?void 0:o.prototype.producer)&&this._unwrap(r.Kafka.prototype,"producer"),(0,xr.isWrapped)((s=r?.Kafka)===null||s===void 0?void 0:s.prototype.consumer)&&this._unwrap(r.Kafka.prototype,"consumer")};return new xr.InstrumentationNodeModuleDefinition("kafkajs",[">=0.1.0 <3"],r=>{var o,s;return e(r),this._wrap((o=r?.Kafka)===null||o===void 0?void 0:o.prototype,"producer",this._getProducerPatch()),this._wrap((s=r?.Kafka)===null||s===void 0?void 0:s.prototype,"consumer",this._getConsumerPatch()),r},e)}_getConsumerPatch(){let e=this;return n=>function(...o){let s=n.apply(this,o);return(0,xr.isWrapped)(s.run)&&e._unwrap(s,"run"),e._wrap(s,"run",e._getConsumerRunPatch()),s}}_getProducerPatch(){let e=this;return n=>function(...o){let s=n.apply(this,o);return(0,xr.isWrapped)(s.sendBatch)&&e._unwrap(s,"sendBatch"),e._wrap(s,"sendBatch",e._getProducerSendBatchPatch()),(0,xr.isWrapped)(s.send)&&e._unwrap(s,"send"),e._wrap(s,"send",e._getProducerSendPatch()),s}}_getConsumerRunPatch(){let e=this;return n=>function(...o){let s=o[0];return s?.eachMessage&&((0,xr.isWrapped)(s.eachMessage)&&e._unwrap(s,"eachMessage"),e._wrap(s,"eachMessage",e._getConsumerEachMessagePatch())),s?.eachBatch&&((0,xr.isWrapped)(s.eachBatch)&&e._unwrap(s,"eachBatch"),e._wrap(s,"eachBatch",e._getConsumerEachBatchPatch())),n.call(this,s)}}_getConsumerEachMessagePatch(){let e=this;return n=>function(...o){let s=o[0],i=kt.propagation.extract(kt.ROOT_CONTEXT,s.message.headers,L9.bufferTextMapGetter),a=e._startConsumerSpan(s.topic,s.message,ri.MESSAGINGOPERATIONVALUES_PROCESS,i),c=kt.context.with(kt.trace.setSpan(i,a),()=>n.apply(this,o));return e._endSpansOnPromise([a],c)}}_getConsumerEachBatchPatch(){return e=>{let n=this;return function(...o){let s=o[0],i=n._startConsumerSpan(s.batch.topic,void 0,ri.MESSAGINGOPERATIONVALUES_RECEIVE,kt.ROOT_CONTEXT);return kt.context.with(kt.trace.setSpan(kt.context.active(),i),()=>{let a=s.batch.messages.map(u=>{var l;let d=kt.propagation.extract(kt.ROOT_CONTEXT,u.headers,L9.bufferTextMapGetter),p=(l=kt.trace.getSpan(d))===null||l===void 0?void 0:l.spanContext(),_;return p&&(_={context:p}),n._startConsumerSpan(s.batch.topic,u,ri.MESSAGINGOPERATIONVALUES_PROCESS,void 0,_)}),c=e.apply(this,o);return a.unshift(i),n._endSpansOnPromise(a,c)})}}}_getProducerSendBatchPatch(){let e=this;return n=>function(...o){let a=(o[0].topicMessages||[]).map(u=>u.messages.map(l=>e._startProducerSpan(u.topic,l))).reduce((u,l)=>u.concat(l),[]),c=n.apply(this,o);return e._endSpansOnPromise(a,c)}}_getProducerSendPatch(){let e=this;return n=>function(...o){let s=o[0],i=s.messages.map(c=>e._startProducerSpan(s.topic,c)),a=n.apply(this,o);return e._endSpansOnPromise(i,a)}}_endSpansOnPromise(e,n){return Promise.resolve(n).catch(r=>{let o;throw typeof r=="string"?o=r:typeof r=="object"&&Object.prototype.hasOwnProperty.call(r,"message")&&(o=r.message),e.forEach(s=>s.setStatus({code:kt.SpanStatusCode.ERROR,message:o})),r}).finally(()=>{e.forEach(r=>r.end())})}_startConsumerSpan(e,n,r,o,s){let i=this.tracer.startSpan(e,{kind:kt.SpanKind.CONSUMER,attributes:{[ri.SEMATTRS_MESSAGING_SYSTEM]:"kafka",[ri.SEMATTRS_MESSAGING_DESTINATION]:e,[ri.SEMATTRS_MESSAGING_OPERATION]:r},links:s?[s]:[]},o),{consumerHook:a}=this.getConfig();return a&&n&&(0,xr.safeExecuteInTheMiddle)(()=>a(i,{topic:e,message:n}),c=>{c&&this._diag.error("consumerHook error",c)},!0),i}_startProducerSpan(e,n){var r;let o=this.tracer.startSpan(e,{kind:kt.SpanKind.PRODUCER,attributes:{[ri.SEMATTRS_MESSAGING_SYSTEM]:"kafka",[ri.SEMATTRS_MESSAGING_DESTINATION]:e}});n.headers=(r=n.headers)!==null&&r!==void 0?r:{},kt.propagation.inject(kt.trace.setSpan(kt.context.active(),o),n.headers);let{producerHook:s}=this.getConfig();return s&&(0,xr.safeExecuteInTheMiddle)(()=>s(o,{topic:e,message:n}),i=>{i&&this._diag.error("producerHook error",i)},!0),o}};tg.KafkaJsInstrumentation=RC});var U9=m(D9=>{"use strict";Object.defineProperty(D9,"__esModule",{value:!0})});var k9=m(oi=>{"use strict";var wBe=oi&&oi.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),w9=oi&&oi.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&wBe(e,t,n)};Object.defineProperty(oi,"__esModule",{value:!0});w9(x9(),oi);w9(U9(),oi)});var $9=m(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.PACKAGE_NAME=Iu.PACKAGE_VERSION=void 0;Iu.PACKAGE_VERSION="0.44.1";Iu.PACKAGE_NAME="@opentelemetry/instrumentation-lru-memoizer"});var Y9=m(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});ng.LruMemoizerInstrumentation=void 0;var F9=(x(),b(B)),j9=fe(),q9=$9(),yC=class extends j9.InstrumentationBase{constructor(e={}){super(q9.PACKAGE_NAME,q9.PACKAGE_VERSION,e)}init(){return[new j9.InstrumentationNodeModuleDefinition("lru-memoizer",[">=1.3 <3"],e=>{let n=function(){let r=e.apply(this,arguments);return function(){let o=[...arguments],s=o.pop(),i=typeof s=="function"?F9.context.bind(F9.context.active(),s):s;return o.push(i),r.apply(this,o)}};return n.sync=e.sync,n},void 0)]}};ng.LruMemoizerInstrumentation=yC});var K9=m(Ia=>{"use strict";var VBe=Ia&&Ia.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),BBe=Ia&&Ia.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&VBe(e,t,n)};Object.defineProperty(Ia,"__esModule",{value:!0});BBe(Y9(),Ia)});var Z9=m(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});sp.MongodbCommandType=void 0;var HBe;(function(t){t.CREATE_INDEXES="createIndexes",t.FIND_AND_MODIFY="findAndModify",t.IS_MASTER="isMaster",t.COUNT="count",t.AGGREGATE="aggregate",t.UNKNOWN="unknown"})(HBe=sp.MongodbCommandType||(sp.MongodbCommandType={}))});var Q9=m(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.PACKAGE_NAME=Pu.PACKAGE_VERSION=void 0;Pu.PACKAGE_VERSION="0.52.0";Pu.PACKAGE_NAME="@opentelemetry/instrumentation-mongodb"});var n8=m(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});rg.MongoDBInstrumentation=void 0;var Ge=(x(),b(B)),Ue=fe(),Xo=(ve(),b(ot)),si=Z9(),e8=Q9(),t8={requireParentSpan:!0},OC=class t extends Ue.InstrumentationBase{constructor(e={}){super(e8.PACKAGE_NAME,e8.PACKAGE_VERSION,Object.assign(Object.assign({},t8),e))}setConfig(e={}){super.setConfig(Object.assign(Object.assign({},t8),e))}_updateMetricInstruments(){this._connectionsUsage=this.meter.createUpDownCounter("db.client.connections.usage",{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"})}init(){let{v3PatchConnection:e,v3UnpatchConnection:n}=this._getV3ConnectionPatches(),{v4PatchConnect:r,v4UnpatchConnect:o}=this._getV4ConnectPatches(),{v4PatchConnectionCallback:s,v4PatchConnectionPromise:i,v4UnpatchConnection:a}=this._getV4ConnectionPatches(),{v4PatchConnectionPool:c,v4UnpatchConnectionPool:u}=this._getV4ConnectionPoolPatches(),{v4PatchSessions:l,v4UnpatchSessions:d}=this._getV4SessionsPatches();return[new Ue.InstrumentationNodeModuleDefinition("mongodb",[">=3.3.0 <4"],void 0,void 0,[new Ue.InstrumentationNodeModuleFile("mongodb/lib/core/wireprotocol/index.js",[">=3.3.0 <4"],e,n)]),new Ue.InstrumentationNodeModuleDefinition("mongodb",[">=4.0.0 <7"],void 0,void 0,[new Ue.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js",[">=4.0.0 <6.4"],s,a),new Ue.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js",[">=6.4.0 <7"],i,a),new Ue.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection_pool.js",[">=4.0.0 <6.4"],c,u),new Ue.InstrumentationNodeModuleFile("mongodb/lib/cmap/connect.js",[">=4.0.0 <7"],r,o),new Ue.InstrumentationNodeModuleFile("mongodb/lib/sessions.js",[">=4.0.0 <7"],l,d)])]}_getV3ConnectionPatches(){return{v3PatchConnection:e=>((0,Ue.isWrapped)(e.insert)&&this._unwrap(e,"insert"),this._wrap(e,"insert",this._getV3PatchOperation("insert")),(0,Ue.isWrapped)(e.remove)&&this._unwrap(e,"remove"),this._wrap(e,"remove",this._getV3PatchOperation("remove")),(0,Ue.isWrapped)(e.update)&&this._unwrap(e,"update"),this._wrap(e,"update",this._getV3PatchOperation("update")),(0,Ue.isWrapped)(e.command)&&this._unwrap(e,"command"),this._wrap(e,"command",this._getV3PatchCommand()),(0,Ue.isWrapped)(e.query)&&this._unwrap(e,"query"),this._wrap(e,"query",this._getV3PatchFind()),(0,Ue.isWrapped)(e.getMore)&&this._unwrap(e,"getMore"),this._wrap(e,"getMore",this._getV3PatchCursor()),e),v3UnpatchConnection:e=>{e!==void 0&&(this._unwrap(e,"insert"),this._unwrap(e,"remove"),this._unwrap(e,"update"),this._unwrap(e,"command"),this._unwrap(e,"query"),this._unwrap(e,"getMore"))}}}_getV4SessionsPatches(){return{v4PatchSessions:e=>((0,Ue.isWrapped)(e.acquire)&&this._unwrap(e,"acquire"),this._wrap(e.ServerSessionPool.prototype,"acquire",this._getV4AcquireCommand()),(0,Ue.isWrapped)(e.release)&&this._unwrap(e,"release"),this._wrap(e.ServerSessionPool.prototype,"release",this._getV4ReleaseCommand()),e),v4UnpatchSessions:e=>{e!==void 0&&((0,Ue.isWrapped)(e.acquire)&&this._unwrap(e,"acquire"),(0,Ue.isWrapped)(e.release)&&this._unwrap(e,"release"))}}}_getV4AcquireCommand(){let e=this;return n=>function(){let o=this.sessions.length,s=n.call(this),i=this.sessions.length;return o===i?e._connectionsUsage.add(1,{state:"used","pool.name":e._poolName}):o-1===i&&(e._connectionsUsage.add(-1,{state:"idle","pool.name":e._poolName}),e._connectionsUsage.add(1,{state:"used","pool.name":e._poolName})),s}}_getV4ReleaseCommand(){let e=this;return n=>function(o){let s=n.call(this,o);return e._connectionsUsage.add(-1,{state:"used","pool.name":e._poolName}),e._connectionsUsage.add(1,{state:"idle","pool.name":e._poolName}),s}}_getV4ConnectionPoolPatches(){return{v4PatchConnectionPool:e=>{let n=e.ConnectionPool.prototype;return(0,Ue.isWrapped)(n.checkOut)&&this._unwrap(n,"checkOut"),this._wrap(n,"checkOut",this._getV4ConnectionPoolCheckOut()),e},v4UnpatchConnectionPool:e=>{e!==void 0&&this._unwrap(e.ConnectionPool.prototype,"checkOut")}}}_getV4ConnectPatches(){return{v4PatchConnect:e=>((0,Ue.isWrapped)(e.connect)&&this._unwrap(e,"connect"),this._wrap(e,"connect",this._getV4ConnectCommand()),e),v4UnpatchConnect:e=>{e!==void 0&&this._unwrap(e,"connect")}}}_getV4ConnectionPoolCheckOut(){return e=>function(r){let o=Ge.context.bind(Ge.context.active(),r);return e.call(this,o)}}_getV4ConnectCommand(){let e=this;return n=>function(o,s){if(n.length===1){let a=n.call(this,o);return a&&typeof a.then=="function"&&a.then(()=>e.setPoolName(o),()=>{}),a}let i=function(a,c){if(a||!c){s(a,c);return}e.setPoolName(o),s(a,c)};return n.call(this,o,i)}}_getV4ConnectionPatches(){return{v4PatchConnectionCallback:e=>((0,Ue.isWrapped)(e.Connection.prototype.command)&&this._unwrap(e.Connection.prototype,"command"),this._wrap(e.Connection.prototype,"command",this._getV4PatchCommandCallback()),e),v4PatchConnectionPromise:e=>((0,Ue.isWrapped)(e.Connection.prototype.command)&&this._unwrap(e.Connection.prototype,"command"),this._wrap(e.Connection.prototype,"command",this._getV4PatchCommandPromise()),e),v4UnpatchConnection:e=>{e!==void 0&&this._unwrap(e.Connection.prototype,"command")}}}_getV3PatchOperation(e){let n=this;return r=>function(s,i,a,c,u){let l=Ge.trace.getSpan(Ge.context.active()),d=n._checkSkipInstrumentation(l),p=typeof c=="function"?c:u;if(d||typeof p!="function"||typeof a!="object")return typeof c=="function"?r.call(this,s,i,a,c):r.call(this,s,i,a,c,u);let _=n.tracer.startSpan(`mongodb.${e}`,{kind:Ge.SpanKind.CLIENT});n._populateV3Attributes(_,i,s,a[0],e);let f=n._patchEnd(_,p);return typeof c=="function"?r.call(this,s,i,a,f):r.call(this,s,i,a,c,f)}}_getV3PatchCommand(){let e=this;return n=>function(o,s,i,a,c){let u=Ge.trace.getSpan(Ge.context.active()),l=e._checkSkipInstrumentation(u),d=typeof a=="function"?a:c;if(l||typeof d!="function"||typeof i!="object")return typeof a=="function"?n.call(this,o,s,i,a):n.call(this,o,s,i,a,c);let p=t._getCommandType(i),_=p===si.MongodbCommandType.UNKNOWN?"command":p,f=e.tracer.startSpan(`mongodb.${_}`,{kind:Ge.SpanKind.CLIENT}),E=p===si.MongodbCommandType.UNKNOWN?void 0:p;e._populateV3Attributes(f,s,o,i,E);let S=e._patchEnd(f,d);return typeof a=="function"?n.call(this,o,s,i,S):n.call(this,o,s,i,a,S)}}_getV4PatchCommandCallback(){let e=this;return n=>function(o,s,i,a){let c=Ge.trace.getSpan(Ge.context.active()),u=e._checkSkipInstrumentation(c),l=a,d=Object.keys(s)[0];if(typeof s!="object"||s.ismaster||s.hello)return n.call(this,o,s,i,a);let p;u||(p=e.tracer.startSpan(`mongodb.${d}`,{kind:Ge.SpanKind.CLIENT}),e._populateV4Attributes(p,this,o,s,d));let _=e._patchEnd(p,l,this.id,d);return n.call(this,o,s,i,_)}}_getV4PatchCommandPromise(){let e=this;return n=>function(...o){let[s,i]=o,a=Ge.trace.getSpan(Ge.context.active()),c=e._checkSkipInstrumentation(a),u=Object.keys(i)[0],l=()=>{};if(typeof i!="object"||i.ismaster||i.hello)return n.apply(this,o);let d;c||(d=e.tracer.startSpan(`mongodb.${u}`,{kind:Ge.SpanKind.CLIENT}),e._populateV4Attributes(d,this,s,i,u));let p=e._patchEnd(d,l,this.id,u),_=n.apply(this,o);return _.then(f=>p(null,f),f=>p(f)),_}}_getV3PatchFind(){let e=this;return n=>function(o,s,i,a,c,u){let l=Ge.trace.getSpan(Ge.context.active()),d=e._checkSkipInstrumentation(l),p=typeof c=="function"?c:u;if(d||typeof p!="function"||typeof i!="object")return typeof c=="function"?n.call(this,o,s,i,a,c):n.call(this,o,s,i,a,c,u);let _=e.tracer.startSpan("mongodb.find",{kind:Ge.SpanKind.CLIENT});e._populateV3Attributes(_,s,o,i,"find");let f=e._patchEnd(_,p);return typeof c=="function"?n.call(this,o,s,i,a,f):n.call(this,o,s,i,a,c,f)}}_getV3PatchCursor(){let e=this;return n=>function(o,s,i,a,c,u){let l=Ge.trace.getSpan(Ge.context.active()),d=e._checkSkipInstrumentation(l),p=typeof c=="function"?c:u;if(d||typeof p!="function")return typeof c=="function"?n.call(this,o,s,i,a,c):n.call(this,o,s,i,a,c,u);let _=e.tracer.startSpan("mongodb.getMore",{kind:Ge.SpanKind.CLIENT});e._populateV3Attributes(_,s,o,i.cmd,"getMore");let f=e._patchEnd(_,p);return typeof c=="function"?n.call(this,o,s,i,a,f):n.call(this,o,s,i,a,c,f)}}static _getCommandType(e){return e.createIndexes!==void 0?si.MongodbCommandType.CREATE_INDEXES:e.findandmodify!==void 0?si.MongodbCommandType.FIND_AND_MODIFY:e.ismaster!==void 0?si.MongodbCommandType.IS_MASTER:e.count!==void 0?si.MongodbCommandType.COUNT:e.aggregate!==void 0?si.MongodbCommandType.AGGREGATE:si.MongodbCommandType.UNKNOWN}_populateV4Attributes(e,n,r,o,s){let i,a;if(n){let u=typeof n.address=="string"?n.address.split(":"):"";u.length===2&&(i=u[0],a=u[1])}let c;o?.documents&&o.documents[0]?c=o.documents[0]:o?.cursors?c=o.cursors:c=o,this._addAllSpanAttributes(e,r.db,r.collection,i,a,c,s)}_populateV3Attributes(e,n,r,o,s){var i,a,c,u,l,d,p,_;let f,E;if(r&&r.s&&(f=(a=(i=r.s.options)===null||i===void 0?void 0:i.host)!==null&&a!==void 0?a:r.s.host,E=(l=(u=(c=r.s.options)===null||c===void 0?void 0:c.port)!==null&&u!==void 0?u:r.s.port)===null||l===void 0?void 0:l.toString(),f==null||E==null)){let A=(d=r.description)===null||d===void 0?void 0:d.address;if(A){let O=A.split(":");f=O[0],E=O[1]}}let[S,h]=n.toString().split("."),R=(_=(p=o?.query)!==null&&p!==void 0?p:o?.q)!==null&&_!==void 0?_:o;this._addAllSpanAttributes(e,S,h,f,E,R,s)}_addAllSpanAttributes(e,n,r,o,s,i,a){if(e.setAttributes({[Xo.SEMATTRS_DB_SYSTEM]:Xo.DBSYSTEMVALUES_MONGODB,[Xo.SEMATTRS_DB_NAME]:n,[Xo.SEMATTRS_DB_MONGODB_COLLECTION]:r,[Xo.SEMATTRS_DB_OPERATION]:a,[Xo.SEMATTRS_DB_CONNECTION_STRING]:`mongodb://${o}:${s}/${n}`}),o&&s){e.setAttribute(Xo.SEMATTRS_NET_PEER_NAME,o);let l=parseInt(s,10);isNaN(l)||e.setAttribute(Xo.SEMATTRS_NET_PEER_PORT,l)}if(!i)return;let{dbStatementSerializer:c}=this.getConfig(),u=typeof c=="function"?c:this._defaultDbStatementSerializer.bind(this);(0,Ue.safeExecuteInTheMiddle)(()=>{let l=u(i);e.setAttribute(Xo.SEMATTRS_DB_STATEMENT,l)},l=>{l&&this._diag.error("Error running dbStatementSerializer hook",l)},!0)}_defaultDbStatementSerializer(e){let{enhancedDatabaseReporting:n}=this.getConfig(),r=n?e:this._scrubStatement(e);return JSON.stringify(r)}_scrubStatement(e){return Array.isArray(e)?e.map(n=>this._scrubStatement(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,this._scrubStatement(r)])):"?"}_handleExecutionResult(e,n){let{responseHook:r}=this.getConfig();typeof r=="function"&&(0,Ue.safeExecuteInTheMiddle)(()=>{r(e,{data:n})},o=>{o&&this._diag.error("Error running response hook",o)},!0)}_patchEnd(e,n,r,o){let s=Ge.context.active(),i=this;return function(...c){let u=c[0];if(e){if(u instanceof Error)e?.setStatus({code:Ge.SpanStatusCode.ERROR,message:u.message});else{let l=c[1];i._handleExecutionResult(e,l)}e.end()}return Ge.context.with(s,()=>(o==="endSessions"&&i._connectionsUsage.add(-1,{state:"idle","pool.name":i._poolName}),n.apply(this,c)))}}setPoolName(e){var n,r;let o=(n=e.hostAddress)===null||n===void 0?void 0:n.host,s=(r=e.hostAddress)===null||r===void 0?void 0:r.port,i=e.dbName,a=`mongodb://${o}:${s}/${i}`;this._poolName=a}_checkSkipInstrumentation(e){return this.getConfig().requireParentSpan===!0&&e===void 0}};rg.MongoDBInstrumentation=OC});var r8=m(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.MongodbCommandType=void 0;var $Be;(function(t){t.CREATE_INDEXES="createIndexes",t.FIND_AND_MODIFY="findAndModify",t.IS_MASTER="isMaster",t.COUNT="count",t.UNKNOWN="unknown"})($Be=ip.MongodbCommandType||(ip.MongodbCommandType={}))});var s8=m(ii=>{"use strict";var FBe=ii&&ii.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),o8=ii&&ii.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&FBe(e,t,n)};Object.defineProperty(ii,"__esModule",{value:!0});o8(n8(),ii);o8(r8(),ii)});var p8=m(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.handleCallbackResponse=ai.handlePromiseResponse=ai.getAttributesFromCollection=void 0;var l8=(x(),b(B)),zBe=fe(),ap=(ve(),b(ot));function XBe(t){return{[ap.SEMATTRS_DB_MONGODB_COLLECTION]:t.name,[ap.SEMATTRS_DB_NAME]:t.conn.name,[ap.SEMATTRS_DB_USER]:t.conn.user,[ap.SEMATTRS_NET_PEER_NAME]:t.conn.host,[ap.SEMATTRS_NET_PEER_PORT]:t.conn.port}}ai.getAttributesFromCollection=XBe;function d8(t,e={}){t.recordException(e),t.setStatus({code:l8.SpanStatusCode.ERROR,message:`${e.message} ${e.code?`
11
- Mongoose Error Code: ${e.code}`:""}`})}function CC(t,e,n,r=void 0){n&&(0,zBe.safeExecuteInTheMiddle)(()=>n(t,{moduleVersion:r,response:e}),o=>{o&&l8.diag.error("mongoose instrumentation: responseHook error",o)},!0)}function JBe(t,e,n,r=void 0){return t instanceof Promise?t.then(o=>(CC(e,o,n,r),o)).catch(o=>{throw d8(e,o),o}).finally(()=>e.end()):(CC(e,t,n,r),e.end(),t)}ai.handlePromiseResponse=JBe;function ZBe(t,e,n,r,o,s,i=void 0){let a=0;return o.length===2&&(a=1),o[a]=(c,u)=>(c?d8(r,c):CC(r,u,s,i),r.end(),t(c,u)),e.apply(n,o)}ai.handleCallbackResponse=ZBe});var _8=m(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.PACKAGE_NAME=bu.PACKAGE_VERSION=void 0;bu.PACKAGE_VERSION="0.46.1";bu.PACKAGE_NAME="@opentelemetry/instrumentation-mongoose"});var g8=m(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.MongooseInstrumentation=mo._STORED_PARENT_SPAN=void 0;var dn=(x(),b(B)),QBe=Se(),vC=p8(),f8=fe(),m8=_8(),cp=(ve(),b(ot)),og=["deleteOne","deleteMany","find","findOne","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace"],eGe=["remove","count","findOneAndRemove",...og],tGe=["count","findOneAndRemove",...og],nGe=[...og];function E8(t){return t?t.startsWith("6.")||t.startsWith("5.")?eGe:t.startsWith("7.")?tGe:nGe:og}function S8(t){return t&&(t.startsWith("5.")||t.startsWith("6."))||!1}mo._STORED_PARENT_SPAN=Symbol("stored-parent-span");var IC=class extends f8.InstrumentationBase{constructor(e={}){super(m8.PACKAGE_NAME,m8.PACKAGE_VERSION,e)}init(){return new f8.InstrumentationNodeModuleDefinition("mongoose",[">=5.9.7 <9"],this.patch.bind(this),this.unpatch.bind(this))}patch(e,n){return this._wrap(e.Model.prototype,"save",this.patchOnModelMethods("save",n)),e.Model.prototype.$save=e.Model.prototype.save,S8(n)&&this._wrap(e.Model.prototype,"remove",this.patchOnModelMethods("remove",n)),this._wrap(e.Query.prototype,"exec",this.patchQueryExec(n)),this._wrap(e.Aggregate.prototype,"exec",this.patchAggregateExec(n)),E8(n).forEach(o=>{this._wrap(e.Query.prototype,o,this.patchAndCaptureSpanContext(o))}),this._wrap(e.Model,"aggregate",this.patchModelAggregate()),e}unpatch(e,n){let r=E8(n);this._unwrap(e.Model.prototype,"save"),e.Model.prototype.$save=e.Model.prototype.save,S8(n)&&this._unwrap(e.Model.prototype,"remove"),this._unwrap(e.Query.prototype,"exec"),this._unwrap(e.Aggregate.prototype,"exec"),r.forEach(o=>{this._unwrap(e.Query.prototype,o)}),this._unwrap(e.Model,"aggregate")}patchAggregateExec(e){let n=this;return r=>function(s){var i;if(n.getConfig().requireParentSpan&&dn.trace.getSpan(dn.context.active())===void 0)return r.apply(this,arguments);let a=this[mo._STORED_PARENT_SPAN],c={},{dbStatementSerializer:u}=n.getConfig();u&&(c[cp.SEMATTRS_DB_STATEMENT]=u("aggregate",{options:this.options,aggregatePipeline:this._pipeline}));let l=n._startSpan(this._model.collection,(i=this._model)===null||i===void 0?void 0:i.modelName,"aggregate",c,a);return n._handleResponse(l,r,this,arguments,s,e)}}patchQueryExec(e){let n=this;return r=>function(s){if(n.getConfig().requireParentSpan&&dn.trace.getSpan(dn.context.active())===void 0)return r.apply(this,arguments);let i=this[mo._STORED_PARENT_SPAN],a={},{dbStatementSerializer:c}=n.getConfig();c&&(a[cp.SEMATTRS_DB_STATEMENT]=c(this.op,{condition:this._conditions,updates:this._update,options:this.options,fields:this._fields}));let u=n._startSpan(this.mongooseCollection,this.model.modelName,this.op,a,i);return n._handleResponse(u,r,this,arguments,s,e)}}patchOnModelMethods(e,n){let r=this;return o=>function(i,a){if(r.getConfig().requireParentSpan&&dn.trace.getSpan(dn.context.active())===void 0)return o.apply(this,arguments);let c={document:this};i&&!(i instanceof Function)&&(c.options=i);let u={},{dbStatementSerializer:l}=r.getConfig();l&&(u[cp.SEMATTRS_DB_STATEMENT]=l(e,c));let d=r._startSpan(this.constructor.collection,this.constructor.modelName,e,u);return i instanceof Function&&(a=i,i=void 0),r._handleResponse(d,o,this,arguments,a,n)}}patchModelAggregate(){let e=this;return n=>function(){let o=dn.trace.getSpan(dn.context.active()),s=e._callOriginalFunction(()=>n.apply(this,arguments));return s&&(s[mo._STORED_PARENT_SPAN]=o),s}}patchAndCaptureSpanContext(e){let n=this;return r=>function(){return this[mo._STORED_PARENT_SPAN]=dn.trace.getSpan(dn.context.active()),n._callOriginalFunction(()=>r.apply(this,arguments))}}_startSpan(e,n,r,o,s){return this.tracer.startSpan(`mongoose.${n}.${r}`,{kind:dn.SpanKind.CLIENT,attributes:Object.assign(Object.assign(Object.assign({},o),(0,vC.getAttributesFromCollection)(e)),{[cp.SEMATTRS_DB_OPERATION]:r,[cp.SEMATTRS_DB_SYSTEM]:"mongoose"})},s?dn.trace.setSpan(dn.context.active(),s):void 0)}_handleResponse(e,n,r,o,s,i=void 0){let a=this;if(s instanceof Function)return a._callOriginalFunction(()=>(0,vC.handleCallbackResponse)(s,n,r,e,o,a.getConfig().responseHook,i));{let c=a._callOriginalFunction(()=>n.apply(r,o));return(0,vC.handlePromiseResponse)(c,e,a.getConfig().responseHook,i)}}_callOriginalFunction(e){return this.getConfig().suppressInternalInstrumentation?dn.context.with((0,QBe.suppressTracing)(dn.context.active()),e):e()}};mo.MongooseInstrumentation=IC});var T8=m(h8=>{"use strict";Object.defineProperty(h8,"__esModule",{value:!0})});var R8=m(ci=>{"use strict";var rGe=ci&&ci.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),A8=ci&&ci.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&rGe(e,t,n)};Object.defineProperty(ci,"__esModule",{value:!0});A8(g8(),ci);A8(T8(),ci)});var v8=m(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});up.AttributeNames=void 0;var sGe;(function(t){t.MYSQL_VALUES="db.mysql.values"})(sGe=up.AttributeNames||(up.AttributeNames={}))});var P8=m(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.getPoolName=Cn.arrayStringifyHelper=Cn.getSpanName=Cn.getDbValues=Cn.getDbStatement=Cn.getConnectionAttributes=void 0;var Jo=(ve(),b(ot));function iGe(t){let{host:e,port:n,database:r,user:o}=aGe(t),s=parseInt(n,10);return isNaN(s)?{[Jo.SEMATTRS_NET_PEER_NAME]:e,[Jo.SEMATTRS_DB_CONNECTION_STRING]:I8(e,n,r),[Jo.SEMATTRS_DB_NAME]:r,[Jo.SEMATTRS_DB_USER]:o}:{[Jo.SEMATTRS_NET_PEER_NAME]:e,[Jo.SEMATTRS_NET_PEER_PORT]:s,[Jo.SEMATTRS_DB_CONNECTION_STRING]:I8(e,n,r),[Jo.SEMATTRS_DB_NAME]:r,[Jo.SEMATTRS_DB_USER]:o}}Cn.getConnectionAttributes=iGe;function aGe(t){let{host:e,port:n,database:r,user:o}=t&&t.connectionConfig||t||{};return{host:e,port:n,database:r,user:o}}function I8(t,e,n){let r=`jdbc:mysql://${t||"localhost"}`;return typeof e=="number"&&(r+=`:${e}`),typeof n=="string"&&(r+=`/${n}`),r}function cGe(t){return typeof t=="string"?t:t.sql}Cn.getDbStatement=cGe;function uGe(t,e){return PC(typeof t=="string"?e:e||t.values)}Cn.getDbValues=uGe;function lGe(t){let e=typeof t=="object"?t.sql:t,n=e?.indexOf(" ");return typeof n=="number"&&n!==-1?e?.substring(0,n):e}Cn.getSpanName=lGe;function PC(t){return t?`[${t.toString()}]`:""}Cn.arrayStringifyHelper=PC;function dGe(t){let e=t.config.connectionConfig,n="";return n+=e.host?`host: '${e.host}', `:"",n+=e.port?`port: ${e.port}, `:"",n+=e.database?`database: '${e.database}', `:"",n+=e.user?`user: '${e.user}'`:"",e.user||(n=n.substring(0,n.length-2)),n.trim()}Cn.getPoolName=dGe});var b8=m(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.PACKAGE_NAME=Mu.PACKAGE_VERSION=void 0;Mu.PACKAGE_VERSION="0.45.1";Mu.PACKAGE_NAME="@opentelemetry/instrumentation-mysql"});var L8=m(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.MySQLInstrumentation=void 0;var vn=(x(),b(B)),Lu=fe(),bC=(ve(),b(ot)),pGe=v8(),xu=P8(),M8=b8(),sg=class t extends Lu.InstrumentationBase{constructor(e={}){super(M8.PACKAGE_NAME,M8.PACKAGE_VERSION,e),this._setMetricInstruments()}setMeterProvider(e){super.setMeterProvider(e),this._setMetricInstruments()}_setMetricInstruments(){this._connectionsUsage=this.meter.createUpDownCounter("db.client.connections.usage",{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"})}init(){return[new Lu.InstrumentationNodeModuleDefinition("mysql",[">=2.0.0 <3"],e=>((0,Lu.isWrapped)(e.createConnection)&&this._unwrap(e,"createConnection"),this._wrap(e,"createConnection",this._patchCreateConnection()),(0,Lu.isWrapped)(e.createPool)&&this._unwrap(e,"createPool"),this._wrap(e,"createPool",this._patchCreatePool()),(0,Lu.isWrapped)(e.createPoolCluster)&&this._unwrap(e,"createPoolCluster"),this._wrap(e,"createPoolCluster",this._patchCreatePoolCluster()),e),e=>{e!==void 0&&(this._unwrap(e,"createConnection"),this._unwrap(e,"createPool"),this._unwrap(e,"createPoolCluster"))})]}_patchCreateConnection(){return e=>{let n=this;return function(o){let s=e(...arguments);return n._wrap(s,"query",n._patchQuery(s)),s}}}_patchCreatePool(){return e=>{let n=this;return function(o){let s=e(...arguments);return n._wrap(s,"query",n._patchQuery(s)),n._wrap(s,"getConnection",n._patchGetConnection(s)),n._wrap(s,"end",n._patchPoolEnd(s)),n._setPoolcallbacks(s,n,""),s}}}_patchPoolEnd(e){return n=>{let r=this;return function(s){let i=e._allConnections.length,a=e._freeConnections.length,c=i-a,u=(0,xu.getPoolName)(e);r._connectionsUsage.add(-c,{state:"used",name:u}),r._connectionsUsage.add(-a,{state:"idle",name:u}),n.apply(e,arguments)}}}_patchCreatePoolCluster(){return e=>{let n=this;return function(o){let s=e(...arguments);return n._wrap(s,"getConnection",n._patchGetConnection(s)),n._wrap(s,"add",n._patchAdd(s)),s}}}_patchAdd(e){return n=>{let r=this;return function(s,i){if(!r._enabled)return r._unwrap(e,"add"),n.apply(e,arguments);n.apply(e,arguments);let a=e._nodes;if(a){let c=typeof s=="object"?"CLUSTER::"+e._lastId:String(s),u=a[c].pool;r._setPoolcallbacks(u,r,s)}}}}_patchGetConnection(e){return n=>{let r=this;return function(s,i,a){if(!r._enabled)return r._unwrap(e,"getConnection"),n.apply(e,arguments);if(arguments.length===1&&typeof s=="function"){let c=r._getConnectionCallbackPatchFn(s);return n.call(e,c)}if(arguments.length===2&&typeof i=="function"){let c=r._getConnectionCallbackPatchFn(i);return n.call(e,s,c)}if(arguments.length===3&&typeof a=="function"){let c=r._getConnectionCallbackPatchFn(a);return n.call(e,s,i,c)}return n.apply(e,arguments)}}}_getConnectionCallbackPatchFn(e){let n=this,r=vn.context.active();return function(o,s){s&&((0,Lu.isWrapped)(s.query)||n._wrap(s,"query",n._patchQuery(s))),typeof e=="function"&&vn.context.with(r,e,this,o,s)}}_patchQuery(e){return n=>{let r=this;return function(o,s,i){if(!r._enabled)return r._unwrap(e,"query"),n.apply(e,arguments);let a=r.tracer.startSpan((0,xu.getSpanName)(o),{kind:vn.SpanKind.CLIENT,attributes:Object.assign(Object.assign({},t.COMMON_ATTRIBUTES),(0,xu.getConnectionAttributes)(e.config))});if(a.setAttribute(bC.SEMATTRS_DB_STATEMENT,(0,xu.getDbStatement)(o)),r.getConfig().enhancedDatabaseReporting){let l;Array.isArray(s)?l=s:arguments[2]&&(l=[s]),a.setAttribute(pGe.AttributeNames.MYSQL_VALUES,(0,xu.getDbValues)(o,l))}let c=Array.from(arguments).findIndex(l=>typeof l=="function"),u=vn.context.active();if(c===-1){let l=vn.context.with(vn.trace.setSpan(vn.context.active(),a),()=>n.apply(e,arguments));return vn.context.bind(u,l),l.on("error",d=>a.setStatus({code:vn.SpanStatusCode.ERROR,message:d.message})).on("end",()=>{a.end()})}else return r._wrap(arguments,c,r._patchCallbackQuery(a,u)),vn.context.with(vn.trace.setSpan(vn.context.active(),a),()=>n.apply(e,arguments))}}}_patchCallbackQuery(e,n){return r=>function(o,s,i){return o&&e.setStatus({code:vn.SpanStatusCode.ERROR,message:o.message}),e.end(),vn.context.with(n,()=>r(...arguments))}}_setPoolcallbacks(e,n,r){let o=r||(0,xu.getPoolName)(e);e.on("connection",s=>{n._connectionsUsage.add(1,{state:"idle",name:o})}),e.on("acquire",s=>{n._connectionsUsage.add(-1,{state:"idle",name:o}),n._connectionsUsage.add(1,{state:"used",name:o})}),e.on("release",s=>{n._connectionsUsage.add(-1,{state:"used",name:o}),n._connectionsUsage.add(1,{state:"idle",name:o})})}};ig.MySQLInstrumentation=sg;sg.COMMON_ATTRIBUTES={[bC.SEMATTRS_DB_SYSTEM]:bC.DBSYSTEMVALUES_MYSQL}});var D8=m(x8=>{"use strict";Object.defineProperty(x8,"__esModule",{value:!0})});var w8=m(ui=>{"use strict";var _Ge=ui&&ui.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),U8=ui&&ui.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_Ge(e,t,n)};Object.defineProperty(ui,"__esModule",{value:!0});U8(L8(),ui);U8(D8(),ui)});var LC=m(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.addSqlCommenterComment=void 0;var MC=(x(),b(B)),mGe=Se();function EGe(t){let e=t.indexOf("--");if(e>=0)return!0;if(t.indexOf("/*")<0)return!1;let r=t.indexOf("*/");return e<r}function SGe(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function gGe(t,e){if(typeof e!="string"||e.length===0||EGe(e))return e;let n=new mGe.W3CTraceContextPropagator,r={};n.inject(MC.trace.setSpan(MC.ROOT_CONTEXT,t),r,MC.defaultTextMapSetter);let o=Object.keys(r).sort();if(o.length===0)return e;let s=o.map(i=>{let a=SGe(r[i]);return`${i}='${a}'`}).join(",");return`${e} /*${s}*/`}ag.addSqlCommenterComment=gGe});var $8=m(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.getConnectionPrototypeToInstrument=cr.once=cr.getSpanName=cr.getDbStatement=cr.getConnectionAttributes=void 0;var Zo=(ve(),b(ot));function hGe(t){let{host:e,port:n,database:r,user:o}=TGe(t),s=parseInt(n,10);return isNaN(s)?{[Zo.SEMATTRS_NET_PEER_NAME]:e,[Zo.SEMATTRS_DB_CONNECTION_STRING]:H8(e,n,r),[Zo.SEMATTRS_DB_NAME]:r,[Zo.SEMATTRS_DB_USER]:o}:{[Zo.SEMATTRS_NET_PEER_NAME]:e,[Zo.SEMATTRS_NET_PEER_PORT]:s,[Zo.SEMATTRS_DB_CONNECTION_STRING]:H8(e,n,r),[Zo.SEMATTRS_DB_NAME]:r,[Zo.SEMATTRS_DB_USER]:o}}cr.getConnectionAttributes=hGe;function TGe(t){let{host:e,port:n,database:r,user:o}=t&&t.connectionConfig||t||{};return{host:e,port:n,database:r,user:o}}function H8(t,e,n){let r=`jdbc:mysql://${t||"localhost"}`;return typeof e=="number"&&(r+=`:${e}`),typeof n=="string"&&(r+=`/${n}`),r}function AGe(t,e,n){return e?typeof t=="string"?n?e(t,n):t:n||t.values?e(t.sql,n||t.values):t.sql:typeof t=="string"?t:t.sql}cr.getDbStatement=AGe;function RGe(t){let e=typeof t=="object"?t.sql:t,n=e?.indexOf(" ");return typeof n=="number"&&n!==-1?e?.substring(0,n):e}cr.getSpanName=RGe;var yGe=t=>{let e=!1;return(...n)=>{if(!e)return e=!0,t(...n)}};cr.once=yGe;function OGe(t){let e=t.prototype,n=Object.getPrototypeOf(e);return typeof n?.query=="function"&&typeof n?.execute=="function"?n:e}cr.getConnectionPrototypeToInstrument=OGe});var F8=m(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.PACKAGE_NAME=Du.PACKAGE_VERSION=void 0;Du.PACKAGE_VERSION="0.45.2";Du.PACKAGE_NAME="@opentelemetry/instrumentation-mysql2"});var K8=m(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});ug.MySQL2Instrumentation=void 0;var j8=(x(),b(B)),Pa=fe(),DC=(ve(),b(ot)),q8=LC(),Uu=$8(),Y8=F8(),xC=[">=1.4.2 <4"],cg=class t extends Pa.InstrumentationBase{constructor(e={}){super(Y8.PACKAGE_NAME,Y8.PACKAGE_VERSION,e)}init(){let e;function n(s){!e&&s.format&&(e=s.format)}let r=s=>{(0,Pa.isWrapped)(s.query)&&this._unwrap(s,"query"),this._wrap(s,"query",this._patchQuery(e,!1)),(0,Pa.isWrapped)(s.execute)&&this._unwrap(s,"execute"),this._wrap(s,"execute",this._patchQuery(e,!0))},o=s=>{this._unwrap(s,"query"),this._unwrap(s,"execute")};return[new Pa.InstrumentationNodeModuleDefinition("mysql2",xC,s=>(n(s),s),()=>{},[new Pa.InstrumentationNodeModuleFile("mysql2/promise.js",xC,s=>(n(s),s),()=>{}),new Pa.InstrumentationNodeModuleFile("mysql2/lib/connection.js",xC,s=>{let i=(0,Uu.getConnectionPrototypeToInstrument)(s);return r(i),s},s=>{if(s===void 0)return;let i=(0,Uu.getConnectionPrototypeToInstrument)(s);o(i)})])]}_patchQuery(e,n){return r=>{let o=this;return function(s,i,a){let c;Array.isArray(i)?c=i:arguments[2]&&(c=[i]);let u=o.tracer.startSpan((0,Uu.getSpanName)(s),{kind:j8.SpanKind.CLIENT,attributes:Object.assign(Object.assign(Object.assign({},t.COMMON_ATTRIBUTES),(0,Uu.getConnectionAttributes)(this.config)),{[DC.SEMATTRS_DB_STATEMENT]:(0,Uu.getDbStatement)(s,e,c)})});!n&&o.getConfig().addSqlCommenterCommentToQueries&&(arguments[0]=s=typeof s=="string"?(0,q8.addSqlCommenterComment)(u,s):Object.assign(s,{sql:(0,q8.addSqlCommenterComment)(u,s.sql)}));let l=(0,Uu.once)((d,p)=>{if(d)u.setStatus({code:j8.SpanStatusCode.ERROR,message:d.message});else{let{responseHook:_}=o.getConfig();typeof _=="function"&&(0,Pa.safeExecuteInTheMiddle)(()=>{_(u,{queryResults:p})},f=>{f&&o._diag.warn("Failed executing responseHook",f)},!0)}u.end()});if(arguments.length===1){typeof s.onResult=="function"&&o._wrap(s,"onResult",o._patchCallbackQuery(l));let d=r.apply(this,arguments);return d.once("error",p=>{l(p)}).once("result",p=>{l(void 0,p)}),d}return typeof arguments[1]=="function"?o._wrap(arguments,1,o._patchCallbackQuery(l)):typeof arguments[2]=="function"&&o._wrap(arguments,2,o._patchCallbackQuery(l)),r.apply(this,arguments)}}}_patchCallbackQuery(e){return n=>function(r,o,s){return e(r,o),n(...arguments)}}};ug.MySQL2Instrumentation=cg;cg.COMMON_ATTRIBUTES={[DC.SEMATTRS_DB_SYSTEM]:DC.DBSYSTEMVALUES_MYSQL}});var z8=m(W8=>{"use strict";Object.defineProperty(W8,"__esModule",{value:!0})});var J8=m(li=>{"use strict";var NGe=li&&li.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),X8=li&&li.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&NGe(e,t,n)};Object.defineProperty(li,"__esModule",{value:!0});X8(K8(),li);X8(z8(),li)});var n6=m(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});lg.endSpan=void 0;var vGe=(x(),b(B)),IGe=(t,e)=>{e&&(t.recordException(e),t.setStatus({code:vGe.SpanStatusCode.ERROR,message:e.message})),t.end()};lg.endSpan=IGe});var UC=m(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});dg.defaultDbStatementSerializer=void 0;var PGe=[{regex:/^ECHO/i,args:0},{regex:/^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,args:1},{regex:/^(HSET|HMSET|LSET|LINSERT)/i,args:2},{regex:/^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,args:-1}],bGe=(t,e)=>{var n,r;if(Array.isArray(e)&&e.length){let o=(r=(n=PGe.find(({regex:i})=>i.test(t)))===null||n===void 0?void 0:n.args)!==null&&r!==void 0?r:0,s=o>=0?e.slice(0,o):e;return e.length>s.length&&s.push(`[${e.length-o} other arguments]`),`${t} ${s.join(" ")}`}return t};dg.defaultDbStatementSerializer=bGe});var r6=m(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.PACKAGE_NAME=wu.PACKAGE_VERSION=void 0;wu.PACKAGE_VERSION="0.47.1";wu.PACKAGE_NAME="@opentelemetry/instrumentation-ioredis"});var a6=m(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});_g.IORedisInstrumentation=void 0;var di=(x(),b(B)),pg=fe(),ur=(ve(),b(ot)),o6=fe(),lp=n6(),MGe=UC(),s6=r6(),i6={requireParentSpan:!0},wC=class extends pg.InstrumentationBase{constructor(e={}){super(s6.PACKAGE_NAME,s6.PACKAGE_VERSION,Object.assign(Object.assign({},i6),e))}setConfig(e={}){super.setConfig(Object.assign(Object.assign({},i6),e))}init(){return[new pg.InstrumentationNodeModuleDefinition("ioredis",[">=2.0.0 <6"],(e,n)=>{let r=e[Symbol.toStringTag]==="Module"?e.default:e;return(0,pg.isWrapped)(r.prototype.sendCommand)&&this._unwrap(r.prototype,"sendCommand"),this._wrap(r.prototype,"sendCommand",this._patchSendCommand(n)),(0,pg.isWrapped)(r.prototype.connect)&&this._unwrap(r.prototype,"connect"),this._wrap(r.prototype,"connect",this._patchConnection()),e},e=>{if(e===void 0)return;let n=e[Symbol.toStringTag]==="Module"?e.default:e;this._unwrap(n.prototype,"sendCommand"),this._unwrap(n.prototype,"connect")})]}_patchSendCommand(e){return n=>this._traceSendCommand(n,e)}_patchConnection(){return e=>this._traceConnection(e)}_traceSendCommand(e,n){let r=this;return function(o){if(arguments.length<1||typeof o!="object")return e.apply(this,arguments);let s=r.getConfig(),i=s.dbStatementSerializer||MGe.defaultDbStatementSerializer,a=di.trace.getSpan(di.context.active())===void 0;if(s.requireParentSpan===!0&&a)return e.apply(this,arguments);let c=r.tracer.startSpan(o.name,{kind:di.SpanKind.CLIENT,attributes:{[ur.SEMATTRS_DB_SYSTEM]:ur.DBSYSTEMVALUES_REDIS,[ur.SEMATTRS_DB_STATEMENT]:i(o.name,o.args)}}),{requestHook:u}=s;u&&(0,o6.safeExecuteInTheMiddle)(()=>u(c,{moduleVersion:n,cmdName:o.name,cmdArgs:o.args}),p=>{p&&di.diag.error("ioredis instrumentation: request hook failed",p)},!0);let{host:l,port:d}=this.options;c.setAttributes({[ur.SEMATTRS_NET_PEER_NAME]:l,[ur.SEMATTRS_NET_PEER_PORT]:d,[ur.SEMATTRS_DB_CONNECTION_STRING]:`redis://${l}:${d}`});try{let p=e.apply(this,arguments),_=o.resolve;o.resolve=function(E){(0,o6.safeExecuteInTheMiddle)(()=>{var S;return(S=s.responseHook)===null||S===void 0?void 0:S.call(s,c,o.name,o.args,E)},S=>{S&&di.diag.error("ioredis instrumentation: response hook failed",S)},!0),(0,lp.endSpan)(c,null),_(E)};let f=o.reject;return o.reject=function(E){(0,lp.endSpan)(c,E),f(E)},p}catch(p){throw(0,lp.endSpan)(c,p),p}}}_traceConnection(e){let n=this;return function(){let r=di.trace.getSpan(di.context.active())===void 0;if(n.getConfig().requireParentSpan===!0&&r)return e.apply(this,arguments);let o=n.tracer.startSpan("connect",{kind:di.SpanKind.CLIENT,attributes:{[ur.SEMATTRS_DB_SYSTEM]:ur.DBSYSTEMVALUES_REDIS,[ur.SEMATTRS_DB_STATEMENT]:"connect"}}),{host:s,port:i}=this.options;o.setAttributes({[ur.SEMATTRS_NET_PEER_NAME]:s,[ur.SEMATTRS_NET_PEER_PORT]:i,[ur.SEMATTRS_DB_CONNECTION_STRING]:`redis://${s}:${i}`});try{let a=e.apply(this,arguments);return(0,lp.endSpan)(o,null),a}catch(a){throw(0,lp.endSpan)(o,a),a}}}};_g.IORedisInstrumentation=wC});var u6=m(c6=>{"use strict";Object.defineProperty(c6,"__esModule",{value:!0})});var d6=m(pi=>{"use strict";var LGe=pi&&pi.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),l6=pi&&pi.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&LGe(e,t,n)};Object.defineProperty(pi,"__esModule",{value:!0});l6(a6(),pi);l6(u6(),pi)});var p6=m(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});fg.getClientAttributes=void 0;var dp=(ve(),b(ot));function xGe(t,e){var n,r;return{[dp.SEMATTRS_DB_SYSTEM]:dp.DBSYSTEMVALUES_REDIS,[dp.SEMATTRS_NET_PEER_NAME]:(n=e?.socket)===null||n===void 0?void 0:n.host,[dp.SEMATTRS_NET_PEER_PORT]:(r=e?.socket)===null||r===void 0?void 0:r.port,[dp.SEMATTRS_DB_CONNECTION_STRING]:DGe(t,e?.url)}}fg.getClientAttributes=xGe;function DGe(t,e){if(!(typeof e!="string"||!e))try{let n=new URL(e);return n.searchParams.delete("user_pwd"),n.username="",n.password="",n.href}catch(n){t.error("failed to sanitize redis connection url",n)}}});var _6=m(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.PACKAGE_NAME=ku.PACKAGE_VERSION=void 0;ku.PACKAGE_VERSION="0.46.1";ku.PACKAGE_NAME="@opentelemetry/instrumentation-redis-4"});var g6=m(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});Eg.RedisInstrumentation=void 0;var lr=(x(),b(B)),Pt=fe(),f6=p6(),UGe=UC(),m6=_6(),wGe=(ve(),b(ot)),pp=Symbol("opentelemetry.instrumentation.redis.open_spans"),E6=Symbol("opentelemetry.instrumentation.redis.multi_command_options"),S6={requireParentSpan:!1},mg=class t extends Pt.InstrumentationBase{constructor(e={}){super(m6.PACKAGE_NAME,m6.PACKAGE_VERSION,Object.assign(Object.assign({},S6),e))}setConfig(e={}){super.setConfig(Object.assign(Object.assign({},S6),e))}init(){return[this._getInstrumentationNodeModuleDefinition("@redis/client"),this._getInstrumentationNodeModuleDefinition("@node-redis/client")]}_getInstrumentationNodeModuleDefinition(e){let n=new Pt.InstrumentationNodeModuleFile(`${e}/dist/lib/commander.js`,["^1.0.0"],(s,i)=>{let a=s.transformCommandArguments;if(!a)return this._diag.error("internal instrumentation error, missing transformCommandArguments function"),s;let c=i?.startsWith("1.0.")?"extendWithCommands":"attachCommands";return(0,Pt.isWrapped)(s?.[c])&&this._unwrap(s,c),this._wrap(s,c,this._getPatchExtendWithCommands(a)),s},s=>{(0,Pt.isWrapped)(s?.extendWithCommands)&&this._unwrap(s,"extendWithCommands"),(0,Pt.isWrapped)(s?.attachCommands)&&this._unwrap(s,"attachCommands")}),r=new Pt.InstrumentationNodeModuleFile(`${e}/dist/lib/client/multi-command.js`,["^1.0.0"],s=>{var i;let a=(i=s?.default)===null||i===void 0?void 0:i.prototype;return(0,Pt.isWrapped)(a?.exec)&&this._unwrap(a,"exec"),this._wrap(a,"exec",this._getPatchMultiCommandsExec()),(0,Pt.isWrapped)(a?.addCommand)&&this._unwrap(a,"addCommand"),this._wrap(a,"addCommand",this._getPatchMultiCommandsAddCommand()),s},s=>{var i;let a=(i=s?.default)===null||i===void 0?void 0:i.prototype;(0,Pt.isWrapped)(a?.exec)&&this._unwrap(a,"exec"),(0,Pt.isWrapped)(a?.addCommand)&&this._unwrap(a,"addCommand")}),o=new Pt.InstrumentationNodeModuleFile(`${e}/dist/lib/client/index.js`,["^1.0.0"],s=>{var i;let a=(i=s?.default)===null||i===void 0?void 0:i.prototype;return a?.multi&&((0,Pt.isWrapped)(a?.multi)&&this._unwrap(a,"multi"),this._wrap(a,"multi",this._getPatchRedisClientMulti())),a?.MULTI&&((0,Pt.isWrapped)(a?.MULTI)&&this._unwrap(a,"MULTI"),this._wrap(a,"MULTI",this._getPatchRedisClientMulti())),(0,Pt.isWrapped)(a?.sendCommand)&&this._unwrap(a,"sendCommand"),this._wrap(a,"sendCommand",this._getPatchRedisClientSendCommand()),this._wrap(a,"connect",this._getPatchedClientConnect()),s},s=>{var i;let a=(i=s?.default)===null||i===void 0?void 0:i.prototype;(0,Pt.isWrapped)(a?.multi)&&this._unwrap(a,"multi"),(0,Pt.isWrapped)(a?.MULTI)&&this._unwrap(a,"MULTI"),(0,Pt.isWrapped)(a?.sendCommand)&&this._unwrap(a,"sendCommand")});return new Pt.InstrumentationNodeModuleDefinition(e,["^1.0.0"],s=>s,()=>{},[n,r,o])}_getPatchExtendWithCommands(e){let n=this;return function(o){return function(i){var a;if(((a=i?.BaseClass)===null||a===void 0?void 0:a.name)!=="RedisClient")return o.apply(this,arguments);let c=i.executor;return i.executor=function(u,l){let d=e(u,l).args;return n._traceClientCommand(c,this,arguments,d)},o.apply(this,arguments)}}}_getPatchMultiCommandsExec(){let e=this;return function(r){return function(){let s=r.apply(this,arguments);return typeof s?.then!="function"?(e._diag.error("got non promise result when patching RedisClientMultiCommand.exec"),s):s.then(i=>{let a=this[pp];return e._endSpansWithRedisReplies(a,i),i}).catch(i=>{let a=this[pp];if(!a)e._diag.error("cannot find open spans to end for redis multi command");else{let c=i.constructor.name==="MultiErrorReply"?i.replies:new Array(a.length).fill(i);e._endSpansWithRedisReplies(a,c)}return Promise.reject(i)})}}}_getPatchMultiCommandsAddCommand(){let e=this;return function(r){return function(s){return e._traceClientCommand(r,this,arguments,s)}}}_getPatchRedisClientMulti(){return function(n){return function(){let o=n.apply(this,arguments);return o[E6]=this.options,o}}}_getPatchRedisClientSendCommand(){let e=this;return function(r){return function(s){return e._traceClientCommand(r,this,arguments,s)}}}_getPatchedClientConnect(){let e=this;return function(r){return function(){let s=this.options,i=(0,f6.getClientAttributes)(e._diag,s),a=e.tracer.startSpan(`${t.COMPONENT}-connect`,{kind:lr.SpanKind.CLIENT,attributes:i});return lr.context.with(lr.trace.setSpan(lr.context.active(),a),()=>r.apply(this)).then(u=>(a.end(),u)).catch(u=>(a.recordException(u),a.setStatus({code:lr.SpanStatusCode.ERROR,message:u.message}),a.end(),Promise.reject(u)))}}}_traceClientCommand(e,n,r,o){if(lr.trace.getSpan(lr.context.active())===void 0&&this.getConfig().requireParentSpan)return e.apply(n,r);let i=n.options||n[E6],a=o[0],c=o.slice(1),u=this.getConfig().dbStatementSerializer||UGe.defaultDbStatementSerializer,l=(0,f6.getClientAttributes)(this._diag,i);try{let _=u(a,c);_!=null&&(l[wGe.SEMATTRS_DB_STATEMENT]=_)}catch(_){this._diag.error("dbStatementSerializer throw an exception",_,{commandName:a})}let d=this.tracer.startSpan(`${t.COMPONENT}-${a}`,{kind:lr.SpanKind.CLIENT,attributes:l}),p=lr.context.with(lr.trace.setSpan(lr.context.active(),d),()=>e.apply(n,r));if(typeof p?.then=="function")p.then(_=>{this._endSpanWithResponse(d,a,c,_,void 0)},_=>{this._endSpanWithResponse(d,a,c,null,_)});else{let _=p;_[pp]=_[pp]||[],_[pp].push({span:d,commandName:a,commandArgs:c})}return p}_endSpansWithRedisReplies(e,n){if(!e)return this._diag.error("cannot find open spans to end for redis multi command");if(n.length!==e.length)return this._diag.error("number of multi command spans does not match response from redis");for(let r=0;r<e.length;r++){let{span:o,commandName:s,commandArgs:i}=e[r],a=n[r],[c,u]=a instanceof Error?[null,a]:[a,void 0];this._endSpanWithResponse(o,s,i,c,u)}}_endSpanWithResponse(e,n,r,o,s){let{responseHook:i}=this.getConfig();if(!s&&i)try{i(e,n,r,o)}catch(a){this._diag.error("responseHook throw an exception",a)}s&&(e.recordException(s),e.setStatus({code:lr.SpanStatusCode.ERROR,message:s?.message})),e.end()}};Eg.RedisInstrumentation=mg;mg.COMPONENT="redis"});var T6=m(h6=>{"use strict";Object.defineProperty(h6,"__esModule",{value:!0})});var R6=m(_i=>{"use strict";var kGe=_i&&_i.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),A6=_i&&_i.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&kGe(e,t,n)};Object.defineProperty(_i,"__esModule",{value:!0});A6(g6(),_i);A6(T6(),_i)});var x6=m(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});Sg.EVENT_LISTENERS_SET=void 0;Sg.EVENT_LISTENERS_SET=Symbol("opentelemetry.instrumentation.pg.eventListenersSet")});var GC=m(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});fp.AttributeNames=void 0;var jGe;(function(t){t.PG_VALUES="db.postgresql.values",t.PG_PLAN="db.postgresql.plan",t.IDLE_TIMEOUT_MILLIS="db.postgresql.idle.timeout.millis",t.MAX_CLIENT="db.postgresql.max.client"})(jGe=fp.AttributeNames||(fp.AttributeNames={}))});var HC=m(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.METRIC_DB_CLIENT_OPERATION_DURATION=ut.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS=ut.METRIC_DB_CLIENT_CONNECTION_COUNT=ut.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE=ut.DB_CLIENT_CONNECTION_STATE_VALUE_USED=ut.ATTR_DB_OPERATION_NAME=ut.ATTR_DB_NAMESPACE=ut.ATTR_DB_CLIENT_CONNECTION_STATE=ut.ATTR_DB_CLIENT_CONNECTION_POOL_NAME=void 0;ut.ATTR_DB_CLIENT_CONNECTION_POOL_NAME="db.client.connection.pool.name";ut.ATTR_DB_CLIENT_CONNECTION_STATE="db.client.connection.state";ut.ATTR_DB_NAMESPACE="db.namespace";ut.ATTR_DB_OPERATION_NAME="db.operation.name";ut.DB_CLIENT_CONNECTION_STATE_VALUE_USED="used";ut.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE="idle";ut.METRIC_DB_CLIENT_CONNECTION_COUNT="db.client.connection.count";ut.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS="db.client.connection.pending_requests";ut.METRIC_DB_CLIENT_OPERATION_DURATION="db.client.operation.duration"});var $C=m(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.SpanNames=void 0;var qGe;(function(t){t.QUERY_PREFIX="pg.query",t.CONNECT="pg.connect",t.POOL_CONNECT="pg-pool.connect"})(qGe=mp.SpanNames||(mp.SpanNames={}))});var G6=m(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.isObjectWithTextString=Te.getErrorMessage=Te.patchClientConnectCallback=Te.patchCallbackPGPool=Te.updateCounter=Te.getPoolName=Te.patchCallback=Te.handleExecutionResult=Te.handleConfigQuery=Te.shouldSkipInstrumentation=Te.getSemanticAttributesFromPool=Te.getSemanticAttributesFromConnection=Te.getConnectionString=Te.parseNormalizedOperationName=Te.getQuerySpanName=void 0;var fi=(x(),b(B)),gg=GC(),tn=(ve(),b(ot)),ba=HC(),YGe=fe(),D6=$C();function U6(t,e){if(!e)return D6.SpanNames.QUERY_PREFIX;let n=typeof e.name=="string"&&e.name?e.name:w6(e.text);return`${D6.SpanNames.QUERY_PREFIX}:${n}${t?` ${t}`:""}`}Te.getQuerySpanName=U6;function w6(t){let e=t.indexOf(" "),n=e===-1?t:t.slice(0,e);return n=n.toUpperCase(),n.endsWith(";")?n.slice(0,-1):n}Te.parseNormalizedOperationName=w6;function FC(t){let e=t.host||"localhost",n=t.port||5432,r=t.database||"";return`postgresql://${e}:${n}/${r}`}Te.getConnectionString=FC;function k6(t){if(Number.isInteger(t))return t}function V6(t){return{[tn.SEMATTRS_DB_SYSTEM]:tn.DBSYSTEMVALUES_POSTGRESQL,[tn.SEMATTRS_DB_NAME]:t.database,[tn.SEMATTRS_DB_CONNECTION_STRING]:FC(t),[tn.SEMATTRS_NET_PEER_NAME]:t.host,[tn.SEMATTRS_NET_PEER_PORT]:k6(t.port),[tn.SEMATTRS_DB_USER]:t.user}}Te.getSemanticAttributesFromConnection=V6;function KGe(t){return{[tn.SEMATTRS_DB_SYSTEM]:tn.DBSYSTEMVALUES_POSTGRESQL,[tn.SEMATTRS_DB_NAME]:t.database,[tn.SEMATTRS_DB_CONNECTION_STRING]:FC(t),[tn.SEMATTRS_NET_PEER_NAME]:t.host,[tn.SEMATTRS_NET_PEER_PORT]:k6(t.port),[tn.SEMATTRS_DB_USER]:t.user,[gg.AttributeNames.IDLE_TIMEOUT_MILLIS]:t.idleTimeoutMillis,[gg.AttributeNames.MAX_CLIENT]:t.maxClient}}Te.getSemanticAttributesFromPool=KGe;function WGe(t){return t.requireParentSpan===!0&&fi.trace.getSpan(fi.context.active())===void 0}Te.shouldSkipInstrumentation=WGe;function zGe(t,e,n){let{connectionParameters:r}=this,o=r.database,s=U6(o,n),i=t.startSpan(s,{kind:fi.SpanKind.CLIENT,attributes:V6(r)});if(!n)return i;if(n.text&&i.setAttribute(tn.SEMATTRS_DB_STATEMENT,n.text),e.enhancedDatabaseReporting&&Array.isArray(n.values))try{let a=n.values.map(c=>c==null?"null":c instanceof Buffer?c.toString():typeof c=="object"?typeof c.toPostgres=="function"?c.toPostgres():JSON.stringify(c):c.toString());i.setAttribute(gg.AttributeNames.PG_VALUES,a)}catch(a){fi.diag.error("failed to stringify ",n.values,a)}return typeof n.name=="string"&&i.setAttribute(gg.AttributeNames.PG_PLAN,n.name),i}Te.handleConfigQuery=zGe;function B6(t,e,n){typeof t.responseHook=="function"&&(0,YGe.safeExecuteInTheMiddle)(()=>{t.responseHook(e,{data:n})},r=>{r&&fi.diag.error("Error running response hook",r)},!0)}Te.handleExecutionResult=B6;function XGe(t,e,n,r,o){return function(i,a){i?(Object.prototype.hasOwnProperty.call(i,"code")&&(r[tn.ATTR_ERROR_TYPE]=i.code),e.setStatus({code:fi.SpanStatusCode.ERROR,message:i.message})):B6(t,e,a),o(),e.end(),n.call(this,i,a)}}Te.patchCallback=XGe;function JGe(t){let e="";return e+=(t?.host?`${t.host}`:"unknown_host")+":",e+=(t?.port?`${t.port}`:"unknown_port")+"/",e+=t?.database?`${t.database}`:"unknown_database",e.trim()}Te.getPoolName=JGe;function ZGe(t,e,n,r,o){let s=e.totalCount,i=e.waitingCount,a=e.idleCount,c=s-a;return n.add(c-o.used,{[ba.ATTR_DB_CLIENT_CONNECTION_STATE]:ba.DB_CLIENT_CONNECTION_STATE_VALUE_USED,[ba.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:t}),n.add(a-o.idle,{[ba.ATTR_DB_CLIENT_CONNECTION_STATE]:ba.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE,[ba.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:t}),r.add(i-o.pending,{[ba.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:t}),{used:c,idle:a,pending:i}}Te.updateCounter=ZGe;function QGe(t,e){return function(r,o,s){r&&t.setStatus({code:fi.SpanStatusCode.ERROR,message:r.message}),t.end(),e.call(this,r,o,s)}}Te.patchCallbackPGPool=QGe;function eHe(t,e){return function(r){r&&t.setStatus({code:fi.SpanStatusCode.ERROR,message:r.message}),t.end(),e.apply(this,arguments)}}Te.patchClientConnectCallback=eHe;function tHe(t){return typeof t=="object"&&t!==null&&"message"in t?String(t.message):void 0}Te.getErrorMessage=tHe;function nHe(t){var e;return typeof t=="object"&&typeof((e=t)===null||e===void 0?void 0:e.text)=="string"}Te.isObjectWithTextString=nHe});var H6=m(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.PACKAGE_NAME=Vu.PACKAGE_VERSION=void 0;Vu.PACKAGE_VERSION="0.51.1";Vu.PACKAGE_NAME="@opentelemetry/instrumentation-pg"});var K6=m(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});Ag.PgInstrumentation=void 0;var dr=fe(),Ie=(x(),b(B)),$6=x6(),lt=G6(),F6=LC(),j6=H6(),q6=$C(),hg=Se(),mi=(ve(),b(ot)),Ma=HC();function Tg(t){return t[Symbol.toStringTag]==="Module"?t.default:t}var jC=class extends dr.InstrumentationBase{constructor(e={}){super(j6.PACKAGE_NAME,j6.PACKAGE_VERSION,e),this._connectionsCounter={used:0,idle:0,pending:0}}_updateMetricInstruments(){this._operationDuration=this.meter.createHistogram(Ma.METRIC_DB_CLIENT_OPERATION_DURATION,{description:"Duration of database client operations.",unit:"s",valueType:Ie.ValueType.DOUBLE,advice:{explicitBucketBoundaries:[.001,.005,.01,.05,.1,.5,1,5,10]}}),this._connectionsCounter={idle:0,pending:0,used:0},this._connectionsCount=this.meter.createUpDownCounter(Ma.METRIC_DB_CLIENT_CONNECTION_COUNT,{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"}),this._connectionPendingRequests=this.meter.createUpDownCounter(Ma.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS,{description:"The number of current pending requests for an open connection.",unit:"{connection}"})}init(){let e=[">=8.0.3 <9"],n=new dr.InstrumentationNodeModuleFile("pg/lib/native/client.js",e,this._patchPgClient.bind(this),this._unpatchPgClient.bind(this)),r=new dr.InstrumentationNodeModuleFile("pg/lib/client.js",e,this._patchPgClient.bind(this),this._unpatchPgClient.bind(this)),o=new dr.InstrumentationNodeModuleDefinition("pg",e,i=>{let a=Tg(i);return this._patchPgClient(a.Client),i},i=>{let a=Tg(i);return this._unpatchPgClient(a.Client),i},[r,n]),s=new dr.InstrumentationNodeModuleDefinition("pg-pool",[">=2.0.0 <4"],i=>((0,dr.isWrapped)(i.prototype.connect)&&this._unwrap(i.prototype,"connect"),this._wrap(i.prototype,"connect",this._getPoolConnectPatch()),i),i=>{(0,dr.isWrapped)(i.prototype.connect)&&this._unwrap(i.prototype,"connect")});return[o,s]}_patchPgClient(e){if(!e)return;let n=Tg(e);return(0,dr.isWrapped)(n.prototype.query)&&this._unwrap(n.prototype,"query"),(0,dr.isWrapped)(n.prototype.connect)&&this._unwrap(n.prototype,"connect"),this._wrap(n.prototype,"query",this._getClientQueryPatch()),this._wrap(n.prototype,"connect",this._getClientConnectPatch()),e}_unpatchPgClient(e){let n=Tg(e);return(0,dr.isWrapped)(n.prototype.query)&&this._unwrap(n.prototype,"query"),(0,dr.isWrapped)(n.prototype.connect)&&this._unwrap(n.prototype,"connect"),e}_getClientConnectPatch(){let e=this;return n=>function(o){if(lt.shouldSkipInstrumentation(e.getConfig()))return n.call(this,o);let s=e.tracer.startSpan(q6.SpanNames.CONNECT,{kind:Ie.SpanKind.CLIENT,attributes:lt.getSemanticAttributesFromConnection(this)});if(o){let a=Ie.trace.getSpan(Ie.context.active());o=lt.patchClientConnectCallback(s,o),a&&(o=Ie.context.bind(Ie.context.active(),o))}let i=Ie.context.with(Ie.trace.setSpan(Ie.context.active(),s),()=>n.call(this,o));return Y6(s,i)}}recordOperationDuration(e,n){let r={};[mi.SEMATTRS_DB_SYSTEM,Ma.ATTR_DB_NAMESPACE,mi.ATTR_ERROR_TYPE,mi.ATTR_SERVER_PORT,mi.ATTR_SERVER_ADDRESS,Ma.ATTR_DB_OPERATION_NAME].forEach(i=>{i in e&&(r[i]=e[i])});let s=(0,hg.hrTimeToMilliseconds)((0,hg.hrTimeDuration)(n,(0,hg.hrTime)()))/1e3;this._operationDuration.record(s,r)}_getClientQueryPatch(){let e=this;return n=>(this._diag.debug("Patching pg.Client.prototype.query"),function(...o){if(lt.shouldSkipInstrumentation(e.getConfig()))return n.apply(this,o);let s=(0,hg.hrTime)(),i=o[0],a=typeof i=="string",c=lt.isObjectWithTextString(i),u=a?{text:i,values:Array.isArray(o[1])?o[1]:void 0}:c?i:void 0,l={[mi.SEMATTRS_DB_SYSTEM]:mi.DBSYSTEMVALUES_POSTGRESQL,[Ma.ATTR_DB_NAMESPACE]:this.database,[mi.ATTR_SERVER_PORT]:this.connectionParameters.port,[mi.ATTR_SERVER_ADDRESS]:this.connectionParameters.host};u?.text&&(l[Ma.ATTR_DB_OPERATION_NAME]=lt.parseNormalizedOperationName(u?.text));let d=()=>{e.recordOperationDuration(l,s)},p=e.getConfig(),_=lt.handleConfigQuery.call(this,e.tracer,p,u);if(p.addSqlCommenterCommentToQueries&&(a?o[0]=(0,F6.addSqlCommenterComment)(_,i):c&&!("name"in i)&&(o[0]=Object.assign(Object.assign({},i),{text:(0,F6.addSqlCommenterComment)(_,i.text)}))),o.length>0){let S=Ie.trace.getSpan(Ie.context.active());if(typeof o[o.length-1]=="function")o[o.length-1]=lt.patchCallback(p,_,o[o.length-1],l,d),S&&(o[o.length-1]=Ie.context.bind(Ie.context.active(),o[o.length-1]));else if(typeof u?.callback=="function"){let h=lt.patchCallback(e.getConfig(),_,u.callback,l,d);S&&(h=Ie.context.bind(Ie.context.active(),h)),o[0].callback=h}}let{requestHook:f}=p;typeof f=="function"&&u&&(0,dr.safeExecuteInTheMiddle)(()=>{let{database:S,host:h,port:R,user:A}=this.connectionParameters;f(_,{connection:{database:S,host:h,port:R,user:A},query:{text:u.text,values:u.values,name:u.name}})},S=>{S&&e._diag.error("Error running query hook",S)},!0);let E;try{E=n.apply(this,o)}catch(S){throw _.setStatus({code:Ie.SpanStatusCode.ERROR,message:lt.getErrorMessage(S)}),_.end(),S}return E instanceof Promise?E.then(S=>new Promise(h=>{lt.handleExecutionResult(e.getConfig(),_,S),d(),_.end(),h(S)})).catch(S=>new Promise((h,R)=>{_.setStatus({code:Ie.SpanStatusCode.ERROR,message:S.message}),d(),_.end(),R(S)})):E})}_setPoolConnectEventListeners(e){if(e[$6.EVENT_LISTENERS_SET])return;let n=lt.getPoolName(e.options);e.on("connect",()=>{this._connectionsCounter=lt.updateCounter(n,e,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),e.on("acquire",()=>{this._connectionsCounter=lt.updateCounter(n,e,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),e.on("remove",()=>{this._connectionsCounter=lt.updateCounter(n,e,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),e.on("release",()=>{this._connectionsCounter=lt.updateCounter(n,e,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),e[$6.EVENT_LISTENERS_SET]=!0}_getPoolConnectPatch(){let e=this;return n=>function(o){if(lt.shouldSkipInstrumentation(e.getConfig()))return n.call(this,o);let s=e.tracer.startSpan(q6.SpanNames.POOL_CONNECT,{kind:Ie.SpanKind.CLIENT,attributes:lt.getSemanticAttributesFromPool(this.options)});if(e._setPoolConnectEventListeners(this),o){let a=Ie.trace.getSpan(Ie.context.active());o=lt.patchCallbackPGPool(s,o),a&&(o=Ie.context.bind(Ie.context.active(),o))}let i=Ie.context.with(Ie.trace.setSpan(Ie.context.active(),s),()=>n.call(this,o));return Y6(s,i)}}};Ag.PgInstrumentation=jC;function Y6(t,e){if(!(e instanceof Promise))return e;let n=e;return Ie.context.bind(Ie.context.active(),n.then(r=>(t.end(),r)).catch(r=>(t.setStatus({code:Ie.SpanStatusCode.ERROR,message:lt.getErrorMessage(r)}),t.end(),Promise.reject(r))))}});var z6=m(W6=>{"use strict";Object.defineProperty(W6,"__esModule",{value:!0})});var X6=m(Qo=>{"use strict";var rHe=Qo&&Qo.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),qC=Qo&&Qo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&rHe(e,t,n)};Object.defineProperty(Qo,"__esModule",{value:!0});qC(K6(),Qo);qC(z6(),Qo);qC(GC(),Qo)});var _J=m(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.PACKAGE_NAME=Bu.PACKAGE_VERSION=void 0;Bu.PACKAGE_VERSION="0.45.2";Bu.PACKAGE_NAME="@opentelemetry/instrumentation-hapi"});var JC=m(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.HapiLifecycleMethodNames=Eo.HapiLayerType=Eo.handlerPatched=Eo.HapiComponentName=void 0;Eo.HapiComponentName="@hapi/hapi";Eo.handlerPatched=Symbol("hapi-handler-patched");Eo.HapiLayerType={ROUTER:"router",PLUGIN:"plugin",EXT:"server.ext"};Eo.HapiLifecycleMethodNames=new Set(["onPreAuth","onCredentials","onPostAuth","onPreHandler","onPostHandler","onPreResponse","onRequest"])});var ZC=m(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});Ep.AttributeNames=void 0;var EHe;(function(t){t.HAPI_TYPE="hapi.type",t.PLUGIN_NAME="hapi.plugin.name",t.EXT_TYPE="server.ext.type"})(EHe=Ep.AttributeNames||(Ep.AttributeNames={}))});var fJ=m(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.getPluginFromInput=dt.getExtMetadata=dt.getRouteMetadata=dt.isPatchableExtMethod=dt.isDirectExtInput=dt.isLifecycleExtEventObj=dt.isLifecycleExtType=dt.getPluginName=void 0;var yg=(ve(),b(ot)),Sp=JC(),Ei=ZC();function SHe(t){return t.name?t.name:t.pkg.name}dt.getPluginName=SHe;var gHe=t=>typeof t=="string"&&Sp.HapiLifecycleMethodNames.has(t);dt.isLifecycleExtType=gHe;var hHe=t=>{var e;let n=(e=t)===null||e===void 0?void 0:e.type;return n!==void 0&&(0,dt.isLifecycleExtType)(n)};dt.isLifecycleExtEventObj=hHe;var THe=t=>Array.isArray(t)&&t.length<=3&&(0,dt.isLifecycleExtType)(t[0])&&typeof t[1]=="function";dt.isDirectExtInput=THe;var AHe=t=>!Array.isArray(t);dt.isPatchableExtMethod=AHe;var RHe=(t,e)=>e?{attributes:{[yg.SEMATTRS_HTTP_ROUTE]:t.path,[yg.SEMATTRS_HTTP_METHOD]:t.method,[Ei.AttributeNames.HAPI_TYPE]:Sp.HapiLayerType.PLUGIN,[Ei.AttributeNames.PLUGIN_NAME]:e},name:`${e}: route - ${t.path}`}:{attributes:{[yg.SEMATTRS_HTTP_ROUTE]:t.path,[yg.SEMATTRS_HTTP_METHOD]:t.method,[Ei.AttributeNames.HAPI_TYPE]:Sp.HapiLayerType.ROUTER},name:`route - ${t.path}`};dt.getRouteMetadata=RHe;var yHe=(t,e)=>e?{attributes:{[Ei.AttributeNames.EXT_TYPE]:t,[Ei.AttributeNames.HAPI_TYPE]:Sp.HapiLayerType.EXT,[Ei.AttributeNames.PLUGIN_NAME]:e},name:`${e}: ext - ${t}`}:{attributes:{[Ei.AttributeNames.EXT_TYPE]:t,[Ei.AttributeNames.HAPI_TYPE]:Sp.HapiLayerType.EXT},name:`ext - ${t}`};dt.getExtMetadata=yHe;var OHe=t=>"plugin"in t?"plugin"in t.plugin?t.plugin.plugin:t.plugin:t;dt.getPluginFromInput=OHe});var SJ=m(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});Ng.HapiInstrumentation=void 0;var Vn=(x(),b(B)),mJ=Se(),Og=fe(),EJ=_J(),gp=JC(),ts=fJ(),QC=class extends Og.InstrumentationBase{constructor(e={}){super(EJ.PACKAGE_NAME,EJ.PACKAGE_VERSION,e)}init(){return new Og.InstrumentationNodeModuleDefinition(gp.HapiComponentName,[">=17.0.0 <22"],e=>{let n=e[Symbol.toStringTag]==="Module"?e.default:e;return(0,Og.isWrapped)(n.server)||this._wrap(n,"server",this._getServerPatch.bind(this)),(0,Og.isWrapped)(n.Server)||this._wrap(n,"Server",this._getServerPatch.bind(this)),n},e=>{let n=e[Symbol.toStringTag]==="Module"?e.default:e;this._massUnwrap([n],["server","Server"])})}_getServerPatch(e){let n=this,r=this;return function(s){let i=e.apply(this,[s]);return r._wrap(i,"route",a=>n._getServerRoutePatch.bind(n)(a)),r._wrap(i,"ext",a=>n._getServerExtPatch.bind(n)(a)),r._wrap(i,"register",n._getServerRegisterPatch.bind(n)),i}}_getServerRegisterPatch(e){let n=this;return function(o,s){if(Array.isArray(o))for(let i of o){let a=(0,ts.getPluginFromInput)(i);n._wrapRegisterHandler(a)}else{let i=(0,ts.getPluginFromInput)(o);n._wrapRegisterHandler(i)}return e.apply(this,[o,s])}}_getServerExtPatch(e,n){let r=this;return function(...s){if(Array.isArray(s[0])){let i=s[0];for(let a=0;a<i.length;a++){let c=i[a];if((0,ts.isLifecycleExtType)(c.type)){let u=c,l=r._wrapExtMethods(u.method,c.type,n);u.method=l,i[a]=u}}return e.apply(this,s)}else if((0,ts.isDirectExtInput)(s)){let i=s,a=i[1],c=r._wrapExtMethods(a,i[0],n);return e.apply(this,[i[0],c,i[2]])}else if((0,ts.isLifecycleExtEventObj)(s[0])){let i=s[0],a=r._wrapExtMethods(i.method,i.type,n);return i.method=a,e.call(this,i)}return e.apply(this,s)}}_getServerRoutePatch(e,n){let r=this;return function(o){if(Array.isArray(o))for(let s=0;s<o.length;s++){let i=r._wrapRouteHandler.call(r,o[s],n);o[s]=i}else o=r._wrapRouteHandler.call(r,o,n);return e.apply(this,[o])}}_wrapRegisterHandler(e){let n=this,r=(0,ts.getPluginName)(e),o=e.register,s=this,i=function(a,c){return s._wrap(a,"route",u=>n._getServerRoutePatch.bind(n)(u,r)),s._wrap(a,"ext",u=>n._getServerExtPatch.bind(n)(u,r)),o.call(this,a,c)};e.register=i}_wrapExtMethods(e,n,r){let o=this;if(e instanceof Array){for(let s=0;s<e.length;s++)e[s]=o._wrapExtMethods(e[s],n);return e}else if((0,ts.isPatchableExtMethod)(e))return e[gp.handlerPatched]===!0?e:(e[gp.handlerPatched]=!0,async function(...i){if(Vn.trace.getSpan(Vn.context.active())===void 0)return await e.apply(this,i);let a=(0,ts.getExtMetadata)(n,r),c=o.tracer.startSpan(a.name,{attributes:a.attributes});try{return await Vn.context.with(Vn.trace.setSpan(Vn.context.active(),c),e,void 0,...i)}catch(u){throw c.recordException(u),c.setStatus({code:Vn.SpanStatusCode.ERROR,message:u.message}),u}finally{c.end()}});return e}_wrapRouteHandler(e,n){var r;let o=this;if(e[gp.handlerPatched]===!0)return e;e[gp.handlerPatched]=!0;let s=i=>async function(...a){if(Vn.trace.getSpan(Vn.context.active())===void 0)return await i.call(this,...a);let c=(0,mJ.getRPCMetadata)(Vn.context.active());c?.type===mJ.RPCType.HTTP&&(c.route=e.path);let u=(0,ts.getRouteMetadata)(e,n),l=o.tracer.startSpan(u.name,{attributes:u.attributes});try{return await Vn.context.with(Vn.trace.setSpan(Vn.context.active(),l),()=>i.call(this,...a))}catch(d){throw l.recordException(d),l.setStatus({code:Vn.SpanStatusCode.ERROR,message:d.message}),d}finally{l.end()}};if(typeof e.handler=="function")e.handler=s(e.handler);else if(typeof e.options=="function"){let i=e.options;e.options=function(a){let c=i(a);return typeof c.handler=="function"&&(c.handler=s(c.handler)),c}}else typeof((r=e.options)===null||r===void 0?void 0:r.handler)=="function"&&(e.options.handler=s(e.options.handler));return e}};Ng.HapiInstrumentation=QC});var hJ=m(Si=>{"use strict";var NHe=Si&&Si.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gJ=Si&&Si.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&NHe(e,t,n)};Object.defineProperty(Si,"__esModule",{value:!0});gJ(SJ(),Si);gJ(ZC(),Si)});var Cg=m(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});hp.KoaLayerType=void 0;var vHe;(function(t){t.ROUTER="router",t.MIDDLEWARE="middleware"})(vHe=hp.KoaLayerType||(hp.KoaLayerType={}))});var OJ=m(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});Gu.PACKAGE_NAME=Gu.PACKAGE_VERSION=void 0;Gu.PACKAGE_VERSION="0.47.1";Gu.PACKAGE_NAME="@opentelemetry/instrumentation-koa"});var ev=m(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});Tp.AttributeNames=void 0;var IHe;(function(t){t.KOA_TYPE="koa.type",t.KOA_NAME="koa.name"})(IHe=Tp.AttributeNames||(Tp.AttributeNames={}))});var CJ=m(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});Hu.isLayerIgnored=Hu.getMiddlewareMetadata=void 0;var NJ=Cg(),vg=ev(),PHe=(ve(),b(ot)),bHe=(t,e,n,r)=>{var o;return n?{attributes:{[vg.AttributeNames.KOA_NAME]:r?.toString(),[vg.AttributeNames.KOA_TYPE]:NJ.KoaLayerType.ROUTER,[PHe.SEMATTRS_HTTP_ROUTE]:r?.toString()},name:t._matchedRouteName||`router - ${r}`}:{attributes:{[vg.AttributeNames.KOA_NAME]:(o=e.name)!==null&&o!==void 0?o:"middleware",[vg.AttributeNames.KOA_TYPE]:NJ.KoaLayerType.MIDDLEWARE},name:`middleware - ${e.name}`}};Hu.getMiddlewareMetadata=bHe;var MHe=(t,e)=>{var n;return!!(Array.isArray(e?.ignoreLayersType)&&(!((n=e?.ignoreLayersType)===null||n===void 0)&&n.includes(t)))};Hu.isLayerIgnored=MHe});var vJ=m(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});Ig.kLayerPatched=void 0;Ig.kLayerPatched=Symbol("koa-layer-patched")});var xJ=m(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});Pg.KoaInstrumentation=void 0;var So=(x(),b(B)),Ap=fe(),IJ=Cg(),PJ=OJ(),bJ=CJ(),MJ=Se(),LJ=vJ(),tv=class extends Ap.InstrumentationBase{constructor(e={}){super(PJ.PACKAGE_NAME,PJ.PACKAGE_VERSION,e)}init(){return new Ap.InstrumentationNodeModuleDefinition("koa",[">=2.0.0 <3"],e=>{let n=e[Symbol.toStringTag]==="Module"?e.default:e;return n==null?n:((0,Ap.isWrapped)(n.prototype.use)&&this._unwrap(n.prototype,"use"),this._wrap(n.prototype,"use",this._getKoaUsePatch.bind(this)),e)},e=>{let n=e[Symbol.toStringTag]==="Module"?e.default:e;(0,Ap.isWrapped)(n.prototype.use)&&this._unwrap(n.prototype,"use")})}_getKoaUsePatch(e){let n=this;return function(o){let s;return o.router?s=n._patchRouterDispatch(o):s=n._patchLayer(o,!1),e.apply(this,[s])}}_patchRouterDispatch(e){var n;So.diag.debug("Patching @koa/router dispatch");let r=e.router,o=(n=r?.stack)!==null&&n!==void 0?n:[];for(let s of o){let i=s.path,a=s.stack;for(let c=0;c<a.length;c++){let u=a[c];a[c]=this._patchLayer(u,!0,i)}}return e}_patchLayer(e,n,r){let o=n?IJ.KoaLayerType.ROUTER:IJ.KoaLayerType.MIDDLEWARE;return e[LJ.kLayerPatched]===!0||(0,bJ.isLayerIgnored)(o,this.getConfig())?e:e.constructor.name==="GeneratorFunction"||e.constructor.name==="AsyncGeneratorFunction"?(So.diag.debug("ignoring generator-based Koa middleware layer"),e):(e[LJ.kLayerPatched]=!0,So.diag.debug("patching Koa middleware layer"),async(s,i)=>{if(So.trace.getSpan(So.context.active())===void 0)return e(s,i);let c=(0,bJ.getMiddlewareMetadata)(s,e,n,r),u=this.tracer.startSpan(c.name,{attributes:c.attributes}),l=(0,MJ.getRPCMetadata)(So.context.active());l?.type===MJ.RPCType.HTTP&&s._matchedRoute&&(l.route=s._matchedRoute.toString());let{requestHook:d}=this.getConfig();d&&(0,Ap.safeExecuteInTheMiddle)(()=>d(u,{context:s,middlewareLayer:e,layerType:o}),_=>{_&&So.diag.error("koa instrumentation: request hook failed",_)},!0);let p=So.trace.setSpan(So.context.active(),u);return So.context.with(p,async()=>{try{return await e(s,i)}catch(_){throw u.recordException(_),_}finally{u.end()}})})}};Pg.KoaInstrumentation=tv});var DJ=m(ns=>{"use strict";var LHe=ns&&ns.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),nv=ns&&ns.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&LHe(e,t,n)};Object.defineProperty(ns,"__esModule",{value:!0});nv(xJ(),ns);nv(Cg(),ns);nv(ev(),ns)});var rv=m(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.ConnectNames=Dr.ConnectTypes=Dr.AttributeNames=void 0;var DHe;(function(t){t.CONNECT_TYPE="connect.type",t.CONNECT_NAME="connect.name"})(DHe=Dr.AttributeNames||(Dr.AttributeNames={}));var UHe;(function(t){t.MIDDLEWARE="middleware",t.REQUEST_HANDLER="request_handler"})(UHe=Dr.ConnectTypes||(Dr.ConnectTypes={}));var wHe;(function(t){t.MIDDLEWARE="middleware",t.REQUEST_HANDLER="request handler"})(wHe=Dr.ConnectNames||(Dr.ConnectNames={}))});var BJ=m($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.PACKAGE_NAME=$u.PACKAGE_VERSION=void 0;$u.PACKAGE_VERSION="0.43.1";$u.PACKAGE_NAME="@opentelemetry/instrumentation-connect"});var GJ=m(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});bg._LAYERS_STORE_PROPERTY=void 0;bg._LAYERS_STORE_PROPERTY=Symbol("opentelemetry.instrumentation-connect.request-route-stack")});var HJ=m(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.generateRoute=hi.replaceCurrentStackRoute=hi.addNewStackLayer=void 0;var kHe=(x(),b(B)),gi=GJ(),VHe=t=>{Array.isArray(t[gi._LAYERS_STORE_PROPERTY])===!1&&Object.defineProperty(t,gi._LAYERS_STORE_PROPERTY,{enumerable:!1,value:[]}),t[gi._LAYERS_STORE_PROPERTY].push("/");let e=t[gi._LAYERS_STORE_PROPERTY].length;return()=>{e===t[gi._LAYERS_STORE_PROPERTY].length?t[gi._LAYERS_STORE_PROPERTY].pop():kHe.diag.warn("Connect: Trying to pop the stack multiple time")}};hi.addNewStackLayer=VHe;var BHe=(t,e)=>{e&&t[gi._LAYERS_STORE_PROPERTY].splice(-1,1,e)};hi.replaceCurrentStackRoute=BHe;var GHe=t=>t[gi._LAYERS_STORE_PROPERTY].reduce((e,n)=>e.replace(/\/+$/,"")+n);hi.generateRoute=GHe});var jJ=m(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.ConnectInstrumentation=Ti.ANONYMOUS_NAME=void 0;var HHe=(x(),b(B)),$J=Se(),Fu=rv(),FJ=BJ(),Mg=fe(),$He=(ve(),b(ot)),ov=HJ();Ti.ANONYMOUS_NAME="anonymous";var sv=class extends Mg.InstrumentationBase{constructor(e={}){super(FJ.PACKAGE_NAME,FJ.PACKAGE_VERSION,e)}init(){return[new Mg.InstrumentationNodeModuleDefinition("connect",[">=3.0.0 <4"],e=>this._patchConstructor(e))]}_patchApp(e){(0,Mg.isWrapped)(e.use)||this._wrap(e,"use",this._patchUse.bind(this)),(0,Mg.isWrapped)(e.handle)||this._wrap(e,"handle",this._patchHandle.bind(this))}_patchConstructor(e){let n=this;return function(...r){let o=e.apply(this,r);return n._patchApp(o),o}}_patchNext(e,n){return function(o){let s=e.apply(this,[o]);return n(),s}}_startSpan(e,n){let r,o,s;e?(r=Fu.ConnectTypes.REQUEST_HANDLER,s=Fu.ConnectNames.REQUEST_HANDLER,o=e):(r=Fu.ConnectTypes.MIDDLEWARE,s=Fu.ConnectNames.MIDDLEWARE,o=n.name||Ti.ANONYMOUS_NAME);let i=`${s} - ${o}`,a={attributes:{[$He.SEMATTRS_HTTP_ROUTE]:e.length>0?e:"/",[Fu.AttributeNames.CONNECT_TYPE]:r,[Fu.AttributeNames.CONNECT_NAME]:o}};return this.tracer.startSpan(i,a)}_patchMiddleware(e,n){let r=this,o=n.length===4;function s(){if(!r.isEnabled())return n.apply(this,arguments);let[i,a,c]=o?[1,2,3]:[0,1,2],u=arguments[i],l=arguments[a],d=arguments[c];(0,ov.replaceCurrentStackRoute)(u,e);let p=(0,$J.getRPCMetadata)(HHe.context.active());e&&p?.type===$J.RPCType.HTTP&&(p.route=(0,ov.generateRoute)(u));let _="";e?_=`request handler - ${e}`:_=`middleware - ${n.name||Ti.ANONYMOUS_NAME}`;let f=r._startSpan(e,n);r._diag.debug("start span",_);let E=!1;function S(){E?r._diag.debug(`span ${f.name} - already finished`):(E=!0,r._diag.debug(`finishing span ${f.name}`),f.end()),l.removeListener("close",S)}return l.addListener("close",S),arguments[c]=r._patchNext(d,S),n.apply(this,arguments)}return Object.defineProperty(s,"length",{value:n.length,writable:!1,configurable:!0}),s}_patchUse(e){let n=this;return function(...r){let o=r[r.length-1],s=r[r.length-2]||"";return r[r.length-1]=n._patchMiddleware(s,o),e.apply(this,r)}}_patchHandle(e){let n=this;return function(){let[r,o]=[0,2],s=arguments[r],i=arguments[o],a=(0,ov.addNewStackLayer)(s);return typeof i=="function"&&(arguments[o]=n._patchOut(i,a)),e.apply(this,arguments)}}_patchOut(e,n){return function(...o){return n(),Reflect.apply(e,this,o)}}};Ti.ConnectInstrumentation=sv});var YJ=m(Ai=>{"use strict";var FHe=Ai&&Ai.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),qJ=Ai&&Ai.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&FHe(e,t,n)};Object.defineProperty(Ai,"__esModule",{value:!0});qJ(rv(),Ai);qJ(jJ(),Ai)});var JJ=m(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});ju.once=ju.getSpanName=void 0;function qHe(t,e,n,r){return t==="execBulkLoad"&&r&&e?`${t} ${r} ${e}`:t==="callProcedure"?e?`${t} ${n} ${e}`:`${t} ${n}`:e?`${t} ${e}`:`${t}`}ju.getSpanName=qHe;var YHe=t=>{let e=!1;return(...n)=>{if(!e)return e=!0,t(...n)}};ju.once=YHe});var ZJ=m(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.PACKAGE_NAME=qu.PACKAGE_VERSION=void 0;qu.PACKAGE_VERSION="0.18.1";qu.PACKAGE_NAME="@opentelemetry/instrumentation-tedious"});var rZ=m(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});Ug.TediousInstrumentation=void 0;var Rp=(x(),b(B)),KHe=require("events"),Lg=fe(),Ri=(ve(),b(ot)),QJ=JJ(),eZ=ZJ(),nZ=Symbol("opentelemetry.instrumentation-tedious.current-database"),tZ=["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"];function xg(t){Object.defineProperty(this,nZ,{value:t,writable:!0})}var Dg=class t extends Lg.InstrumentationBase{constructor(e={}){super(eZ.PACKAGE_NAME,eZ.PACKAGE_VERSION,e)}init(){return[new Lg.InstrumentationNodeModuleDefinition(t.COMPONENT,[">=1.11.0 <20"],e=>{let n=e.Connection.prototype;for(let r of tZ)(0,Lg.isWrapped)(n[r])&&this._unwrap(n,r),this._wrap(n,r,this._patchQuery(r));return(0,Lg.isWrapped)(n.connect)&&this._unwrap(n,"connect"),this._wrap(n,"connect",this._patchConnect),e},e=>{if(e===void 0)return;let n=e.Connection.prototype;for(let r of tZ)this._unwrap(n,r);this._unwrap(n,"connect")})]}_patchConnect(e){return function(){var r,o;return xg.call(this,(o=(r=this.config)===null||r===void 0?void 0:r.options)===null||o===void 0?void 0:o.database),this.removeListener("databaseChange",xg),this.on("databaseChange",xg),this.once("end",()=>{this.removeListener("databaseChange",xg)}),e.apply(this,arguments)}}_patchQuery(e){return n=>{let r=this;function o(s){var i,a,c,u,l,d,p,_;if(!(s instanceof KHe.EventEmitter))return r._diag.warn(`Unexpected invocation of patched ${e} method. Span not recorded`),n.apply(this,arguments);let f=0,E=0,S=()=>E++,h=()=>f++,R=this[nZ],A=(M=>{var I,J;return M.sqlTextOrProcedure==="sp_prepare"&&(!((J=(I=M.parametersByName)===null||I===void 0?void 0:I.stmt)===null||J===void 0)&&J.value)?M.parametersByName.stmt.value:M.sqlTextOrProcedure})(s),O=r.tracer.startSpan((0,QJ.getSpanName)(e,R,A,s.table),{kind:Rp.SpanKind.CLIENT,attributes:{[Ri.SEMATTRS_DB_SYSTEM]:Ri.DBSYSTEMVALUES_MSSQL,[Ri.SEMATTRS_DB_NAME]:R,[Ri.SEMATTRS_NET_PEER_PORT]:(a=(i=this.config)===null||i===void 0?void 0:i.options)===null||a===void 0?void 0:a.port,[Ri.SEMATTRS_NET_PEER_NAME]:(c=this.config)===null||c===void 0?void 0:c.server,[Ri.SEMATTRS_DB_USER]:(l=(u=this.config)===null||u===void 0?void 0:u.userName)!==null&&l!==void 0?l:(_=(p=(d=this.config)===null||d===void 0?void 0:d.authentication)===null||p===void 0?void 0:p.options)===null||_===void 0?void 0:_.userName,[Ri.SEMATTRS_DB_STATEMENT]:A,[Ri.SEMATTRS_DB_SQL_TABLE]:s.table}}),y=(0,QJ.once)(M=>{s.removeListener("done",S),s.removeListener("doneInProc",S),s.removeListener("doneProc",h),s.removeListener("error",y),this.removeListener("end",y),O.setAttribute("tedious.procedure_count",f),O.setAttribute("tedious.statement_count",E),M&&O.setStatus({code:Rp.SpanStatusCode.ERROR,message:M.message}),O.end()});return s.on("done",S),s.on("doneInProc",S),s.on("doneProc",h),s.once("error",y),this.on("end",y),typeof s.callback=="function"?r._wrap(s,"callback",r._patchCallbackQuery(y)):r._diag.error("Expected request.callback to be a function"),Rp.context.with(Rp.trace.setSpan(Rp.context.active(),O),n,this,...arguments)}return Object.defineProperty(o,"length",{value:n.length,writable:!1}),o}}_patchCallbackQuery(e){return n=>function(r,o,s){return e(r),n.apply(this,arguments)}}};Ug.TediousInstrumentation=Dg;Dg.COMPONENT="tedious"});var sZ=m(oZ=>{"use strict";Object.defineProperty(oZ,"__esModule",{value:!0})});var aZ=m(yi=>{"use strict";var WHe=yi&&yi.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),iZ=yi&&yi.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WHe(e,t,n)};Object.defineProperty(yi,"__esModule",{value:!0});iZ(rZ(),yi);iZ(sZ(),yi)});var pZ=m(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.PACKAGE_NAME=Yu.PACKAGE_VERSION=void 0;Yu.PACKAGE_VERSION="0.43.1";Yu.PACKAGE_NAME="@opentelemetry/instrumentation-generic-pool"});var fZ=m(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});wg.GenericPoolInstrumentation=void 0;var Ku=(x(),b(B)),La=fe(),_Z=pZ(),iv="generic-pool",av=class extends La.InstrumentationBase{constructor(e={}){super(_Z.PACKAGE_NAME,_Z.PACKAGE_VERSION,e),this._isDisabled=!1}init(){return[new La.InstrumentationNodeModuleDefinition(iv,[">=3.0.0 <4"],e=>{let n=e.Pool;return(0,La.isWrapped)(n.prototype.acquire)&&this._unwrap(n.prototype,"acquire"),this._wrap(n.prototype,"acquire",this._acquirePatcher.bind(this)),e},e=>{let n=e.Pool;return this._unwrap(n.prototype,"acquire"),e}),new La.InstrumentationNodeModuleDefinition(iv,[">=2.4.0 <3"],e=>{let n=e.Pool;return(0,La.isWrapped)(n.prototype.acquire)&&this._unwrap(n.prototype,"acquire"),this._wrap(n.prototype,"acquire",this._acquireWithCallbacksPatcher.bind(this)),e},e=>{let n=e.Pool;return this._unwrap(n.prototype,"acquire"),e}),new La.InstrumentationNodeModuleDefinition(iv,[">=2.0.0 <2.4"],e=>(this._isDisabled=!1,(0,La.isWrapped)(e.Pool)&&this._unwrap(e,"Pool"),this._wrap(e,"Pool",this._poolWrapper.bind(this)),e),e=>(this._isDisabled=!0,e))]}_acquirePatcher(e){let n=this;return function(...o){let s=Ku.context.active(),i=n.tracer.startSpan("generic-pool.acquire",{},s);return Ku.context.with(Ku.trace.setSpan(s,i),()=>e.call(this,...o).then(a=>(i.end(),a),a=>{throw i.recordException(a),i.end(),a}))}}_poolWrapper(e){let n=this;return function(){let o=e.apply(this,arguments);return n._wrap(o,"acquire",n._acquireWithCallbacksPatcher.bind(n)),o}}_acquireWithCallbacksPatcher(e){let n=this;return function(o,s){if(n._isDisabled)return e.call(this,o,s);let i=Ku.context.active(),a=n.tracer.startSpan("generic-pool.acquire",{},i);return Ku.context.with(Ku.trace.setSpan(i,a),()=>{e.call(this,(c,u)=>{if(a.end(),o)return o(c,u)},s)})}}};wg.GenericPoolInstrumentation=av});var mZ=m(xa=>{"use strict";var JHe=xa&&xa.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ZHe=xa&&xa.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&JHe(e,t,n)};Object.defineProperty(xa,"__esModule",{value:!0});ZHe(fZ(),xa)});var cv=m(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.DEFAULT_CONFIG=Da.EndOperation=void 0;var e$e;(function(t){t.AutoAck="auto ack",t.Ack="ack",t.AckAll="ackAll",t.Reject="reject",t.Nack="nack",t.NackAll="nackAll",t.ChannelClosed="channel closed",t.ChannelError="channel error",t.InstrumentationTimeout="instrumentation timeout"})(e$e=Da.EndOperation||(Da.EndOperation={}));Da.DEFAULT_CONFIG={consumeTimeoutMs:1e3*60,useLinksForConsume:!1}});var yZ=m(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.isConfirmChannelTracing=Ke.unmarkConfirmChannelTracing=Ke.markConfirmChannelTracing=Ke.getConnectionAttributesFromUrl=Ke.getConnectionAttributesFromServer=Ke.normalizeExchange=Ke.CONNECTION_ATTRIBUTES=Ke.CHANNEL_CONSUME_TIMEOUT_TIMER=Ke.CHANNEL_SPANS_NOT_ENDED=Ke.MESSAGE_STORED_SPAN=void 0;var uv=(x(),b(B)),rs=(ve(),b(ot));Ke.MESSAGE_STORED_SPAN=Symbol("opentelemetry.amqplib.message.stored-span");Ke.CHANNEL_SPANS_NOT_ENDED=Symbol("opentelemetry.amqplib.channel.spans-not-ended");Ke.CHANNEL_CONSUME_TIMEOUT_TIMER=Symbol("opentelemetry.amqplib.channel.consumer-timeout-timer");Ke.CONNECTION_ATTRIBUTES=Symbol("opentelemetry.amqplib.connection.attributes");var lv=(0,uv.createContextKey)("opentelemetry.amqplib.channel.is-confirm-channel"),t$e=t=>t!==""?t:"<default>";Ke.normalizeExchange=t$e;var n$e=t=>t.replace(/:[^:@/]*@/,":***@"),TZ=(t,e)=>t||(e==="AMQP"?5672:5671),AZ=t=>{let e=t||"amqp";return(e.endsWith(":")?e.substring(0,e.length-1):e).toUpperCase()},RZ=t=>t||"localhost",Wu=(t,e,n,r)=>n?{[e]:n}:(uv.diag.error(`amqplib instrumentation: could not extract connection attribute ${r} from user supplied url`,{url:t}),{}),r$e=t=>{var e,n;let r=(n=(e=t.serverProperties.product)===null||e===void 0?void 0:e.toLowerCase)===null||n===void 0?void 0:n.call(e);return r?{[rs.SEMATTRS_MESSAGING_SYSTEM]:r}:{}};Ke.getConnectionAttributesFromServer=r$e;var o$e=t=>{let e={[rs.SEMATTRS_MESSAGING_PROTOCOL_VERSION]:"0.9.1"};if(t=t||"amqp://localhost",typeof t=="object"){let n=t,r=AZ(n?.protocol);Object.assign(e,Object.assign({},Wu(t,rs.SEMATTRS_MESSAGING_PROTOCOL,r,"protocol")));let o=RZ(n?.hostname);Object.assign(e,Object.assign({},Wu(t,rs.SEMATTRS_NET_PEER_NAME,o,"hostname")));let s=TZ(n.port,r);Object.assign(e,Object.assign({},Wu(t,rs.SEMATTRS_NET_PEER_PORT,s,"port")))}else{let n=n$e(t);e[rs.SEMATTRS_MESSAGING_URL]=n;try{let r=new URL(n),o=AZ(r.protocol);Object.assign(e,Object.assign({},Wu(n,rs.SEMATTRS_MESSAGING_PROTOCOL,o,"protocol")));let s=RZ(r.hostname);Object.assign(e,Object.assign({},Wu(n,rs.SEMATTRS_NET_PEER_NAME,s,"hostname")));let i=TZ(r.port?parseInt(r.port):void 0,o);Object.assign(e,Object.assign({},Wu(n,rs.SEMATTRS_NET_PEER_PORT,i,"port")))}catch(r){uv.diag.error("amqplib instrumentation: error while extracting connection details from connection url",{censoredUrl:n,err:r})}}return e};Ke.getConnectionAttributesFromUrl=o$e;var s$e=t=>t.setValue(lv,!0);Ke.markConfirmChannelTracing=s$e;var i$e=t=>t.deleteValue(lv);Ke.unmarkConfirmChannelTracing=i$e;var a$e=t=>t.getValue(lv)===!0;Ke.isConfirmChannelTracing=a$e});var OZ=m(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.PACKAGE_NAME=zu.PACKAGE_VERSION=void 0;zu.PACKAGE_VERSION="0.46.1";zu.PACKAGE_NAME="@opentelemetry/instrumentation-amqplib"});var CZ=m(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.AmqplibInstrumentation=void 0;var He=(x(),b(B)),kg=Se(),Oe=fe(),In=(ve(),b(ot)),pn=cv(),We=yZ(),NZ=OZ(),Vg=[">=0.5.5 <1"],dv=class extends Oe.InstrumentationBase{constructor(e={}){super(NZ.PACKAGE_NAME,NZ.PACKAGE_VERSION,Object.assign(Object.assign({},pn.DEFAULT_CONFIG),e))}setConfig(e={}){super.setConfig(Object.assign(Object.assign({},pn.DEFAULT_CONFIG),e))}init(){let e=new Oe.InstrumentationNodeModuleFile("amqplib/lib/channel_model.js",Vg,this.patchChannelModel.bind(this),this.unpatchChannelModel.bind(this)),n=new Oe.InstrumentationNodeModuleFile("amqplib/lib/callback_model.js",Vg,this.patchChannelModel.bind(this),this.unpatchChannelModel.bind(this)),r=new Oe.InstrumentationNodeModuleFile("amqplib/lib/connect.js",Vg,this.patchConnect.bind(this),this.unpatchConnect.bind(this));return new Oe.InstrumentationNodeModuleDefinition("amqplib",Vg,void 0,void 0,[e,r,n])}patchConnect(e){return e=this.unpatchConnect(e),(0,Oe.isWrapped)(e.connect)||this._wrap(e,"connect",this.getConnectPatch.bind(this)),e}unpatchConnect(e){return(0,Oe.isWrapped)(e.connect)&&this._unwrap(e,"connect"),e}patchChannelModel(e,n){return(0,Oe.isWrapped)(e.Channel.prototype.publish)||this._wrap(e.Channel.prototype,"publish",this.getPublishPatch.bind(this,n)),(0,Oe.isWrapped)(e.Channel.prototype.consume)||this._wrap(e.Channel.prototype,"consume",this.getConsumePatch.bind(this,n)),(0,Oe.isWrapped)(e.Channel.prototype.ack)||this._wrap(e.Channel.prototype,"ack",this.getAckPatch.bind(this,!1,pn.EndOperation.Ack)),(0,Oe.isWrapped)(e.Channel.prototype.nack)||this._wrap(e.Channel.prototype,"nack",this.getAckPatch.bind(this,!0,pn.EndOperation.Nack)),(0,Oe.isWrapped)(e.Channel.prototype.reject)||this._wrap(e.Channel.prototype,"reject",this.getAckPatch.bind(this,!0,pn.EndOperation.Reject)),(0,Oe.isWrapped)(e.Channel.prototype.ackAll)||this._wrap(e.Channel.prototype,"ackAll",this.getAckAllPatch.bind(this,!1,pn.EndOperation.AckAll)),(0,Oe.isWrapped)(e.Channel.prototype.nackAll)||this._wrap(e.Channel.prototype,"nackAll",this.getAckAllPatch.bind(this,!0,pn.EndOperation.NackAll)),(0,Oe.isWrapped)(e.Channel.prototype.emit)||this._wrap(e.Channel.prototype,"emit",this.getChannelEmitPatch.bind(this)),(0,Oe.isWrapped)(e.ConfirmChannel.prototype.publish)||this._wrap(e.ConfirmChannel.prototype,"publish",this.getConfirmedPublishPatch.bind(this,n)),e}unpatchChannelModel(e){return(0,Oe.isWrapped)(e.Channel.prototype.publish)&&this._unwrap(e.Channel.prototype,"publish"),(0,Oe.isWrapped)(e.Channel.prototype.consume)&&this._unwrap(e.Channel.prototype,"consume"),(0,Oe.isWrapped)(e.Channel.prototype.ack)&&this._unwrap(e.Channel.prototype,"ack"),(0,Oe.isWrapped)(e.Channel.prototype.nack)&&this._unwrap(e.Channel.prototype,"nack"),(0,Oe.isWrapped)(e.Channel.prototype.reject)&&this._unwrap(e.Channel.prototype,"reject"),(0,Oe.isWrapped)(e.Channel.prototype.ackAll)&&this._unwrap(e.Channel.prototype,"ackAll"),(0,Oe.isWrapped)(e.Channel.prototype.nackAll)&&this._unwrap(e.Channel.prototype,"nackAll"),(0,Oe.isWrapped)(e.Channel.prototype.emit)&&this._unwrap(e.Channel.prototype,"emit"),(0,Oe.isWrapped)(e.ConfirmChannel.prototype.publish)&&this._unwrap(e.ConfirmChannel.prototype,"publish"),e}getConnectPatch(e){return function(r,o,s){return e.call(this,r,o,function(i,a){if(i==null){let c=(0,We.getConnectionAttributesFromUrl)(r),u=(0,We.getConnectionAttributesFromServer)(a);a[We.CONNECTION_ATTRIBUTES]=Object.assign(Object.assign({},c),u)}s.apply(this,arguments)})}}getChannelEmitPatch(e){let n=this;return function(o){if(o==="close"){n.endAllSpansOnChannel(this,!0,pn.EndOperation.ChannelClosed,void 0);let s=this[We.CHANNEL_CONSUME_TIMEOUT_TIMER];s&&clearInterval(s),this[We.CHANNEL_CONSUME_TIMEOUT_TIMER]=void 0}else o==="error"&&n.endAllSpansOnChannel(this,!0,pn.EndOperation.ChannelError,void 0);return e.apply(this,arguments)}}getAckAllPatch(e,n,r){let o=this;return function(i){return o.endAllSpansOnChannel(this,e,n,i),r.apply(this,arguments)}}getAckPatch(e,n,r){let o=this;return function(i,a,c){var u;let l=this,d=n===pn.EndOperation.Reject?a:c,p=(u=l[We.CHANNEL_SPANS_NOT_ENDED])!==null&&u!==void 0?u:[],_=p.findIndex(f=>f.msg===i);if(_<0)o.endConsumerSpan(i,e,n,d);else if(n!==pn.EndOperation.Reject&&a){for(let f=0;f<=_;f++)o.endConsumerSpan(p[f].msg,e,n,d);p.splice(0,_+1)}else o.endConsumerSpan(i,e,n,d),p.splice(_,1);return r.apply(this,arguments)}}getConsumePatch(e,n){let r=this;return function(s,i,a){let c=this;if(!Object.prototype.hasOwnProperty.call(c,We.CHANNEL_SPANS_NOT_ENDED)){let{consumeTimeoutMs:l}=r.getConfig();if(l){let d=setInterval(()=>{r.checkConsumeTimeoutOnChannel(c)},l);d.unref(),c[We.CHANNEL_CONSUME_TIMEOUT_TIMER]=d}c[We.CHANNEL_SPANS_NOT_ENDED]=[]}let u=function(l){var d,p,_,f,E;if(!l)return i.call(this,l);let S=(d=l.properties.headers)!==null&&d!==void 0?d:{},h=He.propagation.extract(He.ROOT_CONTEXT,S),R=(p=l.fields)===null||p===void 0?void 0:p.exchange,A;if(r._config.useLinksForConsume){let I=h?(_=He.trace.getSpan(h))===null||_===void 0?void 0:_.spanContext():void 0;h=void 0,I&&(A=[{context:I}])}let O=r.tracer.startSpan(`${s} process`,{kind:He.SpanKind.CONSUMER,attributes:Object.assign(Object.assign({},(f=c?.connection)===null||f===void 0?void 0:f[We.CONNECTION_ATTRIBUTES]),{[In.SEMATTRS_MESSAGING_DESTINATION]:R,[In.SEMATTRS_MESSAGING_DESTINATION_KIND]:In.MESSAGINGDESTINATIONKINDVALUES_TOPIC,[In.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY]:(E=l.fields)===null||E===void 0?void 0:E.routingKey,[In.SEMATTRS_MESSAGING_OPERATION]:In.MESSAGINGOPERATIONVALUES_PROCESS,[In.SEMATTRS_MESSAGING_MESSAGE_ID]:l?.properties.messageId,[In.SEMATTRS_MESSAGING_CONVERSATION_ID]:l?.properties.correlationId}),links:A},h),{consumeHook:y}=r.getConfig();y&&(0,Oe.safeExecuteInTheMiddle)(()=>y(O,{moduleVersion:e,msg:l}),I=>{I&&He.diag.error("amqplib instrumentation: consumerHook error",I)},!0),a?.noAck||(c[We.CHANNEL_SPANS_NOT_ENDED].push({msg:l,timeOfConsume:(0,kg.hrTime)()}),l[We.MESSAGE_STORED_SPAN]=O);let M=h||He.ROOT_CONTEXT;He.context.with(He.trace.setSpan(M,O),()=>{i.call(this,l)}),a?.noAck&&(r.callConsumeEndHook(O,l,!1,pn.EndOperation.AutoAck),O.end())};return arguments[1]=u,n.apply(this,arguments)}}getConfirmedPublishPatch(e,n){let r=this;return function(s,i,a,c,u){let l=this,{span:d,modifiedOptions:p}=r.createPublishSpan(r,s,i,l,c),{publishHook:_}=r.getConfig();_&&(0,Oe.safeExecuteInTheMiddle)(()=>_(d,{moduleVersion:e,exchange:s,routingKey:i,content:a,options:p,isConfirmChannel:!0}),h=>{h&&He.diag.error("amqplib instrumentation: publishHook error",h)},!0);let f=function(h,R){try{u?.call(this,h,R)}finally{let{publishConfirmHook:A}=r.getConfig();A&&(0,Oe.safeExecuteInTheMiddle)(()=>A(d,{moduleVersion:e,exchange:s,routingKey:i,content:a,options:c,isConfirmChannel:!0,confirmError:h}),O=>{O&&He.diag.error("amqplib instrumentation: publishConfirmHook error",O)},!0),h&&d.setStatus({code:He.SpanStatusCode.ERROR,message:"message confirmation has been nack'ed"}),d.end()}},E=(0,We.markConfirmChannelTracing)(He.context.active()),S=[...arguments];return S[3]=p,S[4]=He.context.bind((0,We.unmarkConfirmChannelTracing)(He.trace.setSpan(E,d)),f),He.context.with(E,n.bind(this,...S))}}getPublishPatch(e,n){let r=this;return function(s,i,a,c){if((0,We.isConfirmChannelTracing)(He.context.active()))return n.apply(this,arguments);{let u=this,{span:l,modifiedOptions:d}=r.createPublishSpan(r,s,i,u,c),{publishHook:p}=r.getConfig();p&&(0,Oe.safeExecuteInTheMiddle)(()=>p(l,{moduleVersion:e,exchange:s,routingKey:i,content:a,options:d,isConfirmChannel:!1}),E=>{E&&He.diag.error("amqplib instrumentation: publishHook error",E)},!0);let _=[...arguments];_[3]=d;let f=n.apply(this,_);return l.end(),f}}}createPublishSpan(e,n,r,o,s){var i;let a=(0,We.normalizeExchange)(n),c=e.tracer.startSpan(`publish ${a}`,{kind:He.SpanKind.PRODUCER,attributes:Object.assign(Object.assign({},o.connection[We.CONNECTION_ATTRIBUTES]),{[In.SEMATTRS_MESSAGING_DESTINATION]:n,[In.SEMATTRS_MESSAGING_DESTINATION_KIND]:In.MESSAGINGDESTINATIONKINDVALUES_TOPIC,[In.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY]:r,[In.SEMATTRS_MESSAGING_MESSAGE_ID]:s?.messageId,[In.SEMATTRS_MESSAGING_CONVERSATION_ID]:s?.correlationId})}),u=s??{};return u.headers=(i=u.headers)!==null&&i!==void 0?i:{},He.propagation.inject(He.trace.setSpan(He.context.active(),c),u.headers),{span:c,modifiedOptions:u}}endConsumerSpan(e,n,r,o){let s=e[We.MESSAGE_STORED_SPAN];s&&(n!==!1&&s.setStatus({code:He.SpanStatusCode.ERROR,message:r!==pn.EndOperation.ChannelClosed&&r!==pn.EndOperation.ChannelError?`${r} called on message${o===!0?" with requeue":o===!1?" without requeue":""}`:r}),this.callConsumeEndHook(s,e,n,r),s.end(),e[We.MESSAGE_STORED_SPAN]=void 0)}endAllSpansOnChannel(e,n,r,o){var s;((s=e[We.CHANNEL_SPANS_NOT_ENDED])!==null&&s!==void 0?s:[]).forEach(a=>{this.endConsumerSpan(a.msg,n,r,o)}),e[We.CHANNEL_SPANS_NOT_ENDED]=[]}callConsumeEndHook(e,n,r,o){let{consumeEndHook:s}=this.getConfig();s&&(0,Oe.safeExecuteInTheMiddle)(()=>s(e,{msg:n,rejected:r,endOperation:o}),i=>{i&&He.diag.error("amqplib instrumentation: consumerEndHook error",i)},!0)}checkConsumeTimeoutOnChannel(e){var n;let r=(0,kg.hrTime)(),o=(n=e[We.CHANNEL_SPANS_NOT_ENDED])!==null&&n!==void 0?n:[],s,{consumeTimeoutMs:i}=this.getConfig();for(s=0;s<o.length;s++){let a=o[s],c=(0,kg.hrTimeDuration)(a.timeOfConsume,r);if((0,kg.hrTimeToMilliseconds)(c)<i)break;this.endConsumerSpan(a.msg,null,pn.EndOperation.InstrumentationTimeout,!0)}o.splice(0,s)}};Bg.AmqplibInstrumentation=dv});var IZ=m(Oi=>{"use strict";var c$e=Oi&&Oi.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vZ=Oi&&Oi.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&c$e(e,t,n)};Object.defineProperty(Oi,"__esModule",{value:!0});vZ(CZ(),Oi);vZ(cv(),Oi)});var WZ=require("commander"),Np=v(require("crypto")),Ur=v(require("fs")),pt=v(require("os")),os=v(require("path")),zZ=require("child_process"),XZ=require("util");var Up=require("child_process"),Ov=require("util"),cs=v(require("fs")),wp=v(require("os")),Jg=v(require("path"));var To="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var kr=(0,Ov.promisify)(Up.execFile),Zg=Jg.join(wp.homedir(),".visa-mcp"),Qu=Jg.join(Zg,"session-token"),Gn="visa-cli",as="session-token",xp="rc-access",_Q=5e3,Dp=class extends Error{constructor(e){super(e),this.name="CredentialAccessError"}};function fQ(t){let e=t;return[e?.message,e?.stderr].filter(n=>typeof n=="string").join(`
12
- `)}function Nv(t){let e=t;if(e?.code==="EPERM"||e?.code==="EACCES")return!0;let n=fQ(t).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function mQ(){try{let{stdout:t}=await kr("security",["find-generic-password","-s",Gn,"-a",as,"-w"],{timeout:5e3});return t.trim()||null}catch(t){if(Nv(t))throw new Dp("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function EQ(t){try{try{await kr("security",["delete-generic-password","-s",Gn,"-a",as],{timeout:5e3})}catch{}return await kr("security",["add-generic-password","-s",Gn,"-a",as,"-w",t],{timeout:5e3}),!0}catch{return!1}}async function SQ(){try{await kr("security",["delete-generic-password","-s",Gn,"-a",as],{timeout:5e3})}catch{}}async function gQ(){if(!Qg())return null;try{let{stdout:t}=await kr("secret-tool",["lookup","service",Gn,"account",as],{timeout:5e3});return t.trim()||null}catch{return null}}async function hQ(t){if(!Qg())return!1;try{let e=(0,Up.execFile)("secret-tool",["store","--label",`${Gn} ${as}`,"service",Gn,"account",as]);return e.stdin?(e.stdin.write(t),e.stdin.end(),await Promise.race([new Promise((n,r)=>{e.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),e.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{e.kill(),r(new Error("secret-tool timed out"))},_Q))]),!0):!1}catch{return!1}}async function TQ(){if(Qg())try{await kr("secret-tool",["clear","service",Gn,"account",as],{timeout:5e3})}catch{}}function Qg(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function AQ(){try{let{stdout:t}=await kr("security",["find-generic-password","-s",Gn,"-a",xp,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function RQ(t){try{try{await kr("security",["delete-generic-password","-s",Gn,"-a",xp],{timeout:5e3})}catch{}await kr("security",["add-generic-password","-s",Gn,"-a",xp,"-w",t],{timeout:5e3})}catch{}}async function yQ(){try{await kr("security",["delete-generic-password","-s",Gn,"-a",xp],{timeout:5e3})}catch{}}function zg(){try{return cs.readFileSync(Qu,"utf-8").trim()||null}catch(t){if(Nv(t))throw new Dp(`Unable to read Visa CLI credentials from ${Qu}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Cv(t){cs.mkdirSync(Zg,{recursive:!0,mode:448}),cs.writeFileSync(Qu,t,{mode:384}),process.platform==="win32"&&OQ(Qu)}function Xg(){try{cs.unlinkSync(Qu)}catch{}}function OQ(t){try{let e=wp.userInfo().username;(0,Up.execFile)("icacls",[t,"/inheritance:r","/grant:r",`${e}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(e){console.error(`[visa-cli] Failed to invoke icacls: ${e instanceof Error?e.message:String(e)}`)}}function Wg(){switch(process.platform){case"darwin":return{get:mQ,store:EQ,delete:SQ};case"linux":return{get:gQ,store:hQ,delete:TQ};default:return{get:async()=>zg(),store:async t=>{try{return Cv(t),!0}catch{return!1}},delete:async()=>Xg(),storesInSessionFile:!0}}}var Ae=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=Wg(),n=await e.get();if(n)return n;let r=zg();return r?(await e.store(r),r):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Wg();if(await n.store(e)){if(await n.get()===e){n.storesInSessionFile||Xg();return}await n.delete()}if(Cv(e),zg()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Zg} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?To:AQ()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await RQ(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Wg().delete(),Xg()}static async clearAll(){await this.deleteSessionToken(),await yQ()}};var Vp=v(require("crypto")),Bp=v(require("tty")),Gp=v(require("fs"));function CQ(t){return/-rc\.|-beta\./.test(t)}function eh(t){return Vp.createHash("sha256").update(t.trim()).digest("hex")}function vv(t){return To==="SKIP"?!0:Vp.timingSafeEqual(Buffer.from(eh(t)),Buffer.from(To))}function vQ(){try{let t=Gp.openSync("/dev/tty","r+"),e=new Bp.ReadStream(t),n=new Bp.WriteStream(t),r=!1;return{input:e,output:n,cleanupStreams:()=>{if(!r){r=!0;try{e.destroy()}catch{}try{n.destroy()}catch{}try{Gp.closeSync(t)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function IQ(t){return new Promise((e,n)=>{let r;try{r=vQ()}catch(l){n(l);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",u);try{o.setRawMode?.(!1)}catch{}i()};s.write(t),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",u=l=>{l==="\r"||l===`
13
- `?(s.write(`
14
- `),a(),e(c)):l===""?(s.write(`
15
- `),a(),n(new Error("Cancelled"))):l==="\x7F"||l==="\b"?c.length>0&&(c=c.slice(0,-1),s.write("\b \b")):(c+=l,s.write("\u2022"))};o.on("data",u)})}var PQ=`
1
+ "use strict";var $c=Object.create;var Jr=Object.defineProperty;var Rc=Object.getOwnPropertyDescriptor;var Ic=Object.getOwnPropertyNames;var Pc=Object.getPrototypeOf,Mc=Object.prototype.hasOwnProperty;var Oc=(e,t)=>()=>(e&&(t=e(e=0)),t);var Eo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$o=(e,t)=>{for(var n in t)Jr(e,n,{get:t[n],enumerable:!0})},Nc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ic(t))!Mc.call(e,s)&&s!==n&&Jr(e,s,{get:()=>t[s],enumerable:!(r=Rc(t,s))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?$c(Pc(e)):{},Nc(t||!e||!e.__esModule?Jr(n,"default",{value:e,enumerable:!0}):n,e));var Gn=Eo((wf,Wc)=>{Wc.exports={name:"@visa/cli",version:"2.0.0-rc.42",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.2","@typescript-eslint/parser":"^8.59.1","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var so=Eo(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.micros=jd;X.fromCents=Vd;X.fromUsdc=qd;X.fromUsd=Fd;X.toCents=Bd;X.toCentsForAcquirer=Hd;X.toUsdc=Kd;X.toWire=Gd;X.fromWire=zd;X.toDisplay=Wd;X.toUsdRounded2dp=Jd;X.add=Yd;X.sub=Zd;X.clampNonNegative=Xd;X.isNonNegative=Qd;X.max=em;X.min=tm;var Je=10000n,Ea=1000000n;function jd(e){return e}function Vd(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Je}function qd(e){return e}function Fd(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Bd(e){if(e>=0n)return Number(e/Je);let t=e/Je,n=e%Je;return Number(n===0n?t:t-1n)}function Hd(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Je)}function Kd(e){return e}function Gd(e){return e.toString()}function zd(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function Wd(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Ea,a=o%Ea,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Jd(e){let t=e<0n,n=t?-e:e,r=n/Je,o=n%Je*2n,i;o<Je?i=r:o>Je?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Yd(e,t){return e+t}function Zd(e,t){return e-t}function Xd(e){return e<0n?0n:e}function Qd(e){return e>=0n}function em(e,t){return e>t?e:t}function tm(e,t){return e<t?e:t}});var Br={};$o(Br,{initSentry:()=>Bp,isSentryConfigured:()=>Fp,reportFatal:()=>Hp});function Fp(){return!1}async function Bp(){return null}async function Hp(e,t){process.exit(t?.exitCode??1)}var Hr=Oc(()=>{});var gc=require("commander"),Ln=A(require("crypto")),Ie=A(require("fs")),W=A(require("os")),Ze=A(require("path")),hc=require("child_process"),yc=require("util");var Hn=require("child_process"),Ro=require("util"),et=A(require("fs")),Kn=A(require("os")),Qr=A(require("path"));var je="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Pe=(0,Ro.promisify)(Hn.execFile),es=Qr.join(Kn.homedir(),".visa-mcp"),mn=Qr.join(es,"session-token"),ye="visa-cli",Qe="session-token",Fn="rc-access",Uc=5e3,Bn=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Dc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Io(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Dc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Lc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",Qe,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Io(e))throw new Bn("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function jc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",Qe],{timeout:5e3})}catch{}return await Pe("security",["add-generic-password","-s",ye,"-a",Qe,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Vc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",Qe],{timeout:5e3})}catch{}}async function qc(){if(!ts())return null;try{let{stdout:e}=await Pe("secret-tool",["lookup","service",ye,"account",Qe],{timeout:5e3});return e.trim()||null}catch{return null}}async function Fc(e){if(!ts())return!1;try{let t=(0,Hn.execFile)("secret-tool",["store","--label",`${ye} ${Qe}`,"service",ye,"account",Qe]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Uc))]),!0):!1}catch{return!1}}async function Bc(){if(ts())try{await Pe("secret-tool",["clear","service",ye,"account",Qe],{timeout:5e3})}catch{}}function ts(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Hc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",Fn,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Kc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}await Pe("security",["add-generic-password","-s",ye,"-a",Fn,"-w",e],{timeout:5e3})}catch{}}async function Gc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}}function Zr(){try{return et.readFileSync(mn,"utf-8").trim()||null}catch(e){if(Io(e))throw new Bn(`Unable to read Visa CLI credentials from ${mn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Po(e){et.mkdirSync(es,{recursive:!0,mode:448}),et.writeFileSync(mn,e,{mode:384}),process.platform==="win32"&&zc(mn)}function Xr(){try{et.unlinkSync(mn)}catch{}}function zc(e){try{let t=Kn.userInfo().username;(0,Hn.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Yr(){switch(process.platform){case"darwin":return{get:Lc,store:jc,delete:Vc};case"linux":return{get:qc,store:Fc,delete:Bc};default:return{get:async()=>Zr(),store:async e=>{try{return Po(e),!0}catch{return!1}},delete:async()=>Xr(),storesInSessionFile:!0}}}var D=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Yr(),n=await t.get();if(n)return n;let r=Zr();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Yr();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Xr();return}await n.delete()}if(Po(t),Zr()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${es} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?je:Hc()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Kc(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Yr().delete(),Xr()}static async clearAll(){await this.deleteSessionToken(),await Gc()}};var zn=A(require("crypto")),Wn=A(require("tty")),Jn=A(require("fs"));function Jc(e){return/-rc\.|-beta\./.test(e)}function ns(e){return zn.createHash("sha256").update(e.trim()).digest("hex")}function Mo(e){return je==="SKIP"?!0:zn.timingSafeEqual(Buffer.from(ns(e)),Buffer.from(je))}function Yc(){try{let e=Jn.openSync("/dev/tty","r+"),t=new Wn.ReadStream(e),n=new Wn.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Jn.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function Zc(e){return new Promise((t,n)=>{let r;try{r=Yc()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
+ `?(o.write(`
4
+ `),a(),t(l)):u===""?(o.write(`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),o.write("\b \b")):(l+=u,o.write("\u2022"))};s.on("data",c)})}var Xc=`
16
6
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
17
7
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
18
8
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -21,34 +11,34 @@ Mongoose Error Code: ${e.code}`:""}`})}function CC(t,e,n,r=void 0){n&&(0,zBe.saf
21
11
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
22
12
 
23
13
  This is a Release Candidate build. Access is restricted to Visa employees.
24
- `;async function Iv(t={}){let e=t.version??kp().version;if(!CQ(e))return;let n=process.env.VISA_RC_CODE;if(n&&vv(n)){await Ae.saveRcAccessToken(eh(n));return}if(t.isMcp??!1){let i=await Ae.getRcAccessToken();if(i&&(To==="SKIP"||i===To))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
25
- `),process.exit(1)}let o=await Ae.getRcAccessToken();if(o&&(To==="SKIP"||o===To))return;console.log(PQ);let s=3;for(let i=1;i<=s;i++){let a;try{a=await IQ(" Enter RC access code: ")}catch{process.exit(1)}if(vv(a)){await Ae.saveRcAccessToken(eh(a)),console.log(`
14
+ `;async function Oo(e={}){let t=e.version??Gn().version;if(!Jc(t))return;let n=process.env.VISA_RC_CODE;if(n&&Mo(n)){await D.saveRcAccessToken(ns(n));return}if(e.isMcp??!1){let i=await D.getRcAccessToken();if(i&&(je==="SKIP"||i===je))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let s=await D.getRcAccessToken();if(s&&(je==="SKIP"||s===je))return;console.log(Xc);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Zc(" Enter RC access code: ")}catch{process.exit(1)}if(Mo(a)){await D.saveRcAccessToken(ns(a)),console.log(`
26
16
  Access granted. Welcome.
27
- `);return}i<s&&console.log(`
28
- Invalid code. ${s-i} attempt(s) remaining.
17
+ `);return}i<o&&console.log(`
18
+ Invalid code. ${o-i} attempt(s) remaining.
29
19
  `)}console.log(`
30
20
  Invalid code. Contact your team lead.
31
- `),process.exit(1)}var Pv=require("child_process");function th(t=process.env,e=process.platform){return t.VISA_CLI_NO_BROWSER==="1"||t.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:t.CI==="true"||t.CI==="1"?{headless:!0,reason:"CI environment detected"}:t.SSH_CONNECTION||t.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function bQ(t){let n=t.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${t}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
32
- `)}function nh(t,e=process.platform){return e==="darwin"?{cmd:"open",args:[t]}:e==="win32"?{cmd:"cmd",args:["/c","start","",t]}:e==="linux"?{cmd:"xdg-open",args:[t]}:null}async function rh(t,e={}){let n=e.log??(c=>console.log(c)),r=e.env??process.env,o=e.platform??process.platform,s=e.spawn??((c,u,l)=>{(0,Pv.execFile)(c,u,d=>l(d))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of bQ(t).split(`
33
- `))n(` ${c}`);n("");let i=th(r,o);if(i.headless){n(` (${i.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let a=nh(t,o);if(!a){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{s(a.cmd,a.args,u=>{u?(n(` Could not open browser automatically (${u.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}function MQ(t){return new Promise(e=>setTimeout(e,t))}function bv(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t*1e3;if(typeof t!="string"||t.trim()==="")return null;let e=Number(t);if(Number.isFinite(e)&&e>0)return e*1e3;let n=Date.parse(t);return Number.isFinite(n)?Math.max(n-Date.now(),0):null}function Mv(t){return!Number.isFinite(t)||t===null||t<=0?1e3:Math.min(Math.max(Math.ceil(t),1e3),3e4)}async function LQ(t,e=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(e)),3e4);if(!t||t.status!==429)return n(1e3);let r=bv(t.headers?.get("Retry-After"));if(r!==null)return n(Mv(r));if(typeof t.json=="function")try{let o=await t.json();return n(Mv(bv(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function us(t,e){let n=await LQ(t);return e?.(n),await MQ(n),n}var xv=v(require("crypto")),fn=v(require("fs")),Hp=v(require("path"));function Dv(t,e){fn.mkdirSync(Hp.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.${xv.randomBytes(8).toString("hex")}.tmp`;try{fn.writeFileSync(n,JSON.stringify(e,null,2)+`
34
- `),fn.renameSync(n,t)}catch(r){try{fn.unlinkSync(n)}catch{}throw r}}function Lv(t){return`'${t.replace(/'/g,"'\\''")}'`}var Uv="# visa-cli-hud-v1";function xQ(t,e){let n=t??process.execPath,r=e??process.argv[1]??"",o=r?Hp.resolve(r):"";return`${o?`${Lv(n)} ${Lv(o)} config statusline`:"visa-cli config statusline"} ${Uv}`}function Ci(t){return typeof t!="string"?!1:t.includes(Uv)?!0:t.includes("visa-cli")&&t.includes("statusline")}function $p(t,e=xQ){let n={},r=!1;if(fn.existsSync(t)){r=!0;try{n=JSON.parse(fn.readFileSync(t,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return Ci(o)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:e()},Dv(t,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function oh(t){if(!fn.existsSync(t))return{removed:!1,message:"No ~/.claude/settings.json found."};let e;try{e=JSON.parse(fn.readFileSync(t,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!e.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof e.statusLine=="object"?e.statusLine.command:"";return Ci(n)?(delete e.statusLine,Dv(t,e),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var Ao=v(require("fs")),Ro=v(require("path")),DQ=1,vi={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},UQ=["terminal","claude","claude-code","codex","all"];function lh(t){let e=t.toLowerCase();return UQ.includes(e)?e:null}var wQ=50,kQ=64*1024,wv=10,sh=80;function VQ(){let t=(process.env.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let e=(process.env.TERM??"").toLowerCase();return e.includes("truecolor")||e.includes("24bit")}var ih=VQ(),ee={reset:"\x1B[0m",visaBlue:ih?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ih?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ih?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function ie(t,e){return t.length===0||process.env.NO_COLOR?t:`${e}${t}${ee.reset}`}function kv(t){return t.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function $v(t=process.stdin){return t.isTTY?null:new Promise(e=>{let n=[],r=!1,o=()=>{t.removeListener("data",i),t.removeListener("end",a),t.removeListener("error",c),clearTimeout(u)},s=l=>{r||(r=!0,o(),e(l))},i=l=>{n.push(typeof l=="string"?Buffer.from(l):l)},a=()=>{let l=Buffer.concat(n).toString("utf-8").trim();if(!l)return s(null);try{let d=JSON.parse(l);s(d&&typeof d=="object"?d:null)}catch{s(null)}},c=()=>s(null),u=setTimeout(()=>{n.length>0?a():s(null)},wQ);t.on("data",i),t.on("end",a),t.on("error",c)})}function Fp(t){let n=Math.round(Math.max(0,Math.min(1,t))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${ie(r||"",ee.visaBlueSoft)}${ie(o||"",ee.dim)}`}function ah(t){return!Number.isFinite(t)||t<0?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${Math.round(t/1e3)}k`:String(Math.round(t))}function Vv(t){if(zQ(t))return BQ(t);let e=` ${ie("\u2502",ee.dim)} `,n=ch(t)||"claude",r=t.cwd?bt(Ro.basename(t.cwd)):"",o=dh(t.workspace),s=r||o,i=o&&o!==s?` ${ie(`@${o}`,ee.visaBlueSoft)}`:"",a=[ie(`[${n}]`,ee.visaBlueSoft)];s&&a.push(`${ie(s,ee.visaGold)}${i}`);let c=a.join(e),u=Number(t.context_window?.context_window_size??0),l=typeof t.context_window?.used_percentage=="number"?t.context_window.used_percentage:typeof t.context_window?.remaining_percentage=="number"?100-t.context_window.remaining_percentage:null,d=t.context_window?.current_usage,p=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(y=>typeof y=="number"&&Number.isFinite(y)),_=p.length>0?p.reduce((y,M)=>y+M,0):null,f=Number(t.context_window?.total_input_tokens??_??d?.input_tokens??0),E=l!==null?Math.max(0,Math.min(1,l/100)):u>0?Math.max(0,Math.min(1,f/u)):0,S=l!==null&&u>0?Math.round(E*u):f,h;if(u>0||l!==null){let y=`${String(Math.round(E*100)).padStart(2," ")}%`,M=u>0?` ${ie(`(${ah(S)}/${ah(u)})`,ee.dim)}`:"";h=`${ie("Context",ee.dim)} ${Fp(E)} ${ie(y,ee.green)}${M}`}else h=`${ie("Context",ee.dim)} ${ie("-",ee.dim)}`;let R=HQ(t.rate_limits),A=[h];R&&A.push(R);let O=A.join(e);return`${c}
35
- ${O}`}function BQ(t){let e=` ${ie("\u2502",ee.dim)} `,n=Jv(t),r=n.model||"codex",o=[ie(`[${r}]`,ee.visaBlueSoft)];n.project&&o.push(ie(n.project,ee.visaGold)),n.gitBranch&&o.push(`${ie("git",ee.dim)} ${ie(n.gitBranch,ee.visaGold)}`);let s=o.join(e),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${ie("Context",ee.dim)} ${Fp(c)} ${ie(`${Math.round(n.contextUsedPercent)}%`,ee.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,u=Math.max(0,Math.min(1,c/100));i.push(`${ie("Context",ee.dim)} ${Fp(u)} ${ie(`${Math.round(c)}%`,ee.green)}`)}typeof n.usedTokens=="number"&&i.push(`${ie("Tokens",ee.dim)} ${ah(n.usedTokens)}`),n.status&&i.push(`${ie("Status",ee.dim)} ${ie(n.status,ee.visaBlueSoft)}`),n.threadTitle&&i.push(`${ie("Thread",ee.dim)} ${ie(n.threadTitle,ee.visaBlueSoft)}`);let a=i.length>0?i.join(e):`${ie("Context",ee.dim)} ${ie("-",ee.dim)}`;return`${s}
36
- ${a}`}function GQ(t){if(typeof t!="number"||t<=0)return"";let n=(t>1e12?t:t*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function Bv(t,e){if(!t||typeof t.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,t.used_percentage)),r=n/100,o=Fp(r),s=n>=90?"\x1B[38;5;196m":n>=70?ee.visaGold:ee.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=GQ(t.resets_at),c=a?` ${ie(`(${a} / ${e})`,ee.dim)}`:` ${ie(`(${e})`,ee.dim)}`;return`${o} ${ie(i,s)}${c}`}function HQ(t){if(!t)return null;let e=Bv(t.five_hour,"5h"),n=typeof t.seven_day?.used_percentage=="number"?t.seven_day.used_percentage:null,r=n!==null&&n>=90?Bv(t.seven_day,"7d"):null;if(!e&&!r)return null;let o=` ${ie("\u2502",ee.dim)} `,s=[e,r].filter(Boolean);return`${ie("Usage",ee.dim)} ${s.join(o)}`}function Fv(t){let e;try{let n=Ao.statSync(t);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,kQ),s=r-o;e=Ao.openSync(t,"r");let i=Buffer.alloc(o);Ao.readSync(e,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=Buffer.alloc(1);if(Ao.readSync(e,c,0,1,s-1),c[0]!==10){let u=a.indexOf(`
37
- `);u>=0&&(a=a.slice(u+1))}}return a}catch{return null}finally{if(e!==void 0)try{Ao.closeSync(e)}catch{}}}function $Q(t){if(!t||typeof t!="object")return;let e=t,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let o=e[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=Ro.basename(Ro.dirname(o)),i=Ro.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function FQ(t){let e=t.split(`
38
- `),n=[],r=new Set;for(let o=e.length-1;o>=0&&n.length<wv*3;o-=1){let s=e[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let u=c.content;if(Array.isArray(u))for(let l of u){if(!l||typeof l!="object")continue;let d=l;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let p=typeof d.id=="string"?d.id:"",_=p.length>0?!r.has(p):!1;n.push({name:d.name,target:$Q(d.input),running:_})}}}return n.reverse(),n.slice(Math.max(0,n.length-wv))}function jQ(t){let e=[];for(let n of t){let r=e[e.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:e.push({...n,count:1})}return e}function qQ(t){let e=t.running?ie("\u25D0",ee.visaGold):ie("\u2713",ee.green),n=t.running?ee.visaGold:ee.visaBlueSoft,r=ie(bt(t.name),n),o=t.target?bt(t.target):"",s=o?`${ie(":",ee.dim)} ${ie(o,ee.dim)}`:"",i=t.count>1?` ${ie(`\xD7${t.count}`,ee.dim)}`:"";return s?`${e} ${r}${s}${i}`:`${e} ${r}${i}`}function YQ(t){let e=` ${ie("\u2502",ee.dim)} `,n=kv(e),r=t.slice();for(;r.length>0;){let c=r.join(e);if(kv(c)<=sh)return c;r=r.slice(1)}if(t.length===0)return"";let o="\u2026",i=t[t.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>sh-n-1?i.slice(0,sh-n-1)+o:i;return`${ie(o,ee.dim)}${e}${a}`}async function Gv(t){if(!t||typeof t!="string")return null;let e=Fv(t);if(!e)return null;let n;try{n=FQ(e)}catch{return null}if(n.length===0)return null;let o=jQ(n).map(qQ);return YQ(o)||null}async function jv(t,e,n){return(await Yv(t,e,n)).join(`
39
- `)}function qv(t,e,n){let r=!!e?.activeSession||t.includes("in session"),o=n?WQ(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Yv(t,e,n){let{isActive:r}=qv(t,n,e?.transcript_path);if(e&&!r){let s=[],i=Vv(e);if(i&&s.push(...i.split(`
40
- `)),e.transcript_path){let c=await Gv(e.transcript_path);c&&s.push(...c.split(`
41
- `))}let a=ie(uh(t),ee.dim);return s.push(a),s}let o=[t];if(e){let s=Vv(e);if(s&&o.push(...s.split(`
42
- `)),e.transcript_path){let i=await Gv(e.transcript_path);i&&o.push(...i.split(`
43
- `))}}return o}var KQ=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function WQ(t){let e=Fv(t);if(!e)return!1;let n=e.slice(-16384).toLowerCase();return KQ.some(r=>n.includes(`"${r}"`))}async function Kv(t,e,n){let r=await Yv(t,e,n),o=r.join(`
44
- `),{isActive:s}=qv(t,n,e?.transcript_path);return{schemaVersion:DQ,client:e?Xv(e):vi.UNKNOWN,rendered:o,lines:r.map(uh),visa:{spendLine:uh(t),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:e?Jv(e):{}}}function bt(t){return t?t.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function dh(t){if(typeof t=="string")return bt(Ro.basename(t));if(!t||typeof t!="object")return"";let e=typeof t.current_dir=="string"?t.current_dir:typeof t.path=="string"?t.path:"";return bt(e?Ro.basename(e):t.name)}function Wv(t){return bt(t.app_name??t.appName??t.app??t.client)}function ch(t){return bt(t.model?.display_name??t.model?.id??t.model_name??t.modelName)}function zv(t){return bt(t.cwd??t.current_dir??t.project_root)}function Hv(t){let e=bt(t.project);if(e)return e;let n=zv(t);if(n)return bt(Ro.basename(n));let r=dh(t.workspace);return r||""}function pr(t){if(!(typeof t!="number"||!Number.isFinite(t)))return t}function Xv(t){let e=Wv(t).toLowerCase();return e.includes("codex")?vi.CODEX:e.includes("claude")||t.model?.display_name||t.transcript_path||t.rate_limits?vi.CLAUDE_CODE:t.run_state||t.runState||t.thread_title||t.threadTitle||t.git_branch||pr(t.context_used)!==void 0?vi.CODEX:vi.UNKNOWN}function zQ(t){return Xv(t)===vi.CODEX}function Jv(t){let e=Wv(t),n=zv(t),r=dh(t.workspace),o=pr(t.context_used)??pr(t.context_window?.used_percentage??void 0),s=pr(t.context_remaining)??pr(t.context_window?.remaining_percentage??void 0);return{...e?{app:e}:{},...ch(t)?{model:ch(t)}:{},...Hv(t)?{project:Hv(t)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...bt(t.git_branch??t.branch)?{gitBranch:bt(t.git_branch??t.branch)}:{},...bt(t.status??t.run_state??t.runState)?{status:bt(t.status??t.run_state??t.runState)}:{},...bt(t.thread_title??t.threadTitle)?{threadTitle:bt(t.thread_title??t.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...pr(t.used_tokens)!==void 0?{usedTokens:pr(t.used_tokens)}:{},...pr(t.total_input_tokens)!==void 0?{totalInputTokens:pr(t.total_input_tokens)}:{},...pr(t.total_output_tokens)!==void 0?{totalOutputTokens:pr(t.total_output_tokens)}:{}}}function uh(t){return t.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function Ii(t,e){let n=e?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=e??{};return await fetch(t,{...i,signal:r.signal})}finally{clearTimeout(o)}}var Mt=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(e,n,r,o,s,i,a,c){super(e),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}};var Zv={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function ph(t){let e=t&&typeof t=="object"?t:{};if(e.name==="AbortError"||typeof e.message=="string"&&e.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(e.cause&&typeof e.cause=="object"?e.cause.code:void 0)??(typeof e.code=="string"?e.code:void 0);return n&&Zv[n]?Zv[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof e.message=="string"?e.message:"unknown"}`:typeof e.message=="string"&&e.message.length>0?e.message:"unknown error"}). Check https://visacli.sh for status.`}var XQ=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function eI(t,e){let n=Qv(t),r=Qv(e);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:JQ(n.pre,r.pre)>0}function Qv(t){if(typeof t!="string")return null;let n=t.trim().replace(/^v/,"").match(XQ);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function JQ(t,e){let n=t.split("."),r=e.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],c=/^\d+$/.test(i),u=/^\d+$/.test(a);if(c&&u){let l=Number(i)-Number(a);if(l!==0)return l}else{if(c)return-1;if(u)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Vr(){return!!(tI(process.env.VISA_CLI_NO_UPDATE_CHECK)||tI(process.env.CI)||process.env.NODE_ENV==="test")}function tI(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var ds=v(require("fs")),oI=v(require("path"));var jp=v(require("fs")),nI=v(require("path")),rI=v(require("os"));var _h=nI.join(rI.homedir(),".visa-mcp"),el=class{static ensureConfigDir(){jp.existsSync(_h)||jp.mkdirSync(_h,{recursive:!0,mode:448})}static getConfigDir(){return _h}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let e=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||e.add(n);return e}static isToolDisabled(e){return this.TOOL_STATES[e]===!1}};var ZQ="settings.json";function tl(){return oI.join(el.getConfigDir(),ZQ)}var ps={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:t=>{if(typeof t!="string")throw new Error("auth.serverUrl must be a string");let e;try{e=new URL(t)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(t)})`)}if(e.protocol!=="https:"&&e.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${e.protocol})`)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_music, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:t=>{if(typeof t!="string")throw new Error("merchants.discover must be a string");let e=t.trim().toLowerCase();if(e===""||e==="all"||e==="off"||e==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=t.split(",").map(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [100, 10000] = $1\u2013$100. Default 500 ($5).",validate:t=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(t))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(t<100||t>1e4)throw new Error("credit.sessionCapCents must be between 100 ($1) and 10000 ($100)")}}},mh=500,qp={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};function Pi(){let t=tl();if(!ds.existsSync(t))return{};try{let e=ds.readFileSync(t,"utf-8"),n=JSON.parse(e);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function fh(t){el.ensureConfigDir();let e=tl(),n=`${e}.tmp`,r=JSON.stringify(t,null,2)+`
45
- `;ds.writeFileSync(n,r,{mode:384}),ds.renameSync(n,e)}function Eh(t){let e=Pi()[t];return typeof e=="string"?e:void 0}function Yp(t){let e=Pi()[t];if(typeof e=="boolean")return e;if(e==="true")return!0;if(e==="false")return!1}function Sh(t){let e=Pi()[t];if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(Number.isFinite(n))return n}}var yo=class extends Error{constructor(e){let n=Object.keys(ps).sort().join(", ");super(`Unknown setting "${e}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Oo=class extends Error{constructor(e){let n="";e.startsWith("biometric.")?n="biometric_on / biometric_off":e.startsWith("spending.")?n="update_spending_controls":e.startsWith("cards.")?n="add_card / remove_card / set_default_card":e.startsWith("account.")&&(n="login / reset"),super(`"${e}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},ls=class extends Error{constructor(e){super(`"${e}" is retired and ignored. Remove it with \`visa-cli config unset ${e}\`. `+qp[e]),this.name="RetiredSettingKeyError"}},sI=["biometric.","spending.","account.","cards.","biometric"];function Kp(t,e){if(sI.some(s=>t.startsWith(s)))throw new Oo(t);if(t in qp)throw new ls(t);let n=ps[t];if(!n)throw new yo(t);let r;if(n.type==="boolean")if(typeof e=="boolean")r=e;else if(typeof e=="string"){let s=e.toLowerCase();if(s==="true")r=!0;else if(s==="false")r=!1;else throw new Error(`${t} expects true or false (got: ${JSON.stringify(e)})`)}else throw new Error(`${t} expects a boolean (got: ${typeof e})`);else if(n.type==="number")if(typeof e=="number")r=e;else if(typeof e=="string"&&e.trim().length>0){let s=Number(e);if(!Number.isFinite(s))throw new Error(`${t} expects a number (got: ${JSON.stringify(e)})`);r=s}else throw new Error(`${t} expects a number (got: ${typeof e})`);else{if(typeof e!="string"||e.length===0)throw new Error(`${t} expects a non-empty string`);r=e}n.validate&&n.validate(r);let o=Pi();return o[t]=r,fh(o),{key:t,value:r,requiresRestart:!!n.requiresRestart,path:tl()}}function Wp(t){if(sI.some(s=>t.startsWith(s)))throw new Oo(t);let e=ps[t];if(t in qp){let s=Pi(),i=t in s;return i&&(delete s[t],fh(s)),{key:t,removed:i,requiresRestart:!1,path:tl()}}if(!e)throw new yo(t);let r=Pi(),o=t in r;return o&&(delete r[t],fh(r)),{key:t,removed:o,requiresRestart:o&&!!e.requiresRestart,path:tl()}}function iI(){let t=Pi();return Object.entries(qp).filter(([e])=>e in t).map(([e,n])=>({key:e,value:t[e],hint:n}))}var QQ="https://auth.visacli.sh",e7="https://auth-visa-code-preview.up.railway.app";function t7(t){return typeof t=="string"&&/-(?:rc|alpha|beta)\./i.test(t)}function n7(){try{let t=kp();return t7(t.version)}catch{return!1}}function r7(t){return t.envVar!==void 0&&t.envVar!==""?t.envVar:t.settingValue!==void 0?t.settingValue:t.isPrerelease?e7:QQ}function Hn(){return r7({envVar:process.env.VISA_AUTH_URL,settingValue:Eh("auth.serverUrl"),isPrerelease:n7()})}function aI(){let t=process.env.VISA_SUPPRESS_BROWSER;return t!==void 0?t==="true":Yp("ui.suppressBrowser")??!1}function cI(){let t=process.env.VISA_SUPPRESS_FEED;return t!==void 0?t==="true":Yp("ui.suppressFeed")??!1}function zp(){let t=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(t!==void 0){let n=Number(t);if(Number.isFinite(n)&&n>=100&&n<=1e4)return Math.floor(n)}let e=Sh("credit.sessionCapCents");return e!==void 0&&e>=100&&e<=1e4?Math.floor(e):mh}var nl="2.0.0-rc.41",o7=/^vk_[A-Za-z0-9_-]{32,}$/;function uI(t=process.env,e=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=t.VISA_CLI_API_KEY?.trim();return r?o7.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),e===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
46
- `)}var $n=class{constructor(e){this.getSessionToken=e;this.baseUrl=Hn()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!Vr()){let r=e.headers.get("X-Latest-Version");r&&eI(r,nl)&&(this.lastSignals.updateAvailable={currentVersion:nl,latestVersion:r})}let n=e.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return nl}async request(e,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(uI());let c={Authorization:`Bearer ${a}`};s&&(e==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let u;try{u=await Ii(`${this.baseUrl}${n}`,{method:e,headers:{...c,"X-Visa-CLI-Version":nl,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(ph(d))}if(this.parseServerSignals(u),u.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(u.status===429){let d=u.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}if(u.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await u.json()}catch{throw u.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!u.ok){if(u.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(l?.declined){let d=Number(l.retryAfter??u.headers.get("Retry-After"));throw new Mt(l.error||"Your card was declined.",!!l.retryable,l.code,l.reason,l.payment_error_class,l.correlation_id,l.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(u.status===402){let d=l?.error||"Gateway returned 402";throw new Error(`${d}. This usually means your daily or per-transaction spending limit has been reached. Check your limits with get_status or run: visa-cli update-spending-controls`)}throw new Error(l?.error||`Request failed (${u.status}). Try again.`)}return l}async pay(e,n){return this.request("POST","/v1/pay",e,void 0,n)}async shortcut(e,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,n,r,o,s)}async shortcutWithSession(e,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(e)}`,c=await this.getSessionToken();if(!c)throw new Error(uI());let u={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":nl,"X-Source":"cli","Content-Type":"application/json"};i&&(u["X-Visa-Meta-Tool"]=i);let l={...n,...r};s&&(l.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ii(`${this.baseUrl}${a}`,{method:"POST",headers:u,body:JSON.stringify(l),timeoutMs:o})}catch(f){throw new Error(ph(f))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let f=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${f}s. Tip: use the batch tool to combine multiple requests into one.`)}if(d.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let p=d.headers.get("X-Voucher-Receipt"),_;try{_=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(_?.declined){let f=Number(_.retryAfter??d.headers.get("Retry-After"));throw new Mt(_.error||"Your card was declined.",!!_.retryable,_.code,_.reason,_.payment_error_class,_.correlation_id,_.transactionId,Number.isFinite(f)&&f>0?f:void 0)}throw new Error(_?.error||`Request failed (${d.status}). Try again.`)}return{data:_,voucherReceiptHeader:p}}async batch(e,n,r){return this.request("POST","/v1/batch",e,n,r)}async emitTelemetry(e){return this.request("POST","/v1/telemetry",{rows:e})}async catalogSearch(e,n,r){let o=r??"discover_tools",s=new URLSearchParams;e&&s.set("q",e),n&&s.set("category",n);let i=s.toString();return this.request("GET",`/v1/catalog${i?`?${i}`:""}`,void 0,void 0,void 0,o)}async catalogTool(e,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(e){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(e)}`)}catch{return null}}async listPublicMerchants(){try{let e=await Ii(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!e.ok)return[];let n=await e.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(e){try{let n=await Ii(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(e)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(e,n){return this.request("POST","/v1/payment-preview",e,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(e){return this.request("POST","/v1/balance/topup",e)}async createSessionBudget(e){return this.request("POST","/v1/session-budget/create",{...e,mode:"prepaid"})}async closeSession(e){return this.request("POST","/v1/session/close",{session_budget_id:e})}async getSessionBudget(e){return this.request("GET",`/v1/session-budget/${encodeURIComponent(e)}`)}async getSessionLedger(e){return this.request("GET",`/v1/session/${encodeURIComponent(e)}/ledger`)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(e,n){return this.request("POST","/v1/visa/smi",e,6e4,n)}async getTransactions(e,n){let r=new URLSearchParams;e?.limit!=null&&r.set("limit",String(e.limit)),e?.offset!=null&&r.set("offset",String(e.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(e,n){return this.request("POST","/v1/spending-controls",e,void 0,n)}async removeCard(e,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,n,void 0,r)}async setDefaultCard(e,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async startAttestationRecovery(e,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:e},void 0,n)}async setBiometricPreference(e,n){return this.request("POST","/v1/biometric-preference",{...e,confirm:!0},void 0,n)}async logout(e,n){return this.request("POST","/v1/logout",e,void 0,n)}async feedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(e){return this.request("POST","/v1/api/keys",e)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(e){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(e))}`)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let n=new URLSearchParams;e?.tab&&n.set("tab",e.tab),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(e,n){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:n})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async getFeedback(e,n){let r=new URLSearchParams;e&&r.set("limit",String(e));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var C={};Lp(C,{BRAND:()=>b7,DIRTY:()=>bi,EMPTY_PATH:()=>c7,INVALID:()=>z,NEVER:()=>fee,OK:()=>Gt,ParseStatus:()=>Lt,Schema:()=>le,ZodAny:()=>ms,ZodArray:()=>Io,ZodBigInt:()=>Li,ZodBoolean:()=>xi,ZodBranded:()=>ol,ZodCatch:()=>ji,ZodDate:()=>Di,ZodDefault:()=>Fi,ZodDiscriminatedUnion:()=>Zp,ZodEffects:()=>qn,ZodEnum:()=>Hi,ZodError:()=>mn,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>e_,ZodIntersection:()=>Vi,ZodIssueCode:()=>P,ZodLazy:()=>Bi,ZodLiteral:()=>Gi,ZodMap:()=>Fa,ZodNaN:()=>qa,ZodNativeEnum:()=>$i,ZodNever:()=>_r,ZodNull:()=>wi,ZodNullable:()=>Hr,ZodNumber:()=>Mi,ZodObject:()=>En,ZodOptional:()=>Fn,ZodParsedType:()=>U,ZodPipeline:()=>sl,ZodPromise:()=>Es,ZodReadonly:()=>qi,ZodRecord:()=>Qp,ZodSchema:()=>le,ZodSet:()=>ja,ZodString:()=>fs,ZodSymbol:()=>Ha,ZodTransformer:()=>qn,ZodTuple:()=>Gr,ZodType:()=>le,ZodUndefined:()=>Ui,ZodUnion:()=>ki,ZodUnknown:()=>vo,ZodVoid:()=>$a,addIssueToContext:()=>D,any:()=>B7,array:()=>F7,bigint:()=>D7,boolean:()=>TI,coerce:()=>_ee,custom:()=>SI,date:()=>U7,datetimeRegex:()=>mI,defaultErrorMap:()=>No,discriminatedUnion:()=>K7,effect:()=>see,enum:()=>nee,function:()=>Q7,getErrorMap:()=>Va,getParsedType:()=>Br,instanceof:()=>L7,intersection:()=>W7,isAborted:()=>Xp,isAsync:()=>Ba,isDirty:()=>Jp,isValid:()=>_s,late:()=>M7,lazy:()=>eee,literal:()=>tee,makeIssue:()=>rl,map:()=>J7,nan:()=>x7,nativeEnum:()=>ree,never:()=>H7,null:()=>V7,nullable:()=>aee,number:()=>hI,object:()=>j7,objectUtil:()=>gh,oboolean:()=>pee,onumber:()=>dee,optional:()=>iee,ostring:()=>lee,pipeline:()=>uee,preprocess:()=>cee,promise:()=>oee,quotelessJson:()=>s7,record:()=>X7,set:()=>Z7,setErrorMap:()=>a7,strictObject:()=>q7,string:()=>gI,symbol:()=>w7,transformer:()=>see,tuple:()=>z7,undefined:()=>k7,union:()=>Y7,unknown:()=>G7,util:()=>de,void:()=>$7});var de;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(de||(de={}));var gh;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(gh||(gh={}));var U=de.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Br=t=>{switch(typeof t){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(t)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(t)?U.array:t===null?U.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?U.promise:typeof Map<"u"&&t instanceof Map?U.map:typeof Set<"u"&&t instanceof Set?U.set:typeof Date<"u"&&t instanceof Date?U.date:U.object;default:return U.unknown}};var P=de.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),s7=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),mn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,de.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};mn.create=t=>new mn(t);var i7=(t,e)=>{let n;switch(t.code){case P.invalid_type:t.received===U.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,de.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${de.joinValues(t.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${de.joinValues(t.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${de.joinValues(t.options)}, received '${t.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:de.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case P.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case P.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=e.defaultError,de.assertNever(t)}return{message:n}},No=i7;var lI=No;function a7(t){lI=t}function Va(){return lI}var rl=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},c7=[];function D(t,e){let n=Va(),r=rl({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===No?void 0:No].filter(o=>!!o)});t.common.issues.push(r)}var Lt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return z;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return z;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},z=Object.freeze({status:"aborted"}),bi=t=>({status:"dirty",value:t}),Gt=t=>({status:"valid",value:t}),Xp=t=>t.status==="aborted",Jp=t=>t.status==="dirty",_s=t=>t.status==="valid",Ba=t=>typeof Promise<"u"&&t instanceof Promise;var F;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}));var jn=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dI=(t,e)=>{if(_s(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new mn(t.common.issues);return this._error=n,this._error}}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var le=class{get description(){return this._def.description}_getType(e){return Br(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Lt,ctx:{common:e.parent.common,data:e.data,parsedType:Br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Ba(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Br(e)},o=this._parseSync({data:e,path:r.path,parent:r});return dI(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Br(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return _s(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>_s(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Br(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Ba(o)?o:Promise.resolve(o));return dI(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:P.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new qn({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Fn.create(this,this._def)}nullable(){return Hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Io.create(this)}promise(){return Es.create(this,this._def)}or(e){return ki.create([this,e],this._def)}and(e){return Vi.create(this,e,this._def)}transform(e){return new qn({...re(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Fi({...re(this._def),innerType:this,defaultValue:n,typeName:Z.ZodDefault})}brand(){return new ol({typeName:Z.ZodBranded,type:this,...re(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new ji({...re(this._def),innerType:this,catchValue:n,typeName:Z.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return sl.create(this,e)}readonly(){return qi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},u7=/^c[^\s-]{8,}$/i,l7=/^[0-9a-z]+$/,d7=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p7=/^[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}$/i,_7=/^[a-z0-9_-]{21}$/i,f7=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,m7=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,E7=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,S7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hh,g7=/^(?:(?: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])$/,h7=/^(?:(?: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])$/,T7=/^(([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]))$/,A7=/^(([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])$/,R7=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,y7=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_I="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",O7=new RegExp(`^${_I}$`);function fI(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function N7(t){return new RegExp(`^${fI(t)}$`)}function mI(t){let e=`${_I}T${fI(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function C7(t,e){return!!((e==="v4"||!e)&&g7.test(t)||(e==="v6"||!e)&&T7.test(t))}function v7(t,e){if(!f7.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function I7(t,e){return!!((e==="v4"||!e)&&h7.test(t)||(e==="v6"||!e)&&A7.test(t))}var fs=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){let s=this._getOrReturnCtx(e);return D(s,{code:P.invalid_type,expected:U.string,received:s.parsedType}),z}let r=new Lt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:P.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:P.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?D(o,{code:P.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&D(o,{code:P.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")E7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"email",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")hh||(hh=new RegExp(S7,"u")),hh.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"emoji",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")p7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"uuid",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")_7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"nanoid",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")u7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"cuid",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")l7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"cuid2",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")d7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"ulid",code:P.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),D(o,{validation:"url",code:P.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"regex",code:P.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?mI(s).test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?O7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?N7(s).test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{code:P.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?m7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"duration",code:P.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?C7(e.data,s.version)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"ip",code:P.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?v7(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"jwt",code:P.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?I7(e.data,s.version)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"cidr",code:P.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?R7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"base64",code:P.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?y7.test(e.data)||(o=this._getOrReturnCtx(e,o),D(o,{validation:"base64url",code:P.invalid_string,message:s.message}),r.dirty()):de.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:P.invalid_string,...F.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...F.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...F.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...F.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...F.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...F.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...F.errToObj(n)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};fs.create=t=>new fs({checks:[],typeName:Z.ZodString,coerce:t?.coerce??!1,...re(t)});function P7(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Mi=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){let s=this._getOrReturnCtx(e);return D(s,{code:P.invalid_type,expected:U.number,received:s.parsedType}),z}let r,o=new Lt;for(let s of this._def.checks)s.kind==="int"?de.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?P7(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_finite,message:s.message}),o.dirty()):de.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&de.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Mi.create=t=>new Mi({checks:[],typeName:Z.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Li=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let r,o=new Lt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):de.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:U.bigint,received:n.parsedType}),z}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Li.create=t=>new Li({checks:[],typeName:Z.ZodBigInt,coerce:t?.coerce??!1,...re(t)});var xi=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.boolean,received:r.parsedType}),z}return Gt(e.data)}};xi.create=t=>new xi({typeName:Z.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Di=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){let s=this._getOrReturnCtx(e);return D(s,{code:P.invalid_type,expected:U.date,received:s.parsedType}),z}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return D(s,{code:P.invalid_date}),z}let r=new Lt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:P.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),D(o,{code:P.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):de.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Di.create=t=>new Di({checks:[],coerce:t?.coerce||!1,typeName:Z.ZodDate,...re(t)});var Ha=class extends le{_parse(e){if(this._getType(e)!==U.symbol){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.symbol,received:r.parsedType}),z}return Gt(e.data)}};Ha.create=t=>new Ha({typeName:Z.ZodSymbol,...re(t)});var Ui=class extends le{_parse(e){if(this._getType(e)!==U.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.undefined,received:r.parsedType}),z}return Gt(e.data)}};Ui.create=t=>new Ui({typeName:Z.ZodUndefined,...re(t)});var wi=class extends le{_parse(e){if(this._getType(e)!==U.null){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.null,received:r.parsedType}),z}return Gt(e.data)}};wi.create=t=>new wi({typeName:Z.ZodNull,...re(t)});var ms=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return Gt(e.data)}};ms.create=t=>new ms({typeName:Z.ZodAny,...re(t)});var vo=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Gt(e.data)}};vo.create=t=>new vo({typeName:Z.ZodUnknown,...re(t)});var _r=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:U.never,received:n.parsedType}),z}};_r.create=t=>new _r({typeName:Z.ZodNever,...re(t)});var $a=class extends le{_parse(e){if(this._getType(e)!==U.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.void,received:r.parsedType}),z}return Gt(e.data)}};$a.create=t=>new $a({typeName:Z.ZodVoid,...re(t)});var Io=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==U.array)return D(n,{code:P.invalid_type,expected:U.array,received:n.parsedType}),z;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(D(n,{code:i?P.too_big:P.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(D(n,{code:P.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(D(n,{code:P.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new jn(n,i,n.path,a)))).then(i=>Lt.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new jn(n,i,n.path,a)));return Lt.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:F.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:F.toString(n)}})}nonempty(e){return this.min(1,e)}};Io.create=(t,e)=>new Io({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...re(e)});function Ga(t){if(t instanceof En){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Fn.create(Ga(r))}return new En({...t._def,shape:()=>e})}else return t instanceof Io?new Io({...t._def,type:Ga(t.element)}):t instanceof Fn?Fn.create(Ga(t.unwrap())):t instanceof Hr?Hr.create(Ga(t.unwrap())):t instanceof Gr?Gr.create(t.items.map(e=>Ga(e))):t}var En=class t extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=de.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==U.object){let u=this._getOrReturnCtx(e);return D(u,{code:P.invalid_type,expected:U.object,received:u.parsedType}),z}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _r&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new jn(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof _r){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(D(o,{code:P.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new jn(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Lt.mergeObjectSync(r,u)):Lt.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:F.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of de.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of de.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ga(this)}partial(e){let n={};for(let r of de.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of de.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Fn;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return EI(de.objectKeys(this.shape))}};En.create=(t,e)=>new En({shape:()=>t,unknownKeys:"strip",catchall:_r.create(),typeName:Z.ZodObject,...re(e)});En.strictCreate=(t,e)=>new En({shape:()=>t,unknownKeys:"strict",catchall:_r.create(),typeName:Z.ZodObject,...re(e)});En.lazycreate=(t,e)=>new En({shape:t,unknownKeys:"strip",catchall:_r.create(),typeName:Z.ZodObject,...re(e)});var ki=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new mn(a.ctx.common.issues));return D(n,{code:P.invalid_union,unionErrors:i}),z}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new mn(c));return D(n,{code:P.invalid_union,unionErrors:a}),z}}get options(){return this._def.options}};ki.create=(t,e)=>new ki({options:t,typeName:Z.ZodUnion,...re(e)});var Co=t=>t instanceof Bi?Co(t.schema):t instanceof qn?Co(t.innerType()):t instanceof Gi?[t.value]:t instanceof Hi?t.options:t instanceof $i?de.objectValues(t.enum):t instanceof Fi?Co(t._def.innerType):t instanceof Ui?[void 0]:t instanceof wi?[null]:t instanceof Fn?[void 0,...Co(t.unwrap())]:t instanceof Hr?[null,...Co(t.unwrap())]:t instanceof ol||t instanceof qi?Co(t.unwrap()):t instanceof ji?Co(t._def.innerType):[],Zp=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==U.object)return D(n,{code:P.invalid_type,expected:U.object,received:n.parsedType}),z;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(D(n,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=Co(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...re(r)})}};function Th(t,e){let n=Br(t),r=Br(e);if(t===e)return{valid:!0,data:t};if(n===U.object&&r===U.object){let o=de.objectKeys(e),s=de.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Th(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===U.array&&r===U.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Th(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===U.date&&r===U.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Vi=class extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Xp(s)||Xp(i))return z;let a=Th(s.value,i.value);return a.valid?((Jp(s)||Jp(i))&&n.dirty(),{status:n.value,value:a.data}):(D(r,{code:P.invalid_intersection_types}),z)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vi.create=(t,e,n)=>new Vi({left:t,right:e,typeName:Z.ZodIntersection,...re(n)});var Gr=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==U.array)return D(r,{code:P.invalid_type,expected:U.array,received:r.parsedType}),z;if(r.data.length<this._def.items.length)return D(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),z;!this._def.rest&&r.data.length>this._def.items.length&&(D(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new jn(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Lt.mergeArray(n,i)):Lt.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Gr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gr({items:t,typeName:Z.ZodTuple,rest:null,...re(e)})};var Qp=class t extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==U.object)return D(r,{code:P.invalid_type,expected:U.object,received:r.parsedType}),z;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new jn(r,a,r.path,a)),value:i._parse(new jn(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Lt.mergeObjectAsync(n,o):Lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof le?new t({keyType:e,valueType:n,typeName:Z.ZodRecord,...re(r)}):new t({keyType:fs.create(),valueType:e,typeName:Z.ZodRecord,...re(n)})}},Fa=class extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==U.map)return D(r,{code:P.invalid_type,expected:U.map,received:r.parsedType}),z;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new jn(r,a,r.path,[u,"key"])),value:s._parse(new jn(r,c,r.path,[u,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Fa.create=(t,e,n)=>new Fa({valueType:e,keyType:t,typeName:Z.ZodMap,...re(n)});var ja=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==U.set)return D(r,{code:P.invalid_type,expected:U.set,received:r.parsedType}),z;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(D(r,{code:P.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(D(r,{code:P.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return z;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new jn(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:F.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ja.create=(t,e)=>new ja({valueType:t,minSize:null,maxSize:null,typeName:Z.ZodSet,...re(e)});var e_=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==U.function)return D(n,{code:P.invalid_type,expected:U.function,received:n.parsedType}),z;function r(a,c){return rl({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Va(),No].filter(u=>!!u),issueData:{code:P.invalid_arguments,argumentsError:c}})}function o(a,c){return rl({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Va(),No].filter(u=>!!u),issueData:{code:P.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Es){let a=this;return Gt(async function(...c){let u=new mn([]),l=await a._def.args.parseAsync(c,s).catch(_=>{throw u.addIssue(r(c,_)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(_=>{throw u.addIssue(o(d,_)),u})})}else{let a=this;return Gt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new mn([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new mn([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Gr.create(e).rest(vo.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Gr.create([]).rest(vo.create()),returns:n||vo.create(),typeName:Z.ZodFunction,...re(r)})}},Bi=class extends le{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Bi.create=(t,e)=>new Bi({getter:t,typeName:Z.ZodLazy,...re(e)});var Gi=class extends le{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return D(n,{received:n.data,code:P.invalid_literal,expected:this._def.value}),z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gi.create=(t,e)=>new Gi({value:t,typeName:Z.ZodLiteral,...re(e)});function EI(t,e){return new Hi({values:t,typeName:Z.ZodEnum,...re(e)})}var Hi=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{expected:de.joinValues(r),received:n.parsedType,code:P.invalid_type}),z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{received:n.data,code:P.invalid_enum_value,options:r}),z}return Gt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Hi.create=EI;var $i=class extends le{_parse(e){let n=de.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==U.string&&r.parsedType!==U.number){let o=de.objectValues(n);return D(r,{expected:de.joinValues(o),received:r.parsedType,code:P.invalid_type}),z}if(this._cache||(this._cache=new Set(de.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=de.objectValues(n);return D(r,{received:r.data,code:P.invalid_enum_value,options:o}),z}return Gt(e.data)}get enum(){return this._def.values}};$i.create=(t,e)=>new $i({values:t,typeName:Z.ZodNativeEnum,...re(e)});var Es=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==U.promise&&n.common.async===!1)return D(n,{code:P.invalid_type,expected:U.promise,received:n.parsedType}),z;let r=n.parsedType===U.promise?n.data:Promise.resolve(n.data);return Gt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Es.create=(t,e)=>new Es({type:t,typeName:Z.ZodPromise,...re(e)});var qn=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{D(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return z;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?z:c.status==="dirty"?bi(c.value):n.value==="dirty"?bi(c.value):c});{if(n.value==="aborted")return z;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?z:a.status==="dirty"?bi(a.value):n.value==="dirty"?bi(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?z:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?z:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_s(i))return z;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>_s(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):z);de.assertNever(o)}};qn.create=(t,e,n)=>new qn({schema:t,typeName:Z.ZodEffects,effect:e,...re(n)});qn.createWithPreprocess=(t,e,n)=>new qn({schema:e,effect:{type:"preprocess",transform:t},typeName:Z.ZodEffects,...re(n)});var Fn=class extends le{_parse(e){return this._getType(e)===U.undefined?Gt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Fn.create=(t,e)=>new Fn({innerType:t,typeName:Z.ZodOptional,...re(e)});var Hr=class extends le{_parse(e){return this._getType(e)===U.null?Gt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Hr.create=(t,e)=>new Hr({innerType:t,typeName:Z.ZodNullable,...re(e)});var Fi=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===U.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Fi.create=(t,e)=>new Fi({innerType:t,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var ji=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ba(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new mn(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ji.create=(t,e)=>new ji({innerType:t,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var qa=class extends le{_parse(e){if(this._getType(e)!==U.nan){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:U.nan,received:r.parsedType}),z}return{status:"valid",value:e.data}}};qa.create=t=>new qa({typeName:Z.ZodNaN,...re(t)});var b7=Symbol("zod_brand"),ol=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},sl=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?z:s.status==="dirty"?(n.dirty(),bi(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?z:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Z.ZodPipeline})}},qi=class extends le{_parse(e){let n=this._def.innerType._parse(e),r=o=>(_s(o)&&(o.value=Object.freeze(o.value)),o);return Ba(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};qi.create=(t,e)=>new qi({innerType:t,typeName:Z.ZodReadonly,...re(e)});function pI(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function SI(t,e={},n){return t?ms.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=pI(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=pI(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ms.create()}var M7={object:En.lazycreate},Z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Z||(Z={}));var L7=(t,e={message:`Input not instance of ${t.name}`})=>SI(n=>n instanceof t,e),gI=fs.create,hI=Mi.create,x7=qa.create,D7=Li.create,TI=xi.create,U7=Di.create,w7=Ha.create,k7=Ui.create,V7=wi.create,B7=ms.create,G7=vo.create,H7=_r.create,$7=$a.create,F7=Io.create,j7=En.create,q7=En.strictCreate,Y7=ki.create,K7=Zp.create,W7=Vi.create,z7=Gr.create,X7=Qp.create,J7=Fa.create,Z7=ja.create,Q7=e_.create,eee=Bi.create,tee=Gi.create,nee=Hi.create,ree=$i.create,oee=Es.create,see=qn.create,iee=Fn.create,aee=Hr.create,cee=qn.createWithPreprocess,uee=sl.create,lee=()=>gI().optional(),dee=()=>hI().optional(),pee=()=>TI().optional(),_ee={string:(t=>fs.create({...t,coerce:!0})),number:(t=>Mi.create({...t,coerce:!0})),boolean:(t=>xi.create({...t,coerce:!0})),bigint:(t=>Li.create({...t,coerce:!0})),date:(t=>Di.create({...t,coerce:!0}))};var fee=z;var AI=["tempo","mpp_self","merchant_self"];var Ah=C.object({inputPerMillion:C.number().positive(),outputPerMillion:C.number().positive(),contextWindow:C.number().int().positive().optional(),maxOutput:C.number().int().positive().optional()}),mee=C.object({strategy:C.enum(["flat","token","band"]).optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),priceCents:C.number().nonnegative().optional(),currency:C.string().optional(),display:C.string().optional(),estimate:C.boolean().optional(),source:C.string().optional(),priceBand:C.record(C.unknown()).optional(),tokenPricing:Ah.optional()}).passthrough(),Rh=C.discriminatedUnion("type",[C.object({type:C.literal("shortcut"),routedPath:C.string().min(1).startsWith("/")}),C.object({type:C.literal("custom"),merchantSlug:C.string().min(1),subPath:C.string().optional()}),C.object({type:C.literal("local"),fn:C.string().min(1)}),C.object({type:C.literal("read")})]),yh=C.object({amount:C.number().nonnegative(),currency:C.string().length(3).optional(),display:C.string().optional(),free:C.boolean().optional(),batchDiscount:C.number().min(0).max(100).optional()}),RI=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),yI=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),Eee=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Oh={id:C.string().min(1),name:C.string().min(1),description:C.string().min(1),provider:C.string().min(1),model:C.string().min(1),category:Eee,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:C.string().min(1),isAsync:C.boolean().optional(),pollUrl:C.string().optional(),pollInterval:C.number().positive().optional(),pollTimeout:C.number().positive().optional(),tags:C.array(C.string()).optional(),tokenPricing:Ah.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:mee.optional(),status:C.enum(["available","unavailable"]).optional(),handler:Rh.optional(),pricing:yh.optional(),security:RI.optional(),engagement:yI.optional(),enabled:C.boolean().optional(),beta:C.boolean().optional(),deprecated:C.boolean().optional(),replacementTool:C.string().optional(),minCliVersion:C.string().optional(),sunsetAt:C.string().optional(),rail:C.enum(AI).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},OI=C.object({...Oh,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),NI=C.object({...Oh,dispatch:C.literal("enveloped")}).strict(),CI=C.object({...Oh,handler:Rh,pricing:yh}).strict(),vI=C.union([C.discriminatedUnion("dispatch",[OI,NI]),CI]);var Nh=/^[a-z0-9][a-z0-9_-]*$/;var bI="https://fal.run",gee="https://openrouter.mpp.tempo.xyz";function hee(t){let{attestation:e,tool_id:n,...r}=t;return r}var II={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function t_(t){let{attestation:e,tool_id:n,aspect_ratio:r,image_size:o,...s}=t,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&II[r]&&(i.image_size=II[r]),i)}function st(t,e,n,r,o,s,i,a){return{dispatch:"routed",id:t,name:e,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${bI}/${r}`,merchantName:"fal.ai",buildBody:hee,tags:[],...a}}function Tee(t){return e=>{let{attestation:n,tool_id:r,prompt:o,system_prompt:s,max_tokens:i,temperature:a,...c}=e;return{model:t,messages:[...s?[{role:"system",content:s}]:[],{role:"user",content:o}],max_tokens:i??1024,temperature:a??.7,...c}}}function Ht(t,e,n,r,o,s,i){let a=5e-4*o*100,c=500/1e6*s*100,u=Math.max(1,Math.ceil(a+c));return{dispatch:"routed",id:t,name:e,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${gee}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Tee(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s},...i}}var Ch=[st("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),st("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:t_}),st("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:t_}),st("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:t_}),st("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),st("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),st("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),st("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),st("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),st("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),st("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),st("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),st("fal-stable-audio","Stable Audio","Generate music and sound effects from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","music","sound-effects"]}),st("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","suno/v4","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{tags:["music","song","vocals","instrumental"],merchantName:"Suno AI",isAsync:!0,pollUrl:`${bI}/suno/v4/requests/{requestId}/status`}),st("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),st("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),st("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),st("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),Ht("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),Ht("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),Ht("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),Ht("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),Ht("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),Ht("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),Ht("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),Ht("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),Ht("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),Ht("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),Ht("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),Ht("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),Ht("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),Ht("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),Ht("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),Ht("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),e},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",buildBody:t=>t_({prompt:t.prompt,aspect_ratio:t.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.image_size&&(e.image_size=t.image_size),t.num_inference_steps!==void 0&&(e.num_inference_steps=t.num_inference_steps),t.seed!==void 0&&(e.seed=t.seed),e},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.style&&(e.style=t.style),t.image_size&&(e.image_size=t.image_size),e},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),t.style_type&&(e.style_type=t.style_type),t.negative_prompt&&(e.negative_prompt=t.negative_prompt),e},tags:["image","ideogram","text","legacy"]},st("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:t=>{let e={image_url:t.image_url};return t.scale!==void 0&&(e.scale=t.scale),e},tags:["upscale","esrgan"]}),st("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:t=>{let e={image_url:t.image_url,prompt:t.prompt};return t.seed!==void 0&&(e.seed=t.seed),e},tags:["image","edit","inpaint","seededit"]}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),t.duration&&(e.duration=t.duration),e},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.negative_prompt&&(e.negative_prompt=t.negative_prompt),t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),t.duration&&(e.duration=t.duration),t.seed!==void 0&&(e.seed=t.seed),e},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.negative_prompt&&(e.negative_prompt=t.negative_prompt),t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),t.seed!==void 0&&(e.seed=t.seed),e},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",buildBody:t=>{let e={prompt:t.prompt};return t.aspect_ratio&&(e.aspect_ratio=t.aspect_ratio),t.seed!==void 0&&(e.seed=t.seed),e},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:t=>`https://fal.mpp.tempo.xyz/queue/${t.model_path}/requests/${t.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",buildBody:t=>{let e={object_prompt:t.object_prompt};return t.style_prompt&&(e.style_prompt=t.style_prompt),t.negative_prompt&&(e.negative_prompt=t.negative_prompt),t.art_style&&(e.art_style=t.art_style),t.seed!==void 0&&(e.seed=t.seed),e},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:t=>{let e={gen_text:t.gen_text};return t.ref_audio_url&&(e.ref_audio_url=t.ref_audio_url),t.ref_text&&(e.ref_text=t.ref_text),t.remove_silence!==void 0&&(e.remove_silence=t.remove_silence),e},tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:t=>({prompt:t.prompt,customMode:!1,instrumental:t.instrumental??!1,model:t.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:t=>({taskId:t.taskId}),tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:t=>t.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:t=>{let e={chain:t.chain,token_address:t.token_address};if(t.start_timestamp){let n=t.end_timestamp||new Date().toISOString(),r=t.time_granularity;if(!r){let o=new Date(t.start_timestamp).getTime();(new Date(n).getTime()-o)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[e],start_timestamp:t.start_timestamp,end_timestamp:n,time_granularity:r}}return[e]},tags:["onchain","prices","allium","crypto","legacy"]}];function n_(t){return Ch.find(e=>e.id===t)}var MI=1,LI=["pick_one","fan_out"],xI=["concat","dedupe_by_url","top_k_by_score"],Ree=8,yee=C.object({type:C.string().min(1),description:C.string().min(1),enum:C.array(C.string()).optional(),default:C.unknown().optional(),minimum:C.number().optional(),maximum:C.number().optional()}),Oee=C.object({toolId:C.string().min(1),notes:C.string().min(1)}),Nee=C.object({providers:C.array(C.string().min(1)).min(1).max(Ree),merge:C.enum(xI),maxResults:C.number().int().positive().optional()}),DI=C.object({mode:C.enum(LI).default("pick_one"),intro:C.string().min(1),defaultTier:C.string().min(1),tiers:C.record(C.string(),Oee).refine(t=>Object.keys(t).length>0,{message:"must have at least one tier"}),fanOut:Nee.optional(),guidance:C.string().min(1),inputProperties:C.record(C.string(),yee),required:C.array(C.string())}).refine(t=>t.tiers[t.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(t=>t.mode!=="fan_out"||t.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(t=>t.required.every(e=>e in t.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Cee=C.object({version:C.literal(MI),generatedAt:C.string().datetime(),tools:C.record(C.string().regex(Nh,"tool name must match MCP naming rules"),DI).refine(t=>Object.keys(t).length>0,{message:"manifest must have at least one tool"})});var Mh=require("child_process"),GI=require("util"),HI=v(require("crypto")),$t=v(require("fs")),$I=v(require("os")),$r=v(require("path"));var Sn=v(require("fs")),Ph=v(require("path")),UI=v(require("os")),Ih=Ph.join(UI.homedir(),".visa-mcp"),il=Ph.join(Ih,"mcp-server.log"),Pee=5*1024*1024,vh=null;function bee(){Sn.existsSync(Ih)||Sn.mkdirSync(Ih,{recursive:!0,mode:448})}function Mee(){if(!vh){if(bee(),Sn.existsSync(il)&&Sn.statSync(il).size>Pee){let e=il+".1";Sn.existsSync(e)&&Sn.unlinkSync(e),Sn.renameSync(il,e)}vh=Sn.createWriteStream(il,{flags:"a"})}return vh}function Lee(t){return t==="WARN"||t==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function r_(t,...e){let n=new Date().toISOString(),r=e.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${t}] ${r}
47
- `;Lee(t)&&process.stderr.write(o),Mee().write(o)}var T={debug:(...t)=>r_("DEBUG",...t),info:(...t)=>r_("INFO",...t),warn:(...t)=>r_("WARN",...t),error:(...t)=>r_("ERROR",...t)};var Ya=(0,GI.promisify)(Mh.execFile),i_=$r.join($I.homedir(),".visa-mcp","bin"),Yi=$r.join(i_,"Visa CLI"),xee=$r.join(__dirname,"..","native"),wI="5",kI=$r.join(i_,"visa-keychain.version"),VI=$r.join(i_,"visa-keychain.sha256");function BI(t){let e=$t.readFileSync(t);return HI.createHash("sha256").update(e).digest("hex")}async function FI(){try{if($t.readFileSync(kI,"utf-8").trim()===wI&&$t.existsSync(Yi)){let r=$t.readFileSync(VI,"utf-8").trim();if(BI(Yi)!==r)T.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),$t.unlinkSync(Yi);else return Yi}}catch{}let t=$r.join(xee,"visa-keychain.m");if($t.existsSync(t)||(t=$r.resolve(__dirname,"..","..","native","visa-keychain.m")),$t.existsSync(t)||(t=$r.resolve(__dirname,"..","native","visa-keychain.m")),!$t.existsSync(t))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");$t.mkdirSync(i_,{recursive:!0,mode:448});try{await Ya("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Yi,t],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let e=BI(Yi);return $t.writeFileSync(VI,e,{mode:384}),$t.writeFileSync(kI,wI,{mode:384}),Yi}async function jI(t){let e=await FI(),n;try{n=(await Ya(e,t,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}var bh=null;function it(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:bh!==null?bh:(bh=!0,!0)}var o_="visa-cli",s_="attestation-key";async function Dee(t){try{await Ya("security",["delete-generic-password","-s",o_,"-a",s_],{timeout:5e3})}catch{}await Ya("security",["add-generic-password","-s",o_,"-a",s_,"-w",t],{timeout:5e3})}async function Uee(){try{let{stdout:t}=await Ya("security",["find-generic-password","-s",o_,"-a",s_,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function a_(){let t=await jI(["generate-key"]);if(!t)throw new Error("Key generation returned no output");let e=t.indexOf(":");if(e<0)throw new Error("Unexpected generate-key output format");let n=t.slice(0,e),r=t.slice(e+1);return await Dee(n),r}async function Ka(t,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Uee();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await FI(),o=["sign",t];return e&&o.push(e),new Promise((s,i)=>{let a=(0,Mh.execFile)(r,o,{timeout:6e4},(c,u)=>{let l=(u||"").trim();if(c){l.startsWith("ERROR:")?i(new Error(l.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}l.startsWith("OK:")?s(l.slice(3)):i(new Error(l.startsWith("ERROR:")?l.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function c_(){try{await Ya("security",["delete-generic-password","-s",o_,"-a",s_],{timeout:5e3})}catch{}try{await jI(["delete-key"])}catch{}}var wee=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],kee=[...wee.map(t=>({id:`legacy.${t}`,match:{kind:"exact_tool",toolId:t},targetToolId:t,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function xh(t,e=kee){for(let r of e)if(r.match.kind==="exact_tool"&&r.match.toolId===t.requestedTool)return r.targetToolId;let n=Lh(t.intentText);for(let r of e)if(r.match.kind==="intent"&&r.match.metaTool===t.metaTool&&!(r.match.tier&&r.match.tier!==t.tier)&&!(r.match.provider&&!n.includes(Lh(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Lh(o))))return r.targetToolId;return null}function Lh(t){return(t??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var qI={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Call check_fal_status_card with those values to poll for completion. Do not poll more than once per 30 seconds.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech (voice cloning) or sound effects.",tiers:{tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"},sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:"For tts: provide text + audio_url (voice sample to clone). For sfx: provide prompt describing the sound.",inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for MetaVoice)."}},required:[]},generate_3d:{intro:"Generate a 3D model from an image.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered pricing is shown per model.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Dh(t,e,n){if(!KI(t))return Gee(t,n);let r=YI[t];if(!r)return t;let o=Object.keys(r.tiers),s=e||o[0],i=Hee(t,s,n);return i||$ee(t,r,s,o)}function Gee(t,e){return xh({requestedTool:t,intentText:e})??t}function Hee(t,e,n){return xh({requestedTool:t,metaTool:t,tier:e,intentText:n})}function $ee(t,e,n,r){let o=e.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${t}. Valid tiers: ${r.join(", ")}`);return o.toolId}var YI=qI;function KI(t){return t in YI}var al=Object.keys(qI);function Uh(t=process.env){let e=t.VISA_DRY_RUN;return e==="true"||e==="1"||e==="mock"?"mock":e==="preflight"?"preflight":null}function WI(t=process.env){return Uh(t)!==null}var xt=v(require("crypto")),DP=require("child_process"),fr=v(require("fs")),ml=v(require("os")),I_=v(require("path"));var Ce=v(require("fs")),p_=v(require("os")),we=v(require("path")),JI=require("child_process");var zI=v(require("fs")),Fee=["npm","pnpm","yarn","bun"],jee=/\s+/;function qee(){let t=process.env.npm_config_user_agent;if(!t)return;let e=t.trim();if(e==="")return;let n=e.split(jee)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Fee.includes(o)?o:void 0}function wh(t){if(!t)return;let e=t;try{e=zI.realpathSync(t)}catch{}let n=e.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function Yee(t=process.argv[1]){return qee()??wh(process.env.npm_execpath)??wh(process.env.npm_node_execpath)??wh(t)}function kh(t,e,n){let r=e??Yee(n)??"npm",s=`@visa/cli@${t??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",s],display:`npm install -g ${s}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",s],display:`pnpm add -g ${s}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",s],display:`yarn global add ${s}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",s],display:`bun add -g ${s}`}}}function za(t,e,n){return kh(t,e,n).display}var Kee=2,cl="# >>> visa-cli shell hud v2 >>>",l_="# <<< visa-cli shell hud v2 <<<",ZI="# >>> visa-cli shell hud >>>",Wee="# <<< visa-cli shell hud <<<",QI=3e4,zee="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Xee={currentVersion:"0.0.0"},Jee=3e4;function Gh(){try{return we.join(jh(),".visa-cli")}catch{return we.join(p_.tmpdir(),".visa-cli")}}function Ja(){return we.join(Gh(),"shell-hud.json")}function __(){return we.join(Gh(),"shell-hud.line")}function eP(){return we.join(Gh(),"shell-hud.lock")}function Qa(t){let e=t??process.env.SHELL;if(!e)return null;let n=we.basename(e.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function ll(t){let e=jh();if(t==="zsh")return we.join(e,".zshrc");if(t==="bash")return we.join(e,".bashrc");let n=(process.platform==="win32","PowerShell");return we.join(e,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Zee(t){let e=jh(),n=[{shell:"zsh",rcPath:we.join(e,".zshrc")},{shell:"bash",rcPath:we.join(e,".bashrc")},{shell:"bash",rcPath:we.join(e,".bash_profile")},{shell:"powershell",rcPath:we.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!t)return n;let r=n.filter(s=>s.shell===t),o=n.filter(s=>s.shell!==t);return[...r,...o]}function Qee(t){let e="$HOME/.visa-cli/shell-hud.line",n=ute(t),r=lte(t);if(t==="zsh")return`${cl}
21
+ `),process.exit(1)}var No=require("child_process");function rs(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function Qc(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
22
+ `)}function ss(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function os(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((l,c,u)=>{(0,No.execFile)(l,c,m=>u(m))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of Qc(e).split(`
23
+ `))n(` ${l}`);n("");let i=rs(r,s);if(i.headless){n(` (${i.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let a=ss(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{o(a.cmd,a.args,c=>{c?(n(` Could not open browser automatically (${c.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()})})}function el(e){return new Promise(t=>setTimeout(t,e))}function Uo(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e*1e3;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1e3;let n=Date.parse(e);return Number.isFinite(n)?Math.max(n-Date.now(),0):null}function Do(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function tl(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Uo(e.headers?.get("Retry-After"));if(r!==null)return n(Do(r));if(typeof e.json=="function")try{let s=await e.json();return n(Do(Uo(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function tt(e,t){let n=await tl(e);return t?.(n),await el(n),n}var jo=A(require("crypto")),ue=A(require("fs")),Yn=A(require("path"));function Vo(e,t){ue.mkdirSync(Yn.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${jo.randomBytes(8).toString("hex")}.tmp`;try{ue.writeFileSync(n,JSON.stringify(t,null,2)+`
24
+ `),ue.renameSync(n,e)}catch(r){try{ue.unlinkSync(n)}catch{}throw r}}function Lo(e){return`'${e.replace(/'/g,"'\\''")}'`}var qo="# visa-cli-hud-v1";function nl(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Yn.resolve(r):"";return`${s?`${Lo(n)} ${Lo(s)} config statusline`:"visa-cli config statusline"} ${qo}`}function _t(e){return typeof e!="string"?!1:e.includes(qo)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Zn(e,t=nl){let n={},r=!1;if(ue.existsSync(e)){r=!0;try{n=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return _t(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},Vo(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function is(e){if(!ue.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return _t(n)?(delete t.statusLine,Vo(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var Ve=A(require("fs")),qe=A(require("path")),rl=1,vt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},sl=["terminal","claude","claude-code","codex","all"];function ms(e){let t=e.toLowerCase();return sl.includes(t)?t:null}var ol=50,il=64*1024,Fo=10,as=80;function al(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var cs=al(),C={reset:"\x1B[0m",visaBlue:cs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:cs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:cs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function E(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${C.reset}`}function Bo(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Wo(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let m=JSON.parse(u);o(m&&typeof m=="object"?m:null)}catch{o(null)}},l=()=>o(null),c=setTimeout(()=>{n.length>0?a():o(null)},ol);e.on("data",i),e.on("end",a),e.on("error",l)})}function Xn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${E(r||"",C.visaBlueSoft)}${E(s||"",C.dim)}`}function ls(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Ho(e){if(_l(e))return cl(e);let t=` ${E("\u2502",C.dim)} `,n=us(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",s=ps(e.workspace),o=r||s,i=s&&s!==o?` ${E(`@${s}`,C.visaBlueSoft)}`:"",a=[E(`[${n}]`,C.visaBlueSoft)];o&&a.push(`${E(o,C.visaGold)}${i}`);let l=a.join(t),c=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,m=e.context_window?.current_usage,h=[m?.input_tokens,m?.output_tokens,m?.cache_creation_input_tokens,m?.cache_read_input_tokens].filter(U=>typeof U=="number"&&Number.isFinite(U)),v=h.length>0?h.reduce((U,J)=>U+J,0):null,g=Number(e.context_window?.total_input_tokens??v??m?.input_tokens??0),x=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,g/c)):0,O=u!==null&&c>0?Math.round(x*c):g,F;if(c>0||u!==null){let U=`${String(Math.round(x*100)).padStart(2," ")}%`,J=c>0?` ${E(`(${ls(O)}/${ls(c)})`,C.dim)}`:"";F=`${E("Context",C.dim)} ${Xn(x)} ${E(U,C.green)}${J}`}else F=`${E("Context",C.dim)} ${E("-",C.dim)}`;let j=ul(e.rate_limits),k=[F];j&&k.push(j);let P=k.join(t);return`${l}
25
+ ${P}`}function cl(e){let t=` ${E("\u2502",C.dim)} `,n=ri(e),r=n.model||"codex",s=[E(`[${r}]`,C.visaBlueSoft)];n.project&&s.push(E(n.project,C.visaGold)),n.gitBranch&&s.push(`${E("git",C.dim)} ${E(n.gitBranch,C.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${E("Context",C.dim)} ${Xn(l)} ${E(`${Math.round(n.contextUsedPercent)}%`,C.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${E("Context",C.dim)} ${Xn(c)} ${E(`${Math.round(l)}%`,C.green)}`)}typeof n.usedTokens=="number"&&i.push(`${E("Tokens",C.dim)} ${ls(n.usedTokens)}`),n.status&&i.push(`${E("Status",C.dim)} ${E(n.status,C.visaBlueSoft)}`),n.threadTitle&&i.push(`${E("Thread",C.dim)} ${E(n.threadTitle,C.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${E("Context",C.dim)} ${E("-",C.dim)}`;return`${o}
26
+ ${a}`}function ll(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Ko(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Xn(r),o=n>=90?"\x1B[38;5;196m":n>=70?C.visaGold:C.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=ll(e.resets_at),l=a?` ${E(`(${a} / ${t})`,C.dim)}`:` ${E(`(${t})`,C.dim)}`;return`${s} ${E(i,o)}${l}`}function ul(e){if(!e)return null;let t=Ko(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ko(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${E("\u2502",C.dim)} `,o=[t,r].filter(Boolean);return`${E("Usage",C.dim)} ${o.join(s)}`}function Jo(e){let t;try{let n=Ve.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,il),o=r-s;t=Ve.openSync(e,"r");let i=Buffer.alloc(s);Ve.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let l=Buffer.alloc(1);if(Ve.readSync(t,l,0,1,o-1),l[0]!==10){let c=a.indexOf(`
27
+ `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{Ve.closeSync(t)}catch{}}}function dl(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=qe.basename(qe.dirname(s)),i=qe.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function ml(e){let t=e.split(`
28
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Fo*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let m=u;if(m.type==="tool_result"&&typeof m.tool_use_id=="string")r.add(m.tool_use_id);else if(m.type==="tool_use"&&typeof m.name=="string"){let h=typeof m.id=="string"?m.id:"",v=h.length>0?!r.has(h):!1;n.push({name:m.name,target:dl(m.input),running:v})}}}return n.reverse(),n.slice(Math.max(0,n.length-Fo))}function pl(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function fl(e){let t=e.running?E("\u25D0",C.visaGold):E("\u2713",C.green),n=e.running?C.visaGold:C.visaBlueSoft,r=E(te(e.name),n),s=e.target?te(e.target):"",o=s?`${E(":",C.dim)} ${E(s,C.dim)}`:"",i=e.count>1?` ${E(`\xD7${e.count}`,C.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function gl(e){let t=` ${E("\u2502",C.dim)} `,n=Bo(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Bo(l)<=as)return l;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>as-n-1?i.slice(0,as-n-1)+s:i;return`${E(s,C.dim)}${t}${a}`}async function Go(e){if(!e||typeof e!="string")return null;let t=Jo(e);if(!t)return null;let n;try{n=ml(t)}catch{return null}if(n.length===0)return null;let s=pl(n).map(fl);return gl(s)||null}async function Yo(e,t,n){return(await Xo(e,t,n)).join(`
29
+ `)}function Zo(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?yl(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Xo(e,t,n){let{isActive:r}=Zo(e,n,t?.transcript_path);if(t&&!r){let o=[],i=Ho(t);if(i&&o.push(...i.split(`
30
+ `)),t.transcript_path){let l=await Go(t.transcript_path);l&&o.push(...l.split(`
31
+ `))}let a=E(ds(e),C.dim);return o.push(a),o}let s=[e];if(t){let o=Ho(t);if(o&&s.push(...o.split(`
32
+ `)),t.transcript_path){let i=await Go(t.transcript_path);i&&s.push(...i.split(`
33
+ `))}}return s}var hl=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function yl(e){let t=Jo(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return hl.some(r=>n.includes(`"${r}"`))}async function Qo(e,t,n){let r=await Xo(e,t,n),s=r.join(`
34
+ `),{isActive:o}=Zo(e,n,t?.transcript_path);return{schemaVersion:rl,client:t?ni(t):vt.UNKNOWN,rendered:s,lines:r.map(ds),visa:{spendLine:ds(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?ri(t):{}}}function te(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function ps(e){if(typeof e=="string")return te(qe.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return te(t?qe.basename(t):e.name)}function ei(e){return te(e.app_name??e.appName??e.app??e.client)}function us(e){return te(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function ti(e){return te(e.cwd??e.current_dir??e.project_root)}function zo(e){let t=te(e.project);if(t)return t;let n=ti(e);if(n)return te(qe.basename(n));let r=ps(e.workspace);return r||""}function ke(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function ni(e){let t=ei(e).toLowerCase();return t.includes("codex")?vt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?vt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ke(e.context_used)!==void 0?vt.CODEX:vt.UNKNOWN}function _l(e){return ni(e)===vt.CODEX}function ri(e){let t=ei(e),n=ti(e),r=ps(e.workspace),s=ke(e.context_used)??ke(e.context_window?.used_percentage??void 0),o=ke(e.context_remaining)??ke(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...us(e)?{model:us(e)}:{},...zo(e)?{project:zo(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...te(e.git_branch??e.branch)?{gitBranch:te(e.git_branch??e.branch)}:{},...te(e.status??e.run_state??e.runState)?{status:te(e.status??e.run_state??e.runState)}:{},...te(e.thread_title??e.threadTitle)?{threadTitle:te(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...ke(e.used_tokens)!==void 0?{usedTokens:ke(e.used_tokens)}:{},...ke(e.total_input_tokens)!==void 0?{totalInputTokens:ke(e.total_input_tokens)}:{},...ke(e.total_output_tokens)!==void 0?{totalOutputTokens:ke(e.total_output_tokens)}:{}}}function ds(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var ne=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var si={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function fs(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&si[n]?si[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var vl=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ii(e,t){let n=oi(e),r=oi(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:bl(n.pre,r.pre)>0}function oi(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(vl);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function bl(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Me(){return!!(ai(process.env.VISA_CLI_NO_UPDATE_CHECK)||ai(process.env.CI)||process.env.NODE_ENV==="test")}function ai(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var rt=A(require("fs")),ui=A(require("path"));var Qn=A(require("fs")),ci=A(require("path")),li=A(require("os"));var gs=ci.join(li.homedir(),".visa-mcp"),pn=class{static ensureConfigDir(){Qn.existsSync(gs)||Qn.mkdirSync(gs,{recursive:!0,mode:448})}static getConfigDir(){return gs}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};var Sl="settings.json";function fn(){return ui.join(pn.getConfigDir(),Sl)}var st={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");let t;try{t=new URL(e)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(e)})`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${t.protocol})`)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_music, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [100, 10000] = $1\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<100||e>1e4)throw new Error("credit.sessionCapCents must be between 100 ($1) and 10000 ($100)")}}},ys=500,er={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};function St(){let e=fn();if(!rt.existsSync(e))return{};try{let t=rt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function hs(e){pn.ensureConfigDir();let t=fn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
35
+ `;rt.writeFileSync(n,r,{mode:384}),rt.renameSync(n,t)}function _s(e){let t=St()[e];return typeof t=="string"?t:void 0}function tr(e){let t=St()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function vs(e){let t=St()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}var Fe=class extends Error{constructor(t){let n=Object.keys(st).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Be=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},nt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+er[t]),this.name="RetiredSettingKeyError"}},di=["biometric.","spending.","account.","cards.","biometric"];function nr(e,t){if(di.some(o=>e.startsWith(o)))throw new Be(e);if(e in er)throw new nt(e);let n=st[e];if(!n)throw new Fe(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=St();return s[e]=r,hs(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:fn()}}function rr(e){if(di.some(o=>e.startsWith(o)))throw new Be(e);let t=st[e];if(e in er){let o=St(),i=e in o;return i&&(delete o[e],hs(o)),{key:e,removed:i,requiresRestart:!1,path:fn()}}if(!t)throw new Fe(e);let r=St(),s=e in r;return s&&(delete r[e],hs(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:fn()}}function mi(){let e=St();return Object.entries(er).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var wl="https://auth.visacli.sh",xl="https://auth-visa-code-preview.up.railway.app";function Cl(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function kl(){try{let e=Gn();return Cl(e.version)}catch{return!1}}function Tl(e){return e.envVar!==void 0&&e.envVar!==""?e.envVar:e.settingValue!==void 0?e.settingValue:e.isPrerelease?xl:wl}function _e(){return Tl({envVar:process.env.VISA_AUTH_URL,settingValue:_s("auth.serverUrl"),isPrerelease:kl()})}function pi(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":tr("ui.suppressBrowser")??!1}function fi(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":tr("ui.suppressFeed")??!1}function sr(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return Math.floor(n)}let t=vs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?Math.floor(t):ys}var gn="2.0.0-rc.42",Al=/^vk_[A-Za-z0-9_-]{32,}$/;function gi(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r?Al.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
36
+ `)}var ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=_e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Me()){let r=t.headers.get("X-Latest-Version");r&&ii(r,gn)&&(this.lastSignals.updateAvailable={currentVersion:gn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return gn}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(gi());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await bt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":gn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(m){throw new Error(fs(m))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let m=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(u?.declined){let m=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ne(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(m)&&m>0?m:void 0)}if(c.status===402){let m=u?.error||"Gateway returned 402";throw new Error(`${m}. This usually means your daily or per-transaction spending limit has been reached. Check your limits with get_status or run: visa-cli update-spending-controls`)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(gi());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":gn,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let m;try{m=await bt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(g){throw new Error(fs(g))}if(this.parseServerSignals(m),m.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(m.status===429){let g=m.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}if(m.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let h=m.headers.get("X-Voucher-Receipt"),v;try{v=await m.json()}catch{throw m.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${a}. Try again.`)}if(!m.ok){if(m.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(v?.declined){let g=Number(v.retryAfter??m.headers.get("Retry-After"));throw new ne(v.error||"Your card was declined.",!!v.retryable,v.code,v.reason,v.payment_error_class,v.correlation_id,v.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(v?.error||`Request failed (${m.status}). Try again.`)}return{data:v,voucherReceiptHeader:h}}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r){let s=r??"discover_tools",o=new URLSearchParams;t&&o.set("q",t),n&&o.set("category",n);let i=o.toString();return this.request("GET",`/v1/catalog${i?`?${i}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await bt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await bt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};$o(p,{BRAND:()=>Ql,DIRTY:()=>wt,EMPTY_PATH:()=>Il,INVALID:()=>S,NEVER:()=>Du,OK:()=>ie,ParseStatus:()=>re,Schema:()=>I,ZodAny:()=>at,ZodArray:()=>ze,ZodBigInt:()=>Ct,ZodBoolean:()=>kt,ZodBranded:()=>yn,ZodCatch:()=>Ut,ZodDate:()=>Tt,ZodDefault:()=>Nt,ZodDiscriminatedUnion:()=>ar,ZodEffects:()=>we,ZodEnum:()=>Mt,ZodError:()=>de,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>lr,ZodIntersection:()=>Rt,ZodIssueCode:()=>f,ZodLazy:()=>It,ZodLiteral:()=>Pt,ZodMap:()=>Gt,ZodNaN:()=>Wt,ZodNativeEnum:()=>Ot,ZodNever:()=>Te,ZodNull:()=>Et,ZodNullable:()=>Ue,ZodNumber:()=>xt,ZodObject:()=>me,ZodOptional:()=>be,ZodParsedType:()=>_,ZodPipeline:()=>_n,ZodPromise:()=>ct,ZodReadonly:()=>Dt,ZodRecord:()=>cr,ZodSchema:()=>I,ZodSet:()=>zt,ZodString:()=>it,ZodSymbol:()=>Ht,ZodTransformer:()=>we,ZodTuple:()=>Ne,ZodType:()=>I,ZodUndefined:()=>At,ZodUnion:()=>$t,ZodUnknown:()=>Ge,ZodVoid:()=>Kt,addIssueToContext:()=>y,any:()=>cu,array:()=>mu,bigint:()=>ru,boolean:()=>Ti,coerce:()=>Uu,custom:()=>xi,date:()=>su,datetimeRegex:()=>Si,defaultErrorMap:()=>He,discriminatedUnion:()=>hu,effect:()=>Eu,enum:()=>ku,function:()=>wu,getErrorMap:()=>qt,getParsedType:()=>Oe,instanceof:()=>tu,intersection:()=>yu,isAborted:()=>or,isAsync:()=>Ft,isDirty:()=>ir,isValid:()=>ot,late:()=>eu,lazy:()=>xu,literal:()=>Cu,makeIssue:()=>hn,map:()=>bu,nan:()=>nu,nativeEnum:()=>Tu,never:()=>uu,null:()=>au,nullable:()=>Ru,number:()=>ki,object:()=>pu,objectUtil:()=>bs,oboolean:()=>Nu,onumber:()=>Ou,optional:()=>$u,ostring:()=>Mu,pipeline:()=>Pu,preprocess:()=>Iu,promise:()=>Au,quotelessJson:()=>El,record:()=>vu,set:()=>Su,setErrorMap:()=>Rl,strictObject:()=>fu,string:()=>Ci,symbol:()=>ou,transformer:()=>Eu,tuple:()=>_u,undefined:()=>iu,union:()=>gu,unknown:()=>lu,util:()=>M,void:()=>du});var M;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(M||(M={}));var bs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(bs||(bs={}));var _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Oe=e=>{switch(typeof e){case"undefined":return _.undefined;case"string":return _.string;case"number":return Number.isNaN(e)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(e)?_.array:e===null?_.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?_.promise:typeof Map<"u"&&e instanceof Map?_.map:typeof Set<"u"&&e instanceof Set?_.set:typeof Date<"u"&&e instanceof Date?_.date:_.object;default:return _.unknown}};var f=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),El=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),de=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e);var $l=(e,t)=>{let n;switch(e.code){case f.invalid_type:e.received===_.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case f.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case f.invalid_union:n="Invalid input";break;case f.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case f.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case f.invalid_arguments:n="Invalid function arguments";break;case f.invalid_return_type:n="Invalid function return type";break;case f.invalid_date:n="Invalid date";break;case f.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case f.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case f.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case f.custom:n="Invalid input";break;case f.invalid_intersection_types:n="Intersection results could not be merged";break;case f.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case f.not_finite:n="Number must be finite";break;default:n=t.defaultError,M.assertNever(e)}return{message:n}},He=$l;var hi=He;function Rl(e){hi=e}function qt(){return hi}var hn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Il=[];function y(e,t){let n=qt(),r=hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===He?void 0:He].filter(s=>!!s)});e.common.issues.push(r)}var re=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return S;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return S;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},S=Object.freeze({status:"aborted"}),wt=e=>({status:"dirty",value:e}),ie=e=>({status:"valid",value:e}),or=e=>e.status==="aborted",ir=e=>e.status==="dirty",ot=e=>e.status==="valid",Ft=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var Se=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},yi=(e,t)=>{if(ot(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new de(e.common.issues);return this._error=n,this._error}}};function T(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var I=class{get description(){return this._def.description}_getType(t){return Oe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new re,ctx:{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ft(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)},s=this._parseSync({data:t,path:r.path,parent:r});return yi(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ot(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>ot(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Ft(s)?s:Promise.resolve(s));return yi(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:f.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new we({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return be.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return ct.create(this,this._def)}or(t){return $t.create([this,t],this._def)}and(t){return Rt.create(this,t,this._def)}transform(t){return new we({...T(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Nt({...T(this._def),innerType:this,defaultValue:n,typeName:w.ZodDefault})}brand(){return new yn({typeName:w.ZodBranded,type:this,...T(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ut({...T(this._def),innerType:this,catchValue:n,typeName:w.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return _n.create(this,t)}readonly(){return Dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pl=/^c[^\s-]{8,}$/i,Ml=/^[0-9a-z]+$/,Ol=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nl=/^[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}$/i,Ul=/^[a-z0-9_-]{21}$/i,Dl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ll=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,jl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Vl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ss,ql=/^(?:(?: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])$/,Fl=/^(?:(?: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])$/,Bl=/^(([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]))$/,Hl=/^(([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])$/,Kl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vi="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",zl=new RegExp(`^${vi}$`);function bi(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Wl(e){return new RegExp(`^${bi(e)}$`)}function Si(e){let t=`${vi}T${bi(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Jl(e,t){return!!((t==="v4"||!t)&&ql.test(e)||(t==="v6"||!t)&&Bl.test(e))}function Yl(e,t){if(!Dl.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function Zl(e,t){return!!((t==="v4"||!t)&&Fl.test(e)||(t==="v6"||!t)&&Hl.test(e))}var it=class e extends I{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==_.string){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.string,received:o.parsedType}),S}let r=new re,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")jl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"email",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Ss||(Ss=new RegExp(Vl,"u")),Ss.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"emoji",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Nl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"uuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Ul.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Pl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Ml.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Ol.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ulid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),y(s,{validation:"url",code:f.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"regex",code:f.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Si(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?zl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Wl(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ll.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"duration",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Jl(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ip",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Yl(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"jwt",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Zl(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cidr",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Kl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Gl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64url",code:f.invalid_string,message:o.message}),r.dirty()):M.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:f.invalid_string,...b.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...b.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...b.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...b.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...b.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...b.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...b.errToObj(n)})}nonempty(t){return this.min(1,b.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};it.create=e=>new it({checks:[],typeName:w.ZodString,coerce:e?.coerce??!1,...T(e)});function Xl(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var xt=class e extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==_.number){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.number,received:o.parsedType}),S}let r,s=new re;for(let o of this._def.checks)o.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Xl(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_finite,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&M.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};xt.create=e=>new xt({checks:[],typeName:w.ZodNumber,coerce:e?.coerce||!1,...T(e)});var Ct=class e extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==_.bigint)return this._getInvalidInput(t);let r,s=new re;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.bigint,received:n.parsedType}),S}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ct.create=e=>new Ct({checks:[],typeName:w.ZodBigInt,coerce:e?.coerce??!1,...T(e)});var kt=class extends I{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==_.boolean){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.boolean,received:r.parsedType}),S}return ie(t.data)}};kt.create=e=>new kt({typeName:w.ZodBoolean,coerce:e?.coerce||!1,...T(e)});var Tt=class e extends I{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==_.date){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.date,received:o.parsedType}),S}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_date}),S}let r=new re,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):M.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:b.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Tt.create=e=>new Tt({checks:[],coerce:e?.coerce||!1,typeName:w.ZodDate,...T(e)});var Ht=class extends I{_parse(t){if(this._getType(t)!==_.symbol){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.symbol,received:r.parsedType}),S}return ie(t.data)}};Ht.create=e=>new Ht({typeName:w.ZodSymbol,...T(e)});var At=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.undefined,received:r.parsedType}),S}return ie(t.data)}};At.create=e=>new At({typeName:w.ZodUndefined,...T(e)});var Et=class extends I{_parse(t){if(this._getType(t)!==_.null){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.null,received:r.parsedType}),S}return ie(t.data)}};Et.create=e=>new Et({typeName:w.ZodNull,...T(e)});var at=class extends I{constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};at.create=e=>new at({typeName:w.ZodAny,...T(e)});var Ge=class extends I{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};Ge.create=e=>new Ge({typeName:w.ZodUnknown,...T(e)});var Te=class extends I{_parse(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.never,received:n.parsedType}),S}};Te.create=e=>new Te({typeName:w.ZodNever,...T(e)});var Kt=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.void,received:r.parsedType}),S}return ie(t.data)}};Kt.create=e=>new Kt({typeName:w.ZodVoid,...T(e)});var ze=class e extends I{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==_.array)return y(n,{code:f.invalid_type,expected:_.array,received:n.parsedType}),S;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(y(n,{code:i?f.too_big:f.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(y(n,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(y(n,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Se(n,i,n.path,a)))).then(i=>re.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Se(n,i,n.path,a)));return re.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:b.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:b.toString(n)}})}nonempty(t){return this.min(1,t)}};ze.create=(e,t)=>new ze({type:e,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...T(t)});function Bt(e){if(e instanceof me){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=be.create(Bt(r))}return new me({...e._def,shape:()=>t})}else return e instanceof ze?new ze({...e._def,type:Bt(e.element)}):e instanceof be?be.create(Bt(e.unwrap())):e instanceof Ue?Ue.create(Bt(e.unwrap())):e instanceof Ne?Ne.create(e.items.map(t=>Bt(t))):e}var me=class e extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=M.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==_.object){let c=this._getOrReturnCtx(t);return y(c,{code:f.invalid_type,expected:_.object,received:c.parsedType}),S}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Te&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],m=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Se(s,m,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Te){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(y(s,{code:f.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let m=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Se(s,m,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let m=await u.key,h=await u.value;c.push({key:m,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>re.mergeObjectSync(r,c)):re.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:w.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of M.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of M.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Bt(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of M.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof be;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return wi(M.objectKeys(this.shape))}};me.create=(e,t)=>new me({shape:()=>e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...T(t)});me.strictCreate=(e,t)=>new me({shape:()=>e,unknownKeys:"strict",catchall:Te.create(),typeName:w.ZodObject,...T(t)});me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...T(t)});var $t=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new de(a.ctx.common.issues));return y(n,{code:f.invalid_union,unionErrors:i}),S}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new de(l));return y(n,{code:f.invalid_union,unionErrors:a}),S}}get options(){return this._def.options}};$t.create=(e,t)=>new $t({options:e,typeName:w.ZodUnion,...T(t)});var Ke=e=>e instanceof It?Ke(e.schema):e instanceof we?Ke(e.innerType()):e instanceof Pt?[e.value]:e instanceof Mt?e.options:e instanceof Ot?M.objectValues(e.enum):e instanceof Nt?Ke(e._def.innerType):e instanceof At?[void 0]:e instanceof Et?[null]:e instanceof be?[void 0,...Ke(e.unwrap())]:e instanceof Ue?[null,...Ke(e.unwrap())]:e instanceof yn||e instanceof Dt?Ke(e.unwrap()):e instanceof Ut?Ke(e._def.innerType):[],ar=class e extends I{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.object)return y(n,{code:f.invalid_type,expected:_.object,received:n.parsedType}),S;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ke(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:w.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...T(r)})}};function ws(e,t){let n=Oe(e),r=Oe(t);if(e===t)return{valid:!0,data:e};if(n===_.object&&r===_.object){let s=M.objectKeys(t),o=M.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=ws(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===_.array&&r===_.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=ws(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===_.date&&r===_.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Rt=class extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(or(o)||or(i))return S;let a=ws(o.value,i.value);return a.valid?((ir(o)||ir(i))&&n.dirty(),{status:n.value,value:a.data}):(y(r,{code:f.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Rt.create=(e,t,n)=>new Rt({left:e,right:t,typeName:w.ZodIntersection,...T(n)});var Ne=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.array)return y(r,{code:f.invalid_type,expected:_.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return y(r,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(y(r,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Se(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>re.mergeArray(n,i)):re.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ne.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ne({items:e,typeName:w.ZodTuple,rest:null,...T(t)})};var cr=class e extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.object)return y(r,{code:f.invalid_type,expected:_.object,received:r.parsedType}),S;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Se(r,a,r.path,a)),value:i._parse(new Se(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?re.mergeObjectAsync(n,s):re.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof I?new e({keyType:t,valueType:n,typeName:w.ZodRecord,...T(r)}):new e({keyType:it.create(),valueType:t,typeName:w.ZodRecord,...T(n)})}},Gt=class extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.map)return y(r,{code:f.invalid_type,expected:_.map,received:r.parsedType}),S;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Se(r,a,r.path,[c,"key"])),value:o._parse(new Se(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Gt.create=(e,t,n)=>new Gt({valueType:t,keyType:e,typeName:w.ZodMap,...T(n)});var zt=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.set)return y(r,{code:f.invalid_type,expected:_.set,received:r.parsedType}),S;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(y(r,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(y(r,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return S;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Se(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:b.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};zt.create=(e,t)=>new zt({valueType:e,minSize:null,maxSize:null,typeName:w.ZodSet,...T(t)});var lr=class e extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.function)return y(n,{code:f.invalid_type,expected:_.function,received:n.parsedType}),S;function r(a,l){return hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qt(),He].filter(c=>!!c),issueData:{code:f.invalid_arguments,argumentsError:l}})}function s(a,l){return hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qt(),He].filter(c=>!!c),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof ct){let a=this;return ie(async function(...l){let c=new de([]),u=await a._def.args.parseAsync(l,o).catch(v=>{throw c.addIssue(r(l,v)),c}),m=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(m,o).catch(v=>{throw c.addIssue(s(m,v)),c})})}else{let a=this;return ie(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new de([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(u,o);if(!m.success)throw new de([s(u,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ne.create(t).rest(Ge.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ne.create([]).rest(Ge.create()),returns:n||Ge.create(),typeName:w.ZodFunction,...T(r)})}},It=class extends I{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};It.create=(e,t)=>new It({getter:e,typeName:w.ZodLazy,...T(t)});var Pt=class extends I{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:f.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pt.create=(e,t)=>new Pt({value:e,typeName:w.ZodLiteral,...T(t)});function wi(e,t){return new Mt({values:e,typeName:w.ZodEnum,...T(t)})}var Mt=class e extends I{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{expected:M.joinValues(r),received:n.parsedType,code:f.invalid_type}),S}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{received:n.data,code:f.invalid_enum_value,options:r}),S}return ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Mt.create=wi;var Ot=class extends I{_parse(t){let n=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==_.string&&r.parsedType!==_.number){let s=M.objectValues(n);return y(r,{expected:M.joinValues(s),received:r.parsedType,code:f.invalid_type}),S}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=M.objectValues(n);return y(r,{received:r.data,code:f.invalid_enum_value,options:s}),S}return ie(t.data)}get enum(){return this._def.values}};Ot.create=(e,t)=>new Ot({values:e,typeName:w.ZodNativeEnum,...T(t)});var ct=class extends I{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.promise&&n.common.async===!1)return y(n,{code:f.invalid_type,expected:_.promise,received:n.parsedType}),S;let r=n.parsedType===_.promise?n.data:Promise.resolve(n.data);return ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ct.create=(e,t)=>new ct({type:e,typeName:w.ZodPromise,...T(t)});var we=class extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{y(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return S;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"?wt(l.value):n.value==="dirty"?wt(l.value):l});{if(n.value==="aborted")return S;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?S:a.status==="dirty"?wt(a.value):n.value==="dirty"?wt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?S:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?S:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ot(i))return S;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ot(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):S);M.assertNever(s)}};we.create=(e,t,n)=>new we({schema:e,typeName:w.ZodEffects,effect:t,...T(n)});we.createWithPreprocess=(e,t,n)=>new we({schema:t,effect:{type:"preprocess",transform:e},typeName:w.ZodEffects,...T(n)});var be=class extends I{_parse(t){return this._getType(t)===_.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};be.create=(e,t)=>new be({innerType:e,typeName:w.ZodOptional,...T(t)});var Ue=class extends I{_parse(t){return this._getType(t)===_.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:w.ZodNullable,...T(t)});var Nt=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===_.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Nt.create=(e,t)=>new Nt({innerType:e,typeName:w.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...T(t)});var Ut=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ft(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:w.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...T(t)});var Wt=class extends I{_parse(t){if(this._getType(t)!==_.nan){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.nan,received:r.parsedType}),S}return{status:"valid",value:t.data}}};Wt.create=e=>new Wt({typeName:w.ZodNaN,...T(e)});var Ql=Symbol("zod_brand"),yn=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},_n=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(n.dirty(),wt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:w.ZodPipeline})}},Dt=class extends I{_parse(t){let n=this._def.innerType._parse(t),r=s=>(ot(s)&&(s.value=Object.freeze(s.value)),s);return Ft(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Dt.create=(e,t)=>new Dt({innerType:e,typeName:w.ZodReadonly,...T(t)});function _i(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function xi(e,t={},n){return e?at.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=_i(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=_i(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):at.create()}var eu={object:me.lazycreate},w;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(w||(w={}));var tu=(e,t={message:`Input not instance of ${e.name}`})=>xi(n=>n instanceof e,t),Ci=it.create,ki=xt.create,nu=Wt.create,ru=Ct.create,Ti=kt.create,su=Tt.create,ou=Ht.create,iu=At.create,au=Et.create,cu=at.create,lu=Ge.create,uu=Te.create,du=Kt.create,mu=ze.create,pu=me.create,fu=me.strictCreate,gu=$t.create,hu=ar.create,yu=Rt.create,_u=Ne.create,vu=cr.create,bu=Gt.create,Su=zt.create,wu=lr.create,xu=It.create,Cu=Pt.create,ku=Mt.create,Tu=Ot.create,Au=ct.create,Eu=we.create,$u=be.create,Ru=Ue.create,Iu=we.createWithPreprocess,Pu=_n.create,Mu=()=>Ci().optional(),Ou=()=>ki().optional(),Nu=()=>Ti().optional(),Uu={string:(e=>it.create({...e,coerce:!0})),number:(e=>xt.create({...e,coerce:!0})),boolean:(e=>kt.create({...e,coerce:!0})),bigint:(e=>Ct.create({...e,coerce:!0})),date:(e=>Tt.create({...e,coerce:!0}))};var Du=S;var Ai=["tempo","mpp_self","merchant_self"];var xs=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional()}),Lu=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:xs.optional()}).passthrough(),Cs=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),ks=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),Ei=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),$i=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),ju=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Ts={id:p.string().min(1),name:p.string().min(1),description:p.string().min(1),provider:p.string().min(1),model:p.string().min(1),category:ju,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:p.string().min(1),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:xs.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Lu.optional(),status:p.enum(["available","unavailable"]).optional(),handler:Cs.optional(),pricing:ks.optional(),security:Ei.optional(),engagement:$i.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(Ai).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},Ri=p.object({...Ts,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),Ii=p.object({...Ts,dispatch:p.literal("enveloped")}).strict(),Pi=p.object({...Ts,handler:Cs,pricing:ks}).strict(),Mi=p.union([p.discriminatedUnion("dispatch",[Ri,Ii]),Pi]);var As=/^[a-z0-9][a-z0-9_-]*$/;var Ui="https://fal.run",qu="https://openrouter.mpp.tempo.xyz";function Fu(e){let{attestation:t,tool_id:n,...r}=e;return r}var Oi={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function ur(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Oi[r]&&(i.image_size=Oi[r]),i)}function G(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Ui}/${r}`,merchantName:"fal.ai",buildBody:Fu,tags:[],...a}}function Bu(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function ae(e,t,n,r,s,o,i){let a=5e-4*s*100,l=500/1e6*o*100,c=Math.max(1,Math.ceil(a+l));return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:c,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${qu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Bu(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o},...i}}var Es=[G("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),G("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:ur}),G("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:ur}),G("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:ur}),G("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),G("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),G("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),G("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),G("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),G("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),G("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),G("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),G("fal-stable-audio","Stable Audio","Generate music and sound effects from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","music","sound-effects"]}),G("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","suno/v4","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{tags:["music","song","vocals","instrumental"],merchantName:"Suno AI",isAsync:!0,pollUrl:`${Ui}/suno/v4/requests/{requestId}/status`}),G("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),G("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),G("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),G("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),ae("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),ae("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),ae("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),ae("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),ae("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),ae("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),ae("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),ae("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),ae("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),ae("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),ae("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),ae("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),ae("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),ae("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),ae("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),ae("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",buildBody:e=>ur({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},G("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"]}),G("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"]}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:e=>{let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]},tags:["onchain","prices","allium","crypto","legacy"]}];function dr(e){return Es.find(t=>t.id===e)}var Di=1,Li=["pick_one","fan_out"],ji=["concat","dedupe_by_url","top_k_by_score"],Ku=8,Gu=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),zu=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),Wu=p.object({providers:p.array(p.string().min(1)).min(1).max(Ku),merge:p.enum(ji),maxResults:p.number().int().positive().optional()}),Vi=p.object({mode:p.enum(Li).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(p.string(),zu).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Wu.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),Gu),required:p.array(p.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Ju=p.object({version:p.literal(Di),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(As,"tool name must match MCP naming rules"),Vi).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Ms=require("child_process"),Gi=require("util"),zi=A(require("crypto")),ce=A(require("fs")),Wi=A(require("os")),De=A(require("path"));var pe=A(require("fs")),Is=A(require("path")),qi=A(require("os")),Rs=Is.join(qi.homedir(),".visa-mcp"),vn=Is.join(Rs,"mcp-server.log"),Xu=5*1024*1024,$s=null;function Qu(){pe.existsSync(Rs)||pe.mkdirSync(Rs,{recursive:!0,mode:448})}function ed(){if(!$s){if(Qu(),pe.existsSync(vn)&&pe.statSync(vn).size>Xu){let t=vn+".1";pe.existsSync(t)&&pe.unlinkSync(t),pe.renameSync(vn,t)}$s=pe.createWriteStream(vn,{flags:"a"})}return $s}function td(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function mr(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
37
+ `;td(e)&&process.stderr.write(s),ed().write(s)}var d={debug:(...e)=>mr("DEBUG",...e),info:(...e)=>mr("INFO",...e),warn:(...e)=>mr("WARN",...e),error:(...e)=>mr("ERROR",...e)};var Jt=(0,Gi.promisify)(Ms.execFile),gr=De.join(Wi.homedir(),".visa-mcp","bin"),Lt=De.join(gr,"Visa CLI"),nd=De.join(__dirname,"..","native"),Fi="5",Bi=De.join(gr,"visa-keychain.version"),Hi=De.join(gr,"visa-keychain.sha256");function Ki(e){let t=ce.readFileSync(e);return zi.createHash("sha256").update(t).digest("hex")}async function Ji(){try{if(ce.readFileSync(Bi,"utf-8").trim()===Fi&&ce.existsSync(Lt)){let r=ce.readFileSync(Hi,"utf-8").trim();if(Ki(Lt)!==r)d.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ce.unlinkSync(Lt);else return Lt}}catch{}let e=De.join(nd,"visa-keychain.m");if(ce.existsSync(e)||(e=De.resolve(__dirname,"..","..","native","visa-keychain.m")),ce.existsSync(e)||(e=De.resolve(__dirname,"..","native","visa-keychain.m")),!ce.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ce.mkdirSync(gr,{recursive:!0,mode:448});try{await Jt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Lt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ki(Lt);return ce.writeFileSync(Hi,t,{mode:384}),ce.writeFileSync(Bi,Fi,{mode:384}),Lt}async function Yi(e){let t=await Ji(),n;try{n=(await Jt(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Ps=null;function z(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ps!==null?Ps:(Ps=!0,!0)}var pr="visa-cli",fr="attestation-key";async function rd(e){try{await Jt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}await Jt("security",["add-generic-password","-s",pr,"-a",fr,"-w",e],{timeout:5e3})}async function sd(){try{let{stdout:e}=await Jt("security",["find-generic-password","-s",pr,"-a",fr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function hr(){let e=await Yi(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await rd(n),r}async function Yt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await sd();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Ji(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Ms.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function yr(){try{await Jt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}try{await Yi(["delete-key"])}catch{}}var od=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],id=[...od.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function Ns(e,t=id){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Os(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Os(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Os(s))))return r.targetToolId;return null}function Os(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Zi={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; check_fal_status_card resolves it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Call check_fal_status_card with those values to poll for completion. Do not poll more than once per 30 seconds.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original ~60\u201390s music track from a prompt (Suno V4 \u2014 vocals, lyrics, full arrangement). ~$0.10. Use for jingles, soundtracks, ad music, viral original songs, or any "make me a song about \u2026" / "compose music for \u2026" request.',tiers:{suno:{toolId:"suno-music",notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech (TTS, voice-cloned) or sound effects from a prompt. $0.03\u2013$0.04. Use for: voiceover (tts tier \u2014 pass text + audio_url of the voice sample), SFX/ambient/background sound (sfx tier \u2014 pass prompt describing the sound).",tiers:{tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"},sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:"For tts: provide text + audio_url (voice sample to clone). For sfx: provide prompt describing the sound.",inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for MetaVoice)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Us(e,t,n){if(!Qi(e))return ld(e,n);let r=Xi[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=ud(e,o,n);return i||dd(e,r,o,s)}function ld(e,t){return Ns({requestedTool:e,intentText:t})??e}function ud(e,t,n){return Ns({requestedTool:e,metaTool:e,tier:t,intentText:n})}function dd(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var Xi=Zi;function Qi(e){return e in Xi}var bn=Object.keys(Zi);function Ds(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function ea(e=process.env){return Ds(e)!==null}var se=A(require("crypto")),qa=require("child_process"),Ae=A(require("fs")),En=A(require("os")),Dr=A(require("path"));var L=A(require("fs")),Sr=A(require("os")),V=A(require("path")),sa=require("child_process");var ta=A(require("fs")),md=["npm","pnpm","yarn","bun"],pd=/\s+/;function fd(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(pd)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return md.includes(s)?s:void 0}function Ls(e){if(!e)return;let t=e;try{t=ta.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function gd(e=process.argv[1]){return fd()??Ls(process.env.npm_execpath)??Ls(process.env.npm_node_execpath)??Ls(e)}function js(e,t,n){let r=t??gd(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function Xt(e,t,n){return js(e,t,n).display}var hd=2,Sn="# >>> visa-cli shell hud v2 >>>",vr="# <<< visa-cli shell hud v2 <<<",oa="# >>> visa-cli shell hud >>>",yd="# <<< visa-cli shell hud <<<",ia=3e4,_d="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",vd={currentVersion:"0.0.0"},bd=3e4;function Fs(){try{return V.join(Gs(),".visa-cli")}catch{return V.join(Sr.tmpdir(),".visa-cli")}}function en(){return V.join(Fs(),"shell-hud.json")}function wr(){return V.join(Fs(),"shell-hud.line")}function aa(){return V.join(Fs(),"shell-hud.lock")}function nn(e){let t=e??process.env.SHELL;if(!t)return null;let n=V.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function xn(e){let t=Gs();if(e==="zsh")return V.join(t,".zshrc");if(e==="bash")return V.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return V.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Sd(e){let t=Gs(),n=[{shell:"zsh",rcPath:V.join(t,".zshrc")},{shell:"bash",rcPath:V.join(t,".bashrc")},{shell:"bash",rcPath:V.join(t,".bash_profile")},{shell:"powershell",rcPath:V.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function wd(e){let t="$HOME/.visa-cli/shell-hud.line",n=Pd(e),r=Md(e);if(e==="zsh")return`${Sn}
48
38
  _visa_cli_shell_hud_precmd() {
49
39
  setopt localoptions no_bg_nice
50
- if [[ -f "${e}" ]]; then
51
- print -r -- "$(cat "${e}")"
40
+ if [[ -f "${t}" ]]; then
41
+ print -r -- "$(cat "${t}")"
52
42
  fi
53
43
  if ${r}; then
54
44
  local _vhud_count=$(pgrep -f "visa-cli config shell-hud refresh" 2>/dev/null | wc -l | tr -d ' ')
@@ -61,13 +51,13 @@ autoload -Uz add-zsh-hook
61
51
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
62
52
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
63
53
  fi
64
- ${l_}`;if(t==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${cl}
54
+ ${vr}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Sn}
65
55
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
66
56
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
67
57
  }
68
58
  function global:prompt {
69
- if (Test-Path ${o}) {
70
- Write-Host (Get-Content ${o} -Raw)
59
+ if (Test-Path ${s}) {
60
+ Write-Host (Get-Content ${s} -Raw)
71
61
  }
72
62
  if (${r}) {
73
63
  # Reap any completed visa-hud jobs before starting a new one so the session
@@ -80,10 +70,10 @@ function global:prompt {
80
70
  }
81
71
  & $function:global:__visa_cli_original_prompt
82
72
  }
83
- ${l_}`}return`${cl}
73
+ ${vr}`}return`${Sn}
84
74
  __visa_cli_shell_hud_precmd() {
85
- if [ -f "${e}" ]; then
86
- cat "${e}"
75
+ if [ -f "${t}" ]; then
76
+ cat "${t}"
87
77
  fi
88
78
  if ${r}; then
89
79
  local _vhud_count
@@ -97,112 +87,86 @@ case ";$PROMPT_COMMAND;" in
97
87
  *";__visa_cli_shell_hud_precmd;"*) ;;
98
88
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
99
89
  esac
100
- ${l_}`}function tP(t){let e=t;for(let[n,r]of[[cl,l_],[ZI,Wee]])e=e.replace(new RegExp(`\\n?${XI(n)}[\\s\\S]*?${XI(r)}\\n?`,"g"),"");return e.trimEnd()}function ete(t,e){let n=tP(t).trimEnd(),r=Qee(e);return n.length>0?`${n}
90
+ ${vr}`}function ca(e){let t=e;for(let[n,r]of[[Sn,vr],[oa,yd]])t=t.replace(new RegExp(`\\n?${ra(n)}[\\s\\S]*?${ra(r)}\\n?`,"g"),"");return t.trimEnd()}function xd(e,t){let n=ca(e).trimEnd(),r=wd(t);return n.length>0?`${n}
101
91
 
102
92
  ${r}
103
93
  `:`${r}
104
- `}function f_(t=Qa()){if(!t)return!1;try{let e=ll(t),n=Ce.readFileSync(e,"utf-8");return n.includes(cl)||n.includes(ZI)}catch{return!1}}function m_(t=Qa()){if(!t)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let e;try{e=ll(t);let n=Ce.existsSync(e)?Ce.readFileSync(e,"utf-8"):"",r=ete(n,t),o=r!==n;return o&&d_(e,r),{installed:!0,changed:o,shell:t,rcPath:e,message:o?`Persistent shell HUD installed in ${e}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${e}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:t,rcPath:e,message:`Failed to install persistent shell HUD in ${e}: ${Bh(n)}`}}}function E_(t=Qa()){let e=[],n=[],r=[];try{for(let o of Zee(t))if(n.push(o.rcPath),!!Ce.existsSync(o.rcPath))try{let s=Ce.readFileSync(o.rcPath,"utf-8"),i=tP(s);if(i===s.trimEnd())continue;d_(o.rcPath,i.length>0?`${i}
105
- `:""),e.push(o.rcPath)}catch(s){r.push(`${o.rcPath}: ${Bh(s)}`)}return e.length>0?{removed:!0,shell:t,rcPath:e[0],rcPaths:e,message:r.length>0?`Removed persistent shell HUD from ${e.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${e.join(", ")}.`}:r.length>0?{removed:!1,shell:t,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:t,rcPath:n[0],rcPaths:n,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(o){return{removed:!1,shell:t,message:`Failed to remove persistent shell HUD: ${Bh(o)}`}}}function Hh(t,e){let n=e??Xee,r=n.currentVersion==="0.0.0"&&t.version?t.version:n.currentVersion,o=Za(r),s=` ${Tt("\u2502",_t.dim)} `,i=nP(n),a=rte(n,i),c=a||n.updateCheckDisabled?"":i,u=nte(o,c);if(!t.enrolled)return[u,Tt("setup needed",_t.visaGold),a].filter(Boolean).join(s);let l=ate(t),d=tte(t);return[u,Tt(l,_t.visaGold),d,a].filter(Boolean).join(s)}function tte(t){let e=typeof t.balanceCents=="number"?t.balanceCents:null,n=t.activeSession;if(e===null)return Tt("balance unknown",_t.dim);let r=e/100;if(n){let s=Math.max(0,n.capCents),i=Math.max(0,n.estimatedRemainingCents),a=Math.max(0,s-i),c=s>0?Math.max(0,Math.min(1,a/s)):0;return`${ite(c)} ${Tt(`${Xa(i/100)} in session`,_t.green)} ${Tt(`(${Xa(a/100)}/${Xa(s/100)} cap)`,_t.dim)} ${Tt("\xB7",_t.dim)} ${Tt(`${Xa(r)} balance`,_t.dim)}`}return e>=100?Tt(`${Xa(r)} balance`,_t.green):Tt(`${Xa(r)} balance \u2014 top up via buy_credits`,_t.visaGold)}function nte(t,e){let n=`${Tt("VISA CLI",_t.visaBlue)} ${Tt(`v${t}`,_t.visaBlueSoft)}`;return e?`${n} ${Tt("\u2B06 update",_t.visaGold)} ${Tt(`v${e}`,_t.visaGold)}`:n}function rte(t,e){if(e&&!t.updateCheckDisabled){let n=Za(za(e));return Tt(`run: ${n}`,_t.visaGold)}return e?null:ote(t)}function nP(t){return t.latestVersion?Za(t.latestVersion):""}function ote(t){let e=nP(t);return e?Tt(`update ready v${e}`,_t.visaGold):null}function rP(){let t=Fh();return!(!t||Date.now()-t.renderedAt>QI||t.cwd&&t.cwd!==process.cwd())}function S_(){let t=Fh();if(t&&Date.now()-t.renderedAt<=QI||(ste(),t?.line))return t.line;try{let e=__();if(Ce.existsSync(e))return Ce.readFileSync(e,"utf-8").trimEnd()}catch{}return zee}function $h(t,e){try{let n=we.dirname(Ja());Ce.mkdirSync(n,{recursive:!0});let r=Za(t),o={hudVersion:Kee,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:e};d_(Ja(),JSON.stringify(o)+`
106
- `),d_(__(),r+`
107
- `)}catch{}}function ul(){try{Ce.unlinkSync(eP())}catch{}}function Fh(){let t=Ja();if(!Ce.existsSync(t))return null;try{return JSON.parse(Ce.readFileSync(t,"utf-8"))}catch{return null}}function oP(){return Fh()?.status??null}function ste(){if(process.env.JEST_WORKER_ID)return;let t=eP();try{if(Ce.mkdirSync(we.dirname(t),{recursive:!0}),!dte(t))return;let e=process.argv[1]?we.resolve(process.argv[1]):"";if(!e){ul();return}let n=(0,JI.spawn)(process.execPath,[e,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",ul),n.unref()}catch{ul()}}function Za(t){return t.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function ite(t){let n=Math.round(Math.max(0,Math.min(1,t))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${Tt(r||"",_t.green)}${Tt(o||"",_t.dim)}`}function Xa(t){return`$${t.toFixed(2)}`}function ate(t){let e=t.cards?.find(a=>a.isDefault)??t.cards?.[0];if(!e)return"card none";let n=typeof e.brand=="string"?e.brand:"card",r=typeof e.last4=="string"?e.last4:"????",o=Za(n.toUpperCase()),s=Za(r);return`${e.isDefault?"default":"active"} ${o} ****${s}`}function cte(){let t=(process.env.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let e=(process.env.TERM??"").toLowerCase();return e.includes("truecolor")||e.includes("24bit")}var Vh=cte(),_t={reset:"\x1B[0m",visaBlue:Vh?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Vh?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Vh?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function Tt(t,e){return t.length===0||process.env.NO_COLOR?t:`${e}${t}${_t.reset}`}function XI(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jh(){let t=p_.homedir();if(!t||!we.isAbsolute(t))throw new Error("unable to determine a valid home directory");return we.resolve(t)}function ute(t){return t==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function lte(t){return t==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function dte(t){for(let e=0;e<2;e+=1){let n;try{return n=Ce.openSync(t,"wx"),Ce.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=Ce.statSync(t);if(Date.now()-o.mtimeMs<=Jee)return!1;Ce.unlinkSync(t)}catch{}}finally{n!==void 0&&Ce.closeSync(n)}}return!1}function Bh(t){return t instanceof Error?t.message:"unknown file system error"}function d_(t,e){Ce.mkdirSync(we.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;Ce.writeFileSync(n,e),Ce.renameSync(n,t)}async function ec(t,e){try{return await e()}catch(n){if(n.message==="Invalid signature"&&it()){T.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await a_();await t.registerAttestationKey(r),T.info("attestation:key-reregistered")}catch(r){throw T.error("attestation:reregister-failure",{error:r.message}),n}return await e()}throw n}}var sP="2.0.0-rc.41";function qh(t,e){return e?{kind:"env",var:t}:{kind:"default"}}function g_(t,e,n){let r=process.env[t];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:t}};let o=Yp(e);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Pn(t){return t==null?"\u2014":t?"yes":"no"}function h_(t){return t==null?"\u2014":`$${t.toFixed(2)}`}function pte(t){return t==null?"\u2014":`$${(t/100).toFixed(2)}`}function _te(){let t=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(t!==void 0){let n=Number(t);if(Number.isFinite(n)&&n>=100&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let e=Sh("credit.sessionCapCents");return e!==void 0&&e>=100&&e<=1e4?{value:Math.floor(e),source:{kind:"settings"}}:{value:mh,source:{kind:"default"}}}async function T_(t){let e=null,n=null;try{e=await t.api.getStatus()}catch(I){n=I?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Eh("auth.serverUrl"),i=Hn(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:e?.enrolled??null,formatted:Pn(e?.enrolled),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),e?.githubUser&&r.push({key:"account.githubUser",value:e.githubUser,formatted:e.githubUser,source:{kind:"server"}});let c=e?e.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:Pn(c),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:e?.hasAttestationKey??null,formatted:Pn(e?.hasAttestationKey),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:it(),formatted:Pn(it()),source:{kind:"device"}});let u=e?.spendingControls,l=u?u.max_transaction_amount??u.maxTransactionAmount??null:null,d=u?u.daily_limit??u.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:l,formatted:h_(l),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:h_(d),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:e?.dailySpent??null,formatted:h_(e?.dailySpent),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:e?.dailyRemaining??null,formatted:h_(e?.dailyRemaining),source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:e?.cardCount??null,formatted:e?.cardCount!=null?String(e.cardCount):"\u2014",source:e?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let p=e?.cards?.find(I=>I.isDefault)??e?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let _=_te();r.push({key:"credit.sessionCapCents",value:_.value,formatted:pte(_.value),source:_.source});let f=iI();f.length>0&&r.push({key:"settings.retired",value:f.map(I=>I.key),formatted:f.map(I=>I.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${f.map(I=>`visa-cli config unset ${I.key}`).join(" && ")}`});let E=g_("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:E.value,formatted:Pn(E.value),source:E.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let S=g_("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:S.value,formatted:Pn(S.value),source:S.source});let h=Vr(),R;process.env.VISA_CLI_NO_UPDATE_CHECK?R={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?R={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?R={kind:"env",var:"NODE_ENV"}:R={kind:"default"},r.push({key:"ui.updateCheck",value:!h,formatted:Pn(!h),source:R});let A=g_("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:A.value,formatted:Pn(A.value),source:A.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let O=g_("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:O.value,formatted:Pn(O.value),source:O.source});let y=process.env.VISA_DRY_RUN,M=WI();if(r.push({key:"tools.dryRun",value:M,formatted:Pn(M),source:y===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:sP,formatted:sP,source:{kind:"default"}}),t.includeDev){let I=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:I==="true",formatted:Pn(I==="true"),source:qh("VISA_MOCK_KEYCHAIN",!!I)});let J=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:J==="true",formatted:Pn(J==="true"),source:qh("VISA_MOCK_TOUCHID",!!J)});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:Pn(!!H),source:qh("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function fte(t){switch(t.kind){case"default":return"default";case"env":return`env ${t.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${t.reason})`}}function iP(t,e={}){if(t.length===0)return"";let n=Math.max(...t.map(s=>s.key.length)),r=Math.max(...t.map(s=>s.formatted.length)),o=[];for(let s of t){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${fte(s.source)})`),e.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
108
- `)}function aP(t){return JSON.stringify({config:t.entries.map(e=>({key:e.key,value:e.value,source:e.source,hint:e.hint})),statusError:t.statusError},null,2)}function cP(t){if(t<=0)return null;let e=(t/100).toFixed(2);return{_credits_prompt:{message:`You've got $${e} in free credits \u2014 enough for about ${Math.floor(t/6)} images. Try something now, or save them for later.`,balanceUsd:e,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.10",what:"an AI song"}]}}}var Ss=require("fs"),lP=require("os"),Yh=require("path"),mte=(0,Yh.join)((0,lP.homedir)(),".visa-mcp"),uP=(0,Yh.join)(mte,"mcp-session-budget.json");function A_(){try{(0,Ss.existsSync)(uP)&&(0,Ss.unlinkSync)(uP)}catch{}}var Kh=require("crypto"),y_=null,dl=0,pl=0,gs=0,Wh=null,zh=null,R_=Promise.resolve();function Po(t){y_=t,dl=0,pl=0,gs=0,Wh=null,zh=null,R_=Promise.resolve()}function _l(t){gs=Math.max(0,Math.floor(t))}function Xh(){return y_}function Jh(t){if(!y_)return null;let e=dl+pl;return gs>0&&e>gs&&(e=gs),{session_budget_id:y_,cumulative_micros:e*1e4,nonce:(0,Kh.randomUUID)(),idempotency_key:t||(0,Kh.randomUUID)()}}function Zh(t){if(!t)return null;let e;try{e=Buffer.from(t,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return typeof r.cumulative=="number"&&Number.isFinite(r.cumulative)&&(dl=r.cumulative,pl=0),Wh=r,r}function dP(){return Wh}function pP(t){let e=t.receipt??null;zh={toolName:t.toolName,resolvedToolId:t.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(t.estimatedAmountCents)),voucherCumulativeCents:Math.floor(t.voucher.cumulative_micros/1e4),estimatedCumulativeCents:O_(),receiptDeltaCents:typeof e?.delta=="number"?e.delta:null,receiptCumulativeCents:typeof e?.cumulative=="number"?e.cumulative:null,receiptRemainingCents:typeof e?.remaining=="number"?e.remaining:null,receiptDeltaMicros:typeof e?.delta_micros=="string"?e.delta_micros:null,receiptCumulativeMicros:typeof e?.cumulative_micros=="string"?e.cumulative_micros:null,receiptRemainingMicros:typeof e?.remaining_micros=="string"?e.remaining_micros:null,recordedAt:new Date().toISOString()}}function _P(){return zh}function fP(){return dl}function O_(){let t=dl+pl;return gs>0&&t>gs&&(t=gs),t}function mP(t){if(!Number.isFinite(t)||t<=0)return Promise.resolve();let e=Math.ceil(t);return R_=R_.then(()=>{pl+=e}),R_}var EP=100,Je=null,SP=Promise.resolve();function Qh(t){let e=SP.catch(()=>{}).then(t);return SP=e.then(()=>{},()=>{}),e}var nn=class extends Error{balanceCents;minRequiredCents;constructor(e,n){super(`Prepaid balance is $${(e/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first (or enable auto-topup with update_spending_controls).`),this.name="InsufficientBalanceError"}};async function eT(t,e,n){return Qh(()=>gP(t,e,n))}async function gP(t,e,n){if(A_(),Je&&new Date(Je.expiresAt).getTime()>Date.now())return Xh()!==Je.budgetId&&(Po(Je.budgetId),_l(Je.totalCents)),T.info("mcp-session:active-hit",{budgetId:Je.budgetId,tool:n.toolName,remainingEstimatedCents:Je.totalCents-O_()}),{budgetId:Je.budgetId,isFresh:!1,totalCents:Je.totalCents,requestedCapCents:Je.totalCents,appliedCapCents:Je.totalCents,clampedReason:null};Je&&(Je=null,Po(null));let r=await t.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<EP)throw new nn(r.balanceCents,EP);let o=n.capCentsOverride??zp(),s=Math.min(o,r.balanceCents),i=s<o?"balance":null,a=await e("session_create",s,"Visa CLI Session",`open credit-model session with $${(s/100).toFixed(2)} cap`,n.userContext),c=await t.createSessionBudget({total_cents:s,...a?{attestation:a}:{}});if(!c.success||!c.budget){let l=c.error||"unknown error";throw new Error(`Failed to open credit session: ${l}`)}let u={budgetId:c.budget.id,expiresAt:c.budget.expiresAt,totalCents:c.budget.totalCents,createdAt:c.budget.createdAt};return Je=u,Po(u.budgetId),_l(u.totalCents),T.info("mcp-session:opened",{budgetId:u.budgetId,capCents:u.totalCents,requestedCapCents:o,clampedReason:i,expiresAt:u.expiresAt,tool:n.toolName}),{budgetId:u.budgetId,isFresh:!0,totalCents:u.totalCents,requestedCapCents:o,appliedCapCents:u.totalCents,clampedReason:i}}async function hP(t,e,n){return Qh(async()=>{let o=hs()?await TP(t):null,s=await gP(t,e,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function TP(t){let n=hs()?.budgetId??Xh(),r=!1;if(n)try{r=!!(await t.closeSession(n))?.success}catch(o){T.warn("mcp-session:close-server-failed",{budgetId:n,error:o?.message||String(o)})}return A_(),Je=null,Po(null),{closedServerSide:r,budgetId:n}}async function tT(t){return Qh(()=>TP(t))}function hs(){return A_(),Je?new Date(Je.expiresAt).getTime()<=Date.now()?(Je=null,Po(null),null):{budgetId:Je.budgetId,totalCents:Je.totalCents,lastReceiptCumulative:fP(),lastReceiptCumulativeMicros:dP()?.cumulative_micros??null,estimatedCumulative:O_(),lastToolSpend:_P(),expiresAt:Je.expiresAt}:null}var yP=v(nT()),RP=10000n;function xte(t){return t<=0n?0:Number((t+RP-1n)/RP)}function OP(t){return xte((0,yP.fromUsd)(t))}var NP=Promise.resolve();function P_(t){let e=NP.catch(()=>{}).then(t);return NP=e.then(()=>{},()=>{}),e}async function UP(t){let e=await eT(ae,Er,{toolName:t.toolId,userContext:t.userContext}),n=Jh(t.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${e.budgetId}`);let r=await Gte(),{data:o,voucherReceiptHeader:s}=await ae.shortcutWithSession(t.toolId,n,t.toolParams,t.timeoutMs,t.userContext,t.metaTool),i=Zh(s);if(await mP(t.estimatedAmountCents),pP({toolName:t.metaTool??t.toolId,resolvedToolId:t.toolId,estimatedAmountCents:t.estimatedAmountCents,voucher:n,receipt:i}),kP(o))return o;let a=await wP();if(t.idempotencyKey&&VP(o,a,t.idempotencyKey))return o;let c=a?C_(a):null;return BP(o,r,c)}function Fr(t){return{success:!1,error:t.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:t.balanceCents,suggestedTool:"buy_credits"}}function sT(t){if(t===null||typeof t!="object"){let n=JSON.stringify(t);return n===void 0?String(t):n}return Array.isArray(t)?`[${t.map(sT).join(",")}]`:`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${sT(r)}`).join(",")}}`}function Dte(t,e,n,r){let o=xt.createHash("sha256").update(`${n}:${sT(r)}`).digest("hex").slice(0,24);return`batch:${t}:${e}:${o}`}function Ute(t,e){return`${t}:${e}`}function wte(t){if(t==null)return;let e=String(t);if(e.length!==0)return e.startsWith("ledger_")?e:/^\d+$/.test(e)?`ledger_${e}`:e}function CP(t,e,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Ts(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=wte(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:t,item_id:Ute(t,e),index:e,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function kte(t){let n=await ae.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<100)throw new nn(n.balanceCents,100);let r=zp(),o=Math.min(r,n.balanceCents),s=C_(n),i=`spend up to $${(t.estimatedAmountCents/100).toFixed(2)} on ${t.toolId} (session cap $${(o/100).toFixed(2)})`,a=await Er("session_create",o,"Visa CLI Session",i,t.userContext),c=await ae.createSessionBudget({total_cents:o,...a?{attestation:a}:{}});if(!c.success||!c.budget)throw new Error(`Failed to open on-demand session: ${c.error||"unknown error"}`);let u=c.budget.id;Po(u),_l(c.budget.totalCents),T.info("on-demand-session:opened",{budgetId:u,capCents:c.budget.totalCents,tool:t.toolId});try{let l=Jh(t.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${u}`);let{data:d,voucherReceiptHeader:p}=await ae.shortcutWithSession(t.toolId,l,t.toolParams,t.timeoutMs,t.userContext,t.metaTool);if(Zh(p),kP(d))return d;let _=await wP();if(t.idempotencyKey&&VP(d,_,t.idempotencyKey))return d;let f=_?C_(_):null;return BP(d,s,f)}finally{try{await ae.closeSession(u)}catch(l){T.warn("on-demand-session:close-failed",{budgetId:u,error:l?.message||String(l)})}Po(null),T.info("on-demand-session:closed",{budgetId:u,tool:t.toolId})}}async function Rs(t){return P_(async()=>hs()?UP(t):kte(t))}function b_(){return Hn()}var ae=new $n(()=>Ae.getSessionToken());function Ts(t){if(typeof t!="string"||!/^-?\d+$/.test(t))return null;try{return BigInt(t)}catch{return null}}function C_(t){return Ts(t.balanceMicros)??BigInt(t.balanceCents)*10000n}function Vte(t){if(t<0n&&(t=0n),t>=1000000n){let r=(t+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let e=t%1000000n;return e===0n?"$0.00":`$0.${e.toString().padStart(6,"0").replace(/0+$/,"")}`}function Bte(t){let e=Ts(t.lastReceiptCumulativeMicros);if(e!==null)return{micros:e,source:"lastReceiptCumulativeMicros"};let n=Ts(t.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,t.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function rT(t,e="INVALID_TOOL_PARAMS"){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Gte(){try{let t=await ae.getBalance();return t.success?C_(t):null}catch{return null}}async function wP(){try{let t=await ae.getBalance();return t.success?t:null}catch{return null}}function kP(t){if(!t||t.success===!1)return!1;let e=Ts(t.receipt_v2?.charged_micros??t.receipt_v2?.actual_micros),n=Ts(t.amountMicros??t.amount_micros??t.charged_micros),r=e??n;if(r===null||r<=0n)return!1;let o=r.toString();return t.amountMicros??=o,t.amount_micros??=o,t.charged_micros??=o,(typeof t.amount!="number"||t.amount<=0)&&(t.amount=Number(r)/1e6),!0}function VP(t,e,n){if(!t||t.success===!1||!e||!Array.isArray(e.ledger))return!1;let r=e.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=Ts(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return t.amountMicros??=i,t.amount_micros??=i,t.charged_micros??=i,(typeof t.amount!="number"||t.amount<=0)&&(t.amount=Number(s)/1e6),!0}function BP(t,e,n){if(!t||t.success===!1||e===null||n===null)return t;let r=e-n;if(r<=0n)return t;let o=r.toString();return t.amountMicros??=o,t.amount_micros??=o,(typeof t.amount!="number"||t.amount<=0)&&(t.amount=Number(r)/1e6),t}var Hte="2.0.0-rc.41",wqe=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
109
- `);function Yn(t){if(!t||typeof t!="string"||aI())return;let e;try{e=new URL(t)}catch{return}if(e.protocol!=="https:"&&e.protocol!=="http:")return;let n=e.toString(),r=th();if(r.headless){T.info(`Browser auto-open skipped (${r.reason}). URL: ${n}`);return}let o=nh(n);if(!o){T.info(`No browser command for platform "${ml.platform()}". URL: ${n}`);return}(0,DP.execFile)(o.cmd,o.args,s=>{s&&T.warn(`Browser open failed: ${s.message}. URL: ${n}`)})}async function gn(t){return ec(ae,t)}var GP="get_cards",HP="set_default_card";function $te(t,e=60){return`The processor returned a transient decline (code ${t??"unknown"}). This is not a permanent failure \u2014 it usually clears within ~${e} seconds and is most often triggered by rapid successive charges on the same card. Tell the user the call was temporarily declined and that you will retry shortly, then wait at least ${e} seconds before retrying the SAME call exactly once. Do not retry more than once. Do not assume the user has run out of funds. IMPORTANT: If the retry also fails, do NOT retry again \u2014 instead tell the user their default card may be temporarily locked by the processor and suggest switching to a different card. They can run '${GP}' to see enrolled cards and '${HP}' to switch, then retry the original request.`}function Fte(t,e){return`The processor returned a non-retryable decline (code ${t??"unknown"}). Stop the current task and tell the user their card was declined for ${e||"the merchant"}. Suggest they check their card status or available balance. If they want to try a different default card, they can run '${GP}' to see enrolled cards and '${HP}' to switch. Do not retry automatically.`}function mr(t,e){let n=t.retryable?$te(t.code,t.retryAfter):Fte(t.code,e.merchantName);return{success:!1,declined:!0,retryable:t.retryable,code:t.code,reason:t.reason,payment_error_class:t.paymentErrorClass,correlation_id:t.correlationId,transactionId:t.transactionId,retryAfter:t.retryAfter,merchantName:e.merchantName,amount:e.amount,message:t.message,agent_guidance:n}}var tc=null,jte=3e4;function $P(){tc=null}var As=class extends Error{constructor(n){super(`${v_()} attestation is required for this action, but it is not available in this MCP process. `+iT());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function El(t,e){return{success:!1,error:t.code,message:t.message,action:e,agent_guidance:`Biometric attestation is required for ${e}, but this MCP process cannot create a local attestation. `+iT()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function v_(){return process.platform==="darwin"?"Touch ID":"local biometric"}function iT(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function M_(t){return typeof t.hasAnyAttestationKey=="boolean"?t.hasAnyAttestationKey:typeof t.hasAttestationKey=="boolean"?t.hasAttestationKey:!0}async function qte(t){let e=Date.now();if(tc&&tc.expiresAt>e)return{required:tc.required,hasRegisteredKey:tc.hasRegisteredKey};try{let n=await ae.getStatus(t),r=n.attestationRequired!==!1,o=M_(n);return tc={required:r,hasRegisteredKey:o,expiresAt:e+jte},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Er(t,e,n,r,o){let s=await qte(o);if(!s.required){T.info("attestation:skipped-by-server-policy",{context:t});return}if(!s.hasRegisteredKey){T.info("attestation:skipped-no-registered-key",{context:t});return}if(!it())throw T.warn("attestation:unavailable",{context:t}),new As(t);T.info("attestation:attempt",{context:t,amount:e,merchant:n});try{let{nonce:i}=await ae.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:e,merchant:n,context:t})).toString("base64");T.info("touchid:prompt",{context:t,amount:e,merchant:n});let c=await Ka(a,r);return T.info("attestation:success",{context:t,amount:e,merchant:n}),{signature:c,nonce:i,amount:e,merchant:n}}catch(i){throw T.error("attestation:failure",{context:t,amount:e,merchant:n,error:i.message}),i}}var vP="[dry-run] https://placeholder.visa-cli.dev/image.png",Yte=new Set(["generate_image_card","generate_image_fast_card","generate_image_schnell_card","generate_image_recraft_card","generate_image_ideogram_card","edit_image_seed_card","fal-flux-pro-ultra","fal-flux-pro","fal-flux-dev","fal-flux-schnell","fal-ideogram-v2","fal-ideogram-v2-turbo","fal-recraft-v3","fal-fast-sdxl"]),Kte=new Set(["generate_video_tempo_card","generate_video_kling_card","generate_video_wan_card","generate_video_minimax_card","fal-kling-video","fal-wan-video","fal-kling-i2v","fal-minimax-video"]);function Wte(t,e){return e==="run_llm"||t.startsWith("or-")?"llm":e==="generate_image"||Yte.has(t)?"image":e==="generate_video"||Kte.has(t)?"video":null}function zte(t){return(typeof t.prompt=="string"?t.prompt:"").slice(0,100)}function Xte(t){return t==="llm"?"OpenRouter":"fal.ai"}function nc(t,e,n,r){let o={success:!0,transactionId:`dry-run:${r??e}`,amount:0,rail:"dry_run",merchantName:Xte(t),dry_run:!0,metadata:{dry_run:!0}};if(t==="llm"){let i=`[dry-run] echo: ${zte(n)}`;return{...o,content:i,data:{content:i,model:e,dry_run:!0}}}return{...o,urls:[vP],data:{[t==="video"?"videoUrl":"imageUrl"]:vP,metadata:{dry_run:!0}}}}async function oT(t){let e=t.mode??"mock",n=e==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=e==="preflight"?"preflight":null;try{await ae.emitTelemetry([{id:xt.randomUUID(),timestamp:new Date().toISOString(),tool_name:t.toolName,user_prompt:t.userContext??"",tool_params:JSON.stringify(t.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(t.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:t.result.merchantName,transaction_id:t.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-t.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:t.resolvedModel,session_budget_id:null}])}catch(o){T.warn("dry_run:telemetry_failed",{tool:t.toolName,error:o?.message||String(o),mode:e})}}var Jte="https://openrouter.ai/api/v1/chat/completions",Zte="openrouter/free",Qte=50,ene=15e3;function tne(t){let e=[t.prompt,t.user_prompt,t.input,t.text];for(let n of e)if(typeof n=="string"&&n.trim().length>0)return n;return"preflight"}async function nne(t,e,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return T.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:t}),{result:nc("llm",t,e,n),degraded:!0,resolvedModel:null};let o=tne(e),s;try{s=await Ii(Jte,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","HTTP-Referer":"https://visacli.sh/preflight","X-Title":"Visa CLI Preflight"},body:JSON.stringify({model:Zte,messages:[{role:"user",content:o}],max_tokens:Qte}),timeoutMs:ene})}catch(l){return T.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:t,error:l?.message||String(l)}),{result:nc("llm",t,e,n),degraded:!0,resolvedModel:null}}if(!s.ok){let l=await s.text().catch(()=>"");return T.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:t,status:s.status,bodyExcerpt:l.slice(0,200)}),{result:nc("llm",t,e,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(l){return T.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:t,error:l?.message||String(l)}),{result:nc("llm",t,e,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??t}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??t,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function L_(t,e,n,r){let o=Uh();if(!o)return null;let s=Wte(t,r);if(!s)return null;let i=Date.now();if(o==="mock"){let u=nc(s,t,e,r);return await oT({toolName:r??t,resolvedModel:r&&r!==t?t:null,toolParams:e,result:u,userContext:n,startedAt:i,mode:"mock"}),T.info("dry_run:payment_intercepted",{tool:t,metaTool:r,kind:s,mode:o}),u}if(s!=="llm"){T.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:t,kind:s});let u=nc(s,t,e,r);return await oT({toolName:r??t,resolvedModel:r&&r!==t?t:null,toolParams:e,result:u,userContext:n,startedAt:i,mode:"preflight"}),u}let{result:a,resolvedModel:c}=await nne(t,e,r);return await oT({toolName:r??t,resolvedModel:c??(r&&r!==t?t:null),toolParams:e,result:a,userContext:n,startedAt:i,mode:"preflight"}),T.info("dry_run:payment_intercepted",{tool:t,metaTool:r,kind:s,mode:o}),a}async function Mo(t,e,n){let r=await ae.paymentPreview({tool:t,url:e},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function ys(t){return OP(t.amount)}function rne(t){if(t.pricingMode==="max-cap"){let e=typeof t.estimatedAmount=="number"&&t.estimatedAmount>0?` (estimated $${t.estimatedAmount.toFixed(2)})`:"";return`pay up to $${t.amount.toFixed(2)} to ${t.merchantName}${e}`}return`pay $${t.amount.toFixed(2)} to ${t.merchantName}`}function one(){return I_.join(ml.homedir(),".visa-mcp","allium-results")}var kqe=16*1024,Vqe=50*1024*1024;function sne(){let t=one();try{if(!fr.existsSync(t))return{file_count:0,size_bytes:0,path:t};let e=fr.readdirSync(t),n=0,r=0;for(let o of e)try{let s=fr.statSync(I_.join(t,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:t}}catch(e){return T.warn("allium:disk_usage_error",{error:e.message}),{file_count:0,size_bytes:0,path:t}}}async function Sl(t){if(!cI())try{let e=await Ae.getSessionToken();if(!e)return;await fetch(`${b_()}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({prompt:t.prompt,tool:t.tool,media_url:t.mediaUrl,media_type:t.mediaType,cost:t.cost,transaction_id:t.transactionId,auto:!0,...t.userContext&&{user_context:t.userContext}}),signal:AbortSignal.timeout(5e3)}),T.info("feed:submitted",{tool:t.tool,mediaType:t.mediaType})}catch{}}async function ine(t,e){if(!t.url||!t.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let n=await Mo(void 0,t.url,e);T.info("payment:attempt",{tool:"pay",amount:n.amount,merchant:n.merchantName,url:t.url});try{return await gn(async()=>{let r=await Er(t.url||"pay",n.amount,n.merchantName,rne(n)),o=await ae.pay({url:t.url||"",merchantName:t.merchantName||"Unknown",description:t.description||"",method:t.method,body:t.body,attestation:r,idempotencyKey:xt.randomUUID()},e);return o.success?(T.info("payment:success",{tool:"pay",amount:n.amount,merchant:n.merchantName,rail:o.receipt?.rail}),o.receipt&&Yne(o.receipt)):T.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,message:o.message}),o})}catch(r){if(r instanceof Mt)return T.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,code:r.code,retryable:r.retryable}),mr(r,n);throw T.error("payment:failure",{tool:"pay",amount:n.amount,merchant:n.merchantName,error:r.message}),r}}async function ane(t,e){let n=(t.state||"").trim().toUpperCase(),r=(t.county||"").trim(),o=(t.start_date||"").trim(),s=(t.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;T.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await gn(async()=>{let u=await Er("get_visa_smi",a,i,c),l=await ae.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:u,idempotencyKey:xt.randomUUID()},e);return l.success?T.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:l.charged_cents}):T.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:l.error}),l})}catch(u){if(u instanceof Mt)return T.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:u.code,retryable:u.retryable}),mr(u,{amount:a,merchantName:i,description:"Visa SMI data"});throw T.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:u.message}),u}}async function cne(t,e){if(!t.prompt||!t.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await L_("generate_image_card",t,e);if(n)return n;let r=await Mo("generate_image_card",void 0,e),o=xt.randomUUID();T.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await gn(async()=>{let s;try{s=await Rs({toolId:"generate_image_card",toolParams:t,estimatedAmountCents:ys(r),userContext:e,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof nn)return Fr(i);throw i}return T.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Yn(i)),Sl({prompt:t.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:e})):T.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof Mt)return T.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),mr(s,r);throw T.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function une(t,e){if(!t.prompt||!t.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await L_("generate_image_fast_card",t,e);if(n)return n;let r=await Mo("generate_image_fast_card",void 0,e),o=xt.randomUUID();T.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await gn(async()=>{let s;try{s=await Rs({toolId:"generate_image_fast_card",toolParams:t,estimatedAmountCents:ys(r),userContext:e,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof nn)return Fr(i);throw i}return T.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Yn(i)),Sl({prompt:t.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:e})):T.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof Mt)return T.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),mr(s,r);throw T.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function lne(t,e){if(!t.prompt||!t.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await L_("generate_video_tempo_card",t,e);if(n)return n;let r=await Mo("generate_video_tempo_card",void 0,e),o=xt.randomUUID();T.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await gn(async()=>{let s;try{s=await Rs({toolId:"generate_video_tempo_card",toolParams:t,estimatedAmountCents:ys(r),userContext:e,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof nn)return Fr(i);throw i}return T.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Yn(i)),Sl({prompt:t.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:e})):T.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof Mt)return T.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),mr(s,r);throw T.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function dne(t,e){if(!t.prompt||!t.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await Mo("generate_music_tempo_card",void 0,e),r=xt.randomUUID();T.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await gn(async()=>{let o;try{o=await Rs({toolId:"generate_music_tempo_card",toolParams:t,estimatedAmountCents:ys(n),userContext:e,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof nn)return Fr(s);throw s}return T.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Yn(s)),Sl({prompt:t.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:e})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,T.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):T.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof Mt)return T.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),mr(o,n);throw T.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function pne(t,e){let n=await Mo("check_music_status_tempo_card",void 0,e),r=xt.randomUUID();T.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await gn(async()=>{let o;try{o=await Rs({toolId:"check_music_status_tempo_card",toolParams:t,estimatedAmountCents:ys(n),userContext:e,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof nn)return Fr(s);throw s}return T.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Yn(s)),o})}catch(o){if(o instanceof Mt)return T.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),mr(o,n);throw T.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function _ne(t,e){if(!t.chain||!t.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!t.token_address||!t.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let n=await Mo("query_onchain_prices_card",void 0,e),r=xt.randomUUID();T.info("payment:attempt",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName});try{return await gn(async()=>{let o;try{o=await Rs({toolId:"query_onchain_prices_card",toolParams:t,estimatedAmountCents:ys(n),userContext:e,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof nn)return Fr(s);throw s}if(T.info("payment:success",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof Mt)return T.warn("payment:declined",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),mr(o,n);throw T.error("payment:failure",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var fne=["generate_music_tempo_card"],IP=50,PP=5,bP=new Map;function MP(t){let e=bP.get(t);if(e!==void 0)return e;let r=n_(t)?.isAsync===!0||fne.includes(t);return bP.set(t,r),r}var mne=36e4,Ene=18e4,Sne=15e3,gne=12e4,hne=2e3;async function Tne(t,e){let n;if(t.requests?.some(A=>A.tool||A.tool_id)&&t.requests)n=t.requests.map(A=>{let O=A.tool||A.tool_id||t.tool;if(!O)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let y=Dh(O,A.tier||t.tier,A.prompt??e),{tool:M,tool_id:I,tier:J,params:H,...me}=A,G=H&&typeof H=="object"?{...H,...me}:me;return{resolvedTool:y,params:G}});else if(t.tool){let A=Dh(t.tool,t.tier,t.params?.prompt??e);n=(t.requests||(t.count&&t.params?Array.from({length:t.count},()=>({...t.params})):[])).map(y=>({resolvedTool:A,params:y}))}else throw new Error("Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)throw new Error("Batch requires at least one item.");if(n.length>IP)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${IP} items. Please split into smaller batches.`};if([...new Set(n.map(A=>A.resolvedTool))].some(MP)&&n.length>PP)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${PP} items. Please use multiple batches for more.`};let i=[...new Set(n.map(A=>A.resolvedTool))],a=i.length===1,c={};for(let A of i)c[A]=await Mo(A,void 0,e);let u=0;for(let A of n)u+=c[A.resolvedTool].amount;let l=[...new Set(Object.values(c).map(A=>A.merchantName))].join(", "),d=a?i[0]:"mixed";T.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:u,merchant:l,heterogeneous:!a});let p=n.some(A=>MP(A.resolvedTool)),_=n.some(A=>A.resolvedTool.startsWith("or-")||A.resolvedTool==="run_llm"||A.resolvedTool==="execute_tool"),f=p?mne:_?Ene+n.length*Sne:gne+n.length*hne,E=xt.randomUUID(),S=[],h=0,R=0n;return P_(async()=>{let A=!hs();if(A)try{await eT(ae,Er,{toolName:"batch",userContext:e})}catch(O){return O instanceof nn?Fr(O):(T.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:O?.message||String(O)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:O?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let H=0;H<n.length;H+=1){let me=n[H],G=c[me.resolvedTool];try{let j=await UP({toolId:me.resolvedTool,toolParams:me.params,estimatedAmountCents:ys(G),userContext:e,metaTool:"batch",timeoutMs:f,idempotencyKey:Dte(E,H,me.resolvedTool,me.params)});if(S.push({success:j?.success!==!1,tool:me.resolvedTool,...j,...CP(E,H,j)}),j?.success!==!1){let Ne=Ts(j?.amountMicros??j?.amount_micros),pe=typeof j?.amount=="number"?j.amount:G.amount;Ne!==null&&Ne>0n?R+=Ne:R+=BigInt(Math.round(pe*1e6)),h+=pe}j?.urls&&j.urls.forEach(Ne=>Yn(Ne))}catch(j){if(j instanceof nn&&S.length===0)return Fr(j);T.warn("payment:batch-item-failed",{tool:me.resolvedTool,index:H,error:j?.message||String(j)}),S.push({success:!1,tool:me.resolvedTool,...CP(E,H),error:j?.message||String(j)})}}let O=S.filter(H=>H?.success===!1).length,y=S.length-O,M=S.flatMap(H=>Array.isArray(H?.urls)?H.urls:[]),I=R>0n?Number(R)/1e6:Math.round((h+Number.EPSILON)*100)/100,J=y===0?"failure":O===0?"success":"partial";return T.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:u,totalCharged:I,merchant:l,successCount:y,failedCount:O,outcome:J,mode:"session",batchId:E}),{success:y>0,outcome:J,batch_id:E,tool:a?i[0]:d,count:n.length,successCount:y,failedCount:O,totalCharged:I,...R>0n?{totalChargedMicros:R.toString(),amountMicros:R.toString(),amount_micros:R.toString()}:{},merchantName:l,results:S,...M.length?{urls:M}:{}}}catch(O){if(O instanceof Mt)return T.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:u,merchant:l,code:O.code,retryable:O.retryable}),mr(O,{amount:u,merchantName:l});throw T.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:u,merchant:l,error:O.message}),O}finally{if(A){let O=await tT(ae);T.info("batch-session:closed",{budgetId:O.budgetId,closedServerSide:O.closedServerSide})}}})}function Ane(){let t=!1,e;try{let r=I_.join(ml.homedir(),".claude","settings.json");if(fr.existsSync(r)){let o=JSON.parse(fr.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";t=Ci(s)}}catch{}let n=f_();return n||(e="visa-cli config shell-hud install"),{statusLine:t,shellHud:n,...e?{shellHudSetup:e}:{}}}async function Rne(t){let[e,n]=await Promise.all([ae.getStatus(t),ae.getBalance().catch(s=>(T.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof e?.dailyRemaining=="number"&&(e.dailyRemaining=Math.round(e.dailyRemaining*100)/100);let r=sne();r.file_count>0&&(e.alliumResultsOnDisk=r),e.hud=Ane(),e.version=Hte,Array.isArray(e.cards)&&(e.cards=e.cards.map(s=>({...s,displayName:aT(s)})),e.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(e.balanceCents=n.balanceCents,e.amountUsd=n.amountUsd);let o=hs();if(e.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);e.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return e}function aT(t){let e=typeof t.brand=="string"&&t.brand.trim().length>0?t.brand.trim():"card",n=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),r=typeof t.last4=="string"&&t.last4.trim().length>0?t.last4.trim():"unknown",o=t.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function FP(t,e){try{let r=((await ae.getStatus(e)).cards||[]).find(o=>o?.id===t);if(r)return aT(r)}catch(n){T.warn("cards:display_name_lookup_failed",{cardId:t,error:n?.message||String(n)})}return"selected card"}async function yne(t){let n=(await ae.getStatus(t)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(o=>({...o,displayName:aT(o)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function One(t,e){let n=await ae.getTransactions({limit:t.limit,offset:t.offset},e);return Array.isArray(n?.transactions)&&(n.transactions=n.transactions.filter(r=>!(r.tool_name==null||r.amount===0&&r.status==="failed"))),n}async function Nne(t,e){return await ae.feedback(t.message,t.transaction_id,e)}var Cne=100;async function vne(t,e){if(!t.amount||!Number.isFinite(t.amount)||t.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(t.amount*100);if(n<Cne)return{success:!1,error:"Minimum top-up is $1.00"};let r=xt.randomUUID();T.info("buy_credits:attempt",{amountCents:n});try{return await gn(async()=>{let o=await Er("balance-topup",t.amount,"Visa CLI Balance",`top up balance with $${t.amount.toFixed(2)}`),s=await ae.topupBalance({amount_cents:n,idempotency_key:r,attestation:o});if(s.success){T.info("buy_credits:success",{amountCents:n,balanceCents:s.balanceCents});let i=((s.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...s,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return T.warn("buy_credits:failed",{amountCents:n,error:s.error}),s})}catch(o){if(o instanceof As)return El(o,"buy_credits");throw T.error("buy_credits:failure",{amountCents:n,error:o.message}),o}}function fl(t,e){return{success:!1,error:e,code:t,message:e}}async function Ine(t,e){if(!t.confirm)return fl("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(t.maxTransactionAmount!==void 0&&(typeof t.maxTransactionAmount!="number"||!Number.isFinite(t.maxTransactionAmount)||t.maxTransactionAmount<.01||t.maxTransactionAmount>1e4))return fl("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $10,000");if(t.dailyLimit!==void 0&&(typeof t.dailyLimit!="number"||!Number.isFinite(t.dailyLimit)||t.dailyLimit<1||t.dailyLimit>1e4))return fl("INVALID_VALUE","dailyLimit must be between $1 and $10,000");if(t.maxTransactionAmount!==void 0&&t.dailyLimit!==void 0&&t.maxTransactionAmount>t.dailyLimit)return fl("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");T.info("spending_controls:update",{maxTransactionAmount:t.maxTransactionAmount,dailyLimit:t.dailyLimit});try{return await gn(async()=>{let n=await Er("spending-controls",0,"","update spending controls"),r=await ae.updateSpendingControls({maxTransactionAmount:t.maxTransactionAmount,dailyLimit:t.dailyLimit,confirm:!0,attestation:n},e);return T.info("spending_controls:success",{maxTransactionAmount:t.maxTransactionAmount,dailyLimit:t.dailyLimit}),r})}catch(n){if(T.error("spending_controls:failure",{error:n.message}),n instanceof As)return El(n,"update_spending_controls");throw n}}async function Pne(t){let e=await T_({api:ae,includeDev:!!t.includeDev});return{config:e.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:e.statusError}}async function bne(t){if(!t.key||typeof t.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(t.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};T.info("config:set",{key:t.key});try{let e=Kp(t.key,t.value);return T.info("config:set:success",{key:e.key,requiresRestart:e.requiresRestart}),{success:!0,key:e.key,value:e.value,requiresRestart:e.requiresRestart,path:e.path,message:e.requiresRestart?`Saved ${e.key}. Restart Claude Code for the change to take effect.`:`Saved ${e.key}.`}}catch(e){let n=e instanceof yo?"UNKNOWN_KEY":e instanceof Oo?"SERVER_CONTROLLED":e instanceof ls?"RETIRED_KEY":"INVALID_VALUE";return T.warn("config:set:rejected",{key:t.key,code:n,error:e.message}),{success:!1,error:e.message,code:n,settableKeys:Object.keys(ps).sort()}}}async function Mne(t){if(!t.key||typeof t.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};T.info("config:unset",{key:t.key});try{let e=Wp(t.key);return T.info("config:unset:success",{key:e.key,removed:e.removed}),{success:!0,key:e.key,removed:e.removed,requiresRestart:e.requiresRestart,path:e.path,message:e.removed?e.requiresRestart?`Removed ${e.key}. Restart Claude Code for the change to take effect.`:`Removed ${e.key}.`:`${e.key} was not set in settings.json \u2014 nothing to remove.`}}catch(e){let n=e instanceof yo?"UNKNOWN_KEY":e instanceof Oo?"SERVER_CONTROLLED":e instanceof ls?"RETIRED_KEY":"INVALID_VALUE";return T.warn("config:unset:rejected",{key:t.key,code:n,error:e.message}),{success:!1,error:e.message,code:n,settableKeys:Object.keys(ps).sort()}}}async function Lne(t){let e=await ae.getStatus(t),n=e.attestationRequired!==!1,r=M_(e),o=it(),s=n?r?o?`${v_()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${v_()} is not available in this process. ${iT()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!e.hasAttestationKey,hasTelegramAttestationKey:!!e.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function xne(t){T.info("biometric:on");let e=await ae.setBiometricPreference({required:!0},t);return e.success?($P(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:e.error||"unknown error"}}async function Dne(t,e){if(!t.confirm)return fl("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");T.info("biometric:off");try{return await gn(async()=>{let n=await ae.getStatus(e),r;if(M_(n)&&(r=await Er("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${v_()} confirmation required to disable \u2014 not available on this device.`);let o=await ae.setBiometricPreference({required:!1,attestation:r},e);if(!o.success)throw new Error(o.error||"unknown error");return $P(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(T.error("biometric:off:failure",{error:n.message}),n instanceof As)return El(n,"biometric_off");throw n}}var LP=3e4,Une=3e5;async function jP(t,e,n="login"){let r=xt.randomUUID(),o=`${t}${t.includes("?")?"&":"?"}state=${r}`;return Yn(o),qP(r,e,n)}async function qP(t,e,n="login"){let r=Date.now()+Une;for(;Date.now()<r;)try{let s=await fetch(`${b_()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:t,timeout:LP,...e&&{user_context:e}}),signal:AbortSignal.timeout(LP+5e3)});if(!s.ok){await us(s,a=>{T.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return T.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=cP(a);if(i.sessionToken){await Ae.saveSessionToken(i.sessionToken);let l=i.user||"",d=i.last4||"****";return T.info("auth:login_complete",{user:l,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${l}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let u=i.last4||"****";return T.info("auth:card_added",{last4:u,bonusCents:a}),{success:!0,message:`Card ending in ${u} enrolled and ready for payments.`,...c||{}}}}catch{await us(void 0,s=>{T.warn("auth_status:retry_after_network_error",{delayMs:s})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function wne(t){let e=xt.randomUUID(),n;try{n=await ae.startAttestationRecovery(e,t)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(Yn(n.recoveryUrl),qP(e,t,"attestation-recovery"))}async function kne(t,e){if(!t.confirm)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=t.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};T.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await FP(n,e)}`;try{return await gn(async()=>{let s=await Er(r,0,"",o),i=await ae.removeCard(n,{attestation:s},e);return T.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(T.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof As)return El(s,"remove_card");throw s}}async function Vne(t,e){let n=t.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};T.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await FP(n,e)} as default`;try{return await gn(async()=>{let s=await Er(r,0,"",o),i=await ae.setDefaultCard(n,{attestation:s},e);return T.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(T.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof As)return El(s,"set_default_card");throw s}}async function Bne(t){return T.info("auth:login_attempt"),jP(`${b_()}/login`,t)}function Gne(t){if(t.capCents!==void 0){let e=Number(t.capCents);if(!Number.isFinite(e)||e<100||e>1e4)throw new Error("capCents must be between 100 ($1) and 10000 ($100)");return Math.floor(e)}if(t.capUsd!==void 0){let e=Number(t.capUsd);if(!Number.isFinite(e)||e<1||e>100)throw new Error("capUsd must be between 1 and 100");return Math.floor(e*100)}}async function Hne(t={},e){let n;try{n=Gne(t)}catch(r){return{success:!1,error:r?.message||String(r)}}return P_(async()=>{let r=await hP(ae,Er,{toolName:"start_session",userContext:e,capCentsOverride:n});T.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${s} was clamped to your prepaid balance of $${o}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function $ne(){let t=hs();if(!t)return{success:!0,active:!1,message:"No active session. Paid calls are pay-as-you-go and will request approval per call."};let e=Math.max(0,t.totalCents-t.estimatedCumulative);return{success:!0,active:!0,budgetId:t.budgetId,totalCents:t.totalCents,estimatedCumulativeCents:t.estimatedCumulative,estimatedRemainingCents:e,expiresAt:t.expiresAt,lastToolSpend:t.lastToolSpend,message:`Active session: about $${(e/100).toFixed(2)} remaining of $${(t.totalCents/100).toFixed(2)}.`}}async function Fne(){return P_(async()=>{let t=hs();if(!t)return{success:!0,message:"No active session to close.",closed:!1};let e=await tT(ae);T.info("session:closed",{budgetId:e.budgetId,closedServerSide:e.closedServerSide});let n=Bte(t),r=n.micros,o=Number(r/10000n);return T.info("session:closed:final-spend",{budgetId:e.budgetId,closedServerSide:e.closedServerSide,finalSpendMicros:r.toString(),finalSpendCents:o,finalSpendSource:n.source,totalCents:t.totalCents}),{success:!0,closed:!0,closedServerSide:e.closedServerSide,budgetId:e.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:r.toString(),totalCents:t.totalCents,message:e.closedServerSide?`Session closed. Spent ${Vte(r)} of $${(t.totalCents/100).toFixed(2)} cap.`:"Session cleared locally; server-side close call did not succeed (likely already closed). Paid calls will use pay-as-you-go until you start a new session."}})}async function jne(t){return T.info("auth:add_card_attempt"),await Ae.getSessionToken()?jP(`${b_()}/enroll`,t,"enrollment"):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function qne(t,e){if(!t.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};T.info("reset:attempt");let n=!1;try{let r=await ae.getStatus(e);if(r&&M_(r)){let o=await wne(e);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};T.warn("reset:server_attestation_status_unavailable",{error:o})}try{await ae.logout(void 0,e)}catch{}if(await Ae.clearAll(),it())try{await c_()}catch{}return T.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}function Yne(t){let e=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let n of e){let r=t[n];r&&typeof r=="string"&&r.startsWith("http")&&Yn(r)}Array.isArray(t.urls)&&t.urls.forEach(n=>{n&&typeof n=="string"&&n.startsWith("http")&&Yn(n)})}async function Kne(t){let e=t.query?.trim()||void 0,n=t.category?.trim()||void 0,r=!e&&!n;T.info("catalog:discover",{query:e,category:n,browseAll:r});try{let s=(await ae.catalogSearch(e,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${e||n}". Try a different search term.`}]};if(r){let a={};for(let u of s){let l=u.category||"other";(a[l]??=[]).push(u)}let c=Object.keys(a).sort().map(u=>{let l=a[u].map((p,_)=>`${_+1}. **${p.name}** (${p.id})
110
- ${p.description}
111
- Provider: ${p.provider} | Price: ${xP(p)}
112
- Params: ${Object.keys(p.inputSchema?.properties||p.inputSchema||{}).join(", ")||"none"}`).join(`
94
+ `}function xr(e=nn()){if(!e)return!1;try{let t=xn(e),n=L.readFileSync(t,"utf-8");return n.includes(Sn)||n.includes(oa)}catch{return!1}}function Cr(e=nn()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=xn(e);let n=L.existsSync(t)?L.readFileSync(t,"utf-8"):"",r=xd(n,e),s=r!==n;return s&&br(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${qs(n)}`}}}function kr(e=nn()){let t=[],n=[],r=[];try{for(let s of Sd(e))if(n.push(s.rcPath),!!L.existsSync(s.rcPath))try{let o=L.readFileSync(s.rcPath,"utf-8"),i=ca(o);if(i===o.trimEnd())continue;br(s.rcPath,i.length>0?`${i}
95
+ `:""),t.push(s.rcPath)}catch(o){r.push(`${s.rcPath}: ${qs(o)}`)}return t.length>0?{removed:!0,shell:e,rcPath:t[0],rcPaths:t,message:r.length>0?`Removed persistent shell HUD from ${t.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${t.join(", ")}.`}:r.length>0?{removed:!1,shell:e,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${qs(s)}`}}}function Bs(e,t){let n=t??vd,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=tn(r),o=` ${Q("\u2502",Z.dim)} `,i=la(n),a=Td(n,i),l=a||n.updateCheckDisabled?"":i,c=kd(s,l);if(!e.enrolled)return[c,Q("setup needed",Z.visaGold),a].filter(Boolean).join(o);let u=Rd(e),m=Cd(e);return[c,Q(u,Z.visaGold),m,a].filter(Boolean).join(o)}function Cd(e){let t=typeof e.balanceCents=="number"?e.balanceCents:null,n=e.activeSession;if(t===null)return Q("balance unknown",Z.dim);let r=t/100;if(n){let o=Math.max(0,n.capCents),i=Math.max(0,n.estimatedRemainingCents),a=Math.max(0,o-i),l=o>0?Math.max(0,Math.min(1,a/o)):0;return`${$d(l)} ${Q(`${Qt(i/100)} in session`,Z.green)} ${Q(`(${Qt(a/100)}/${Qt(o/100)} cap)`,Z.dim)} ${Q("\xB7",Z.dim)} ${Q(`${Qt(r)} balance`,Z.dim)}`}return t>=100?Q(`${Qt(r)} balance`,Z.green):Q(`${Qt(r)} balance \u2014 top up via buy_credits`,Z.visaGold)}function na(e){let t=/^([0-9]+\.[0-9]+\.[0-9]+)-(rc|beta|alpha|next)\.[0-9]+$/.exec(e);return t?`${t[1]} ${t[2].toUpperCase()}`:e}function kd(e,t){let n=na(e),r=`${Q("VISA CLI",Z.visaBlue)} ${Q(`v${n}`,Z.visaBlueSoft)}`;if(!t)return r;let s=na(t);return`${r} ${Q("\u2B06 update",Z.visaGold)} ${Q(`v${s}`,Z.visaGold)}`}function Td(e,t){if(t&&!e.updateCheckDisabled){let n=tn(Xt(t));return Q(`run: ${n}`,Z.visaGold)}return t?null:Ad(e)}function la(e){return e.latestVersion?tn(e.latestVersion):""}function Ad(e){let t=la(e);return t?Q(`update ready v${t}`,Z.visaGold):null}function ua(){let e=Ks();return!(!e||Date.now()-e.renderedAt>ia||e.cwd&&e.cwd!==process.cwd())}function Tr(){let e=Ks();if(e&&Date.now()-e.renderedAt<=ia||(Ed(),e?.line))return e.line;try{let t=wr();if(L.existsSync(t))return L.readFileSync(t,"utf-8").trimEnd()}catch{}return _d}function Hs(e,t){try{let n=V.dirname(en());L.mkdirSync(n,{recursive:!0});let r=tn(e),s={hudVersion:hd,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};br(en(),JSON.stringify(s)+`
96
+ `),br(wr(),r+`
97
+ `)}catch{}}function wn(){try{L.unlinkSync(aa())}catch{}}function Ks(){let e=en();if(!L.existsSync(e))return null;try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{return null}}function da(){return Ks()?.status??null}function Ed(){if(process.env.JEST_WORKER_ID)return;let e=aa();try{if(L.mkdirSync(V.dirname(e),{recursive:!0}),!Od(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){wn();return}let n=(0,sa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",wn),n.unref()}catch{wn()}}function tn(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function $d(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${Q(r||"",Z.green)}${Q(s||"",Z.dim)}`}function Qt(e){return`$${e.toFixed(2)}`}function Rd(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=tn(n.toUpperCase()),o=tn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Id(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Vs=Id(),Z={reset:"\x1B[0m",visaBlue:Vs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Vs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Vs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function Q(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${Z.reset}`}function ra(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gs(){let e=Sr.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function Pd(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Md(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Od(e){for(let t=0;t<2;t+=1){let n;try{return n=L.openSync(e,"wx"),L.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=L.statSync(e);if(Date.now()-s.mtimeMs<=bd)return!1;L.unlinkSync(e)}catch{}}finally{n!==void 0&&L.closeSync(n)}}return!1}function qs(e){return e instanceof Error?e.message:"unknown file system error"}function br(e,t){L.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;L.writeFileSync(n,t),L.renameSync(n,e)}async function rn(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&z()){d.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await hr();await e.registerAttestationKey(r),d.info("attestation:key-reregistered")}catch(r){throw d.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var ma="2.0.0-rc.42";function zs(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ar(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=tr(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function he(e){return e==null?"\u2014":e?"yes":"no"}function Er(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Nd(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ud(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=vs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:ys,source:{kind:"default"}}}async function $r(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(Y){n=Y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=_s("auth.serverUrl"),i=_e(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:he(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:he(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:he(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:z(),formatted:he(z()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,m=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Er(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:m,formatted:Er(m),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Er(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Er(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let h=t?.cards?.find(Y=>Y.isDefault)??t?.cards?.[0];h&&r.push({key:"cards.default",value:{brand:h.brand??null,last4:h.last4},formatted:`${h.brand||"card"} \u2022\u2022\u2022\u2022 ${h.last4}`,source:{kind:"server"}});let v=Ud();r.push({key:"credit.sessionCapCents",value:v.value,formatted:Nd(v.value),source:v.source});let g=mi();g.length>0&&r.push({key:"settings.retired",value:g.map(Y=>Y.key),formatted:g.map(Y=>Y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(Y=>`visa-cli config unset ${Y.key}`).join(" && ")}`});let x=Ar("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:x.value,formatted:he(x.value),source:x.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let O=Ar("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:O.value,formatted:he(O.value),source:O.source});let F=Me(),j;process.env.VISA_CLI_NO_UPDATE_CHECK?j={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?j={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?j={kind:"env",var:"NODE_ENV"}:j={kind:"default"},r.push({key:"ui.updateCheck",value:!F,formatted:he(!F),source:j});let k=Ar("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:k.value,formatted:he(k.value),source:k.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let P=Ar("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:P.value,formatted:he(P.value),source:P.source});let U=process.env.VISA_DRY_RUN,J=ea();if(r.push({key:"tools.dryRun",value:J,formatted:he(J),source:U===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:ma,formatted:ma,source:{kind:"default"}}),e.includeDev){let Y=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:Y==="true",formatted:he(Y==="true"),source:zs("VISA_MOCK_KEYCHAIN",!!Y)});let yt=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:yt==="true",formatted:he(yt==="true"),source:zs("VISA_MOCK_TOUCHID",!!yt)});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:he(!!K),source:zs("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function Dd(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function pa(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Dd(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
98
+ `)}function fa(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}function ga(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.10",what:"an AI song"}]}}}var lt=require("fs"),ya=require("os"),Ws=require("path"),Ld=(0,Ws.join)((0,ya.homedir)(),".visa-mcp"),ha=(0,Ws.join)(Ld,"mcp-session-budget.json");function Rr(){try{(0,lt.existsSync)(ha)&&(0,lt.unlinkSync)(ha)}catch{}}var Js=require("crypto"),Pr=null,Cn=0,kn=0,ut=0,Ys=null,Zs=null,Ir=Promise.resolve();function We(e){Pr=e,Cn=0,kn=0,ut=0,Ys=null,Zs=null,Ir=Promise.resolve()}function Tn(e){ut=Math.max(0,Math.floor(e))}function Xs(){return Pr}function Qs(e){if(!Pr)return null;let t=Cn+kn;return ut>0&&t>ut&&(t=ut),{session_budget_id:Pr,cumulative_micros:t*1e4,nonce:(0,Js.randomUUID)(),idempotency_key:e||(0,Js.randomUUID)()}}function eo(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return typeof r.cumulative=="number"&&Number.isFinite(r.cumulative)&&(Cn=r.cumulative,kn=0),Ys=r,r}function _a(){return Ys}function va(e){let t=e.receipt??null;Zs={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Math.floor(e.voucher.cumulative_micros/1e4),estimatedCumulativeCents:Mr(),receiptDeltaCents:typeof t?.delta=="number"?t.delta:null,receiptCumulativeCents:typeof t?.cumulative=="number"?t.cumulative:null,receiptRemainingCents:typeof t?.remaining=="number"?t.remaining:null,receiptDeltaMicros:typeof t?.delta_micros=="string"?t.delta_micros:null,receiptCumulativeMicros:typeof t?.cumulative_micros=="string"?t.cumulative_micros:null,receiptRemainingMicros:typeof t?.remaining_micros=="string"?t.remaining_micros:null,recordedAt:new Date().toISOString()}}function ba(){return Zs}function Sa(){return Cn}function Mr(){let e=Cn+kn;return ut>0&&e>ut&&(e=ut),e}function wa(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Ir=Ir.then(()=>{kn+=t}),Ir}var xa=100,B=null,Ca=Promise.resolve();function to(e){let t=Ca.catch(()=>{}).then(e);return Ca=t.then(()=>{},()=>{}),t}var le=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first (or enable auto-topup with update_spending_controls).`),this.name="InsufficientBalanceError"}};async function no(e,t,n){return to(()=>ka(e,t,n))}async function ka(e,t,n){if(Rr(),B&&new Date(B.expiresAt).getTime()>Date.now())return Xs()!==B.budgetId&&(We(B.budgetId),Tn(B.totalCents)),d.info("mcp-session:active-hit",{budgetId:B.budgetId,tool:n.toolName,remainingEstimatedCents:B.totalCents-Mr()}),{budgetId:B.budgetId,isFresh:!1,totalCents:B.totalCents,requestedCapCents:B.totalCents,appliedCapCents:B.totalCents,clampedReason:null};B&&(B=null,We(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<xa)throw new le(r.balanceCents,xa);let s=n.capCentsOverride??sr(),o=Math.min(s,r.balanceCents),i=o<s?"balance":null,a=await t("session_create",o,"Visa CLI Session",`open credit-model session with $${(o/100).toFixed(2)} cap`,n.userContext),l=await e.createSessionBudget({total_cents:o,...a?{attestation:a}:{}});if(!l.success||!l.budget){let u=l.error||"unknown error";throw new Error(`Failed to open credit session: ${u}`)}let c={budgetId:l.budget.id,expiresAt:l.budget.expiresAt,totalCents:l.budget.totalCents,createdAt:l.budget.createdAt};return B=c,We(c.budgetId),Tn(c.totalCents),d.info("mcp-session:opened",{budgetId:c.budgetId,capCents:c.totalCents,requestedCapCents:s,clampedReason:i,expiresAt:c.expiresAt,tool:n.toolName}),{budgetId:c.budgetId,isFresh:!0,totalCents:c.totalCents,requestedCapCents:s,appliedCapCents:c.totalCents,clampedReason:i}}async function Ta(e,t,n){return to(async()=>{let s=dt()?await Aa(e):null,o=await ka(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Aa(e){let n=dt()?.budgetId??Xs(),r=!1;if(n)try{r=!!(await e.closeSession(n))?.success}catch(s){d.warn("mcp-session:close-server-failed",{budgetId:n,error:s?.message||String(s)})}return Rr(),B=null,We(null),{closedServerSide:r,budgetId:n}}async function ro(e){return to(()=>Aa(e))}function dt(){return Rr(),B?new Date(B.expiresAt).getTime()<=Date.now()?(B=null,We(null),null):{budgetId:B.budgetId,totalCents:B.totalCents,lastReceiptCumulative:Sa(),lastReceiptCumulativeMicros:_a()?.cumulative_micros??null,estimatedCumulative:Mr(),lastToolSpend:ba(),expiresAt:B.expiresAt}:null}var Ra=A(so()),$a=10000n;function nm(e){return e<=0n?0:Number((e+$a-1n)/$a)}function Ia(e){return nm((0,Ra.fromUsd)(e))}var Pa=Promise.resolve();function Lr(e){let t=Pa.catch(()=>{}).then(e);return Pa=t.then(()=>{},()=>{}),t}async function Fa(e){let t=await no($,$e,{toolName:e.toolId,userContext:e.userContext}),n=Qs(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await lm(),{data:s,voucherReceiptHeader:o}=await $.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool),i=eo(o);if(await wa(e.estimatedAmountCents),va({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:i}),Ha(s))return s;let a=await Ba();if(e.idempotencyKey&&Ka(s,a,e.idempotencyKey))return s;let l=a?Nr(a):null;return Ga(s,r,l)}function Le(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ao(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(ao).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ao(r)}`).join(",")}}`}function rm(e,t,n,r){let s=se.createHash("sha256").update(`${n}:${ao(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function sm(e,t){return`${e}:${t}`}function om(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function Ma(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=mt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=om(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:sm(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function im(e){let n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<100)throw new le(n.balanceCents,100);let r=sr(),s=Math.min(r,n.balanceCents),o=Nr(n),i=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(s/100).toFixed(2)})`,a=await $e("session_create",s,"Visa CLI Session",i,e.userContext),l=await $.createSessionBudget({total_cents:s,...a?{attestation:a}:{}});if(!l.success||!l.budget)throw new Error(`Failed to open on-demand session: ${l.error||"unknown error"}`);let c=l.budget.id;We(c),Tn(l.budget.totalCents),d.info("on-demand-session:opened",{budgetId:c,capCents:l.budget.totalCents,tool:e.toolId});try{let u=Qs(e.idempotencyKey);if(!u)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:m,voucherReceiptHeader:h}=await $.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(eo(h),Ha(m))return m;let v=await Ba();if(e.idempotencyKey&&Ka(m,v,e.idempotencyKey))return m;let g=v?Nr(v):null;return Ga(m,o,g)}finally{try{await $.closeSession(c)}catch(u){d.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}We(null),d.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function ft(e){return Lr(async()=>dt()?Fa(e):im(e))}function jr(){return _e()}var $=new ve(()=>D.getSessionToken());function mt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Nr(e){return mt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function am(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function cm(e){let t=mt(e.lastReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"lastReceiptCumulativeMicros"};let n=mt(e.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function oo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}async function lm(){try{let e=await $.getBalance();return e.success?Nr(e):null}catch{return null}}async function Ba(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function Ha(e){if(!e||e.success===!1)return!1;let t=mt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=mt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Ka(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=mt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Ga(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var um="2.0.0-rc.42",Qh=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
99
+ `);function xe(e){if(!e||typeof e!="string"||pi())return;let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.toString(),r=rs();if(r.headless){d.info(`Browser auto-open skipped (${r.reason}). URL: ${n}`);return}let s=ss(n);if(!s){d.info(`No browser command for platform "${En.platform()}". URL: ${n}`);return}(0,qa.execFile)(s.cmd,s.args,o=>{o&&d.warn(`Browser open failed: ${o.message}. URL: ${n}`)})}async function fe(e){return rn($,e)}var za="get_cards",Wa="set_default_card";function dm(e,t=60){return`The processor returned a transient decline (code ${e??"unknown"}). This is not a permanent failure \u2014 it usually clears within ~${t} seconds and is most often triggered by rapid successive charges on the same card. Tell the user the call was temporarily declined and that you will retry shortly, then wait at least ${t} seconds before retrying the SAME call exactly once. Do not retry more than once. Do not assume the user has run out of funds. IMPORTANT: If the retry also fails, do NOT retry again \u2014 instead tell the user their default card may be temporarily locked by the processor and suggest switching to a different card. They can run '${za}' to see enrolled cards and '${Wa}' to switch, then retry the original request.`}function mm(e,t){return`The processor returned a non-retryable decline (code ${e??"unknown"}). Stop the current task and tell the user their card was declined for ${t||"the merchant"}. Suggest they check their card status or available balance. If they want to try a different default card, they can run '${za}' to see enrolled cards and '${Wa}' to switch. Do not retry automatically.`}function Ee(e,t){let n=e.retryable?dm(e.code,e.retryAfter):mm(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}var sn=null,pm=3e4;function Ja(){sn=null}var pt=class extends Error{constructor(n){super(`${Ur()} attestation is required for this action, but it is not available in this MCP process. `+co());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function $n(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+co()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ur(){return process.platform==="darwin"?"Touch ID":"local biometric"}function co(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function Vr(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function fm(e){let t=Date.now();if(sn&&sn.expiresAt>t)return{required:sn.required,hasRegisteredKey:sn.hasRegisteredKey};try{let n=await $.getStatus(e),r=n.attestationRequired!==!1,s=Vr(n);return sn={required:r,hasRegisteredKey:s,expiresAt:t+pm},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function $e(e,t,n,r,s){let o=await fm(s);if(!o.required){d.info("attestation:skipped-by-server-policy",{context:e});return}if(!o.hasRegisteredKey){d.info("attestation:skipped-no-registered-key",{context:e});return}if(!z())throw d.warn("attestation:unavailable",{context:e}),new pt(e);d.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await $.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");d.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Yt(a,r);return d.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw d.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Oa="[dry-run] https://placeholder.visa-cli.dev/image.png",gm=new Set(["generate_image_card","generate_image_fast_card","generate_image_schnell_card","generate_image_recraft_card","generate_image_ideogram_card","edit_image_seed_card","fal-flux-pro-ultra","fal-flux-pro","fal-flux-dev","fal-flux-schnell","fal-ideogram-v2","fal-ideogram-v2-turbo","fal-recraft-v3","fal-fast-sdxl"]),hm=new Set(["generate_video_tempo_card","generate_video_kling_card","generate_video_wan_card","generate_video_minimax_card","fal-kling-video","fal-wan-video","fal-kling-i2v","fal-minimax-video"]);function ym(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||gm.has(e)?"image":t==="generate_video"||hm.has(e)?"video":null}function _m(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function vm(e){return e==="llm"?"OpenRouter":"fal.ai"}function on(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:vm(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${_m(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Oa],data:{[e==="video"?"videoUrl":"imageUrl"]:Oa,metadata:{dry_run:!0}}}}async function io(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await $.emitTelemetry([{id:se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){d.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var bm="https://openrouter.ai/api/v1/chat/completions",Sm="openrouter/free",wm=50,xm=15e3;function Cm(e){let t=[e.prompt,e.user_prompt,e.input,e.text];for(let n of t)if(typeof n=="string"&&n.trim().length>0)return n;return"preflight"}async function km(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return d.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null};let s=Cm(t),o;try{o=await bt(bm,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","HTTP-Referer":"https://visacli.sh/preflight","X-Title":"Visa CLI Preflight"},body:JSON.stringify({model:Sm,messages:[{role:"user",content:s}],max_tokens:wm}),timeoutMs:xm})}catch(u){return d.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return d.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return d.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function qr(e,t,n,r){let s=Ds();if(!s)return null;let o=ym(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=on(o,e,t,r);return await io({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){d.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=on(o,e,t,r);return await io({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await km(e,t,r);return await io({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function Ye(e,t,n){let r=await $.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function gt(e){return Ia(e.amount)}function Tm(e){if(e.pricingMode==="max-cap"){let t=typeof e.estimatedAmount=="number"&&e.estimatedAmount>0?` (estimated $${e.estimatedAmount.toFixed(2)})`:"";return`pay up to $${e.amount.toFixed(2)} to ${e.merchantName}${t}`}return`pay $${e.amount.toFixed(2)} to ${e.merchantName}`}function Am(){return Dr.join(En.homedir(),".visa-mcp","allium-results")}var ey=16*1024,ty=50*1024*1024;function Em(){let e=Am();try{if(!Ae.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ae.readdirSync(e),n=0,r=0;for(let s of t)try{let o=Ae.statSync(Dr.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return d.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}async function Rn(e){if(!fi())try{let t=await D.getSessionToken();if(!t)return;await fetch(`${jr()}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),signal:AbortSignal.timeout(5e3)}),d.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType})}catch{}}async function $m(e,t){if(!e.url||!e.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let n=await Ye(void 0,e.url,t);d.info("payment:attempt",{tool:"pay",amount:n.amount,merchant:n.merchantName,url:e.url});try{return await fe(async()=>{let r=await $e(e.url||"pay",n.amount,n.merchantName,Tm(n)),s=await $.pay({url:e.url||"",merchantName:e.merchantName||"Unknown",description:e.description||"",method:e.method,body:e.body,attestation:r,idempotencyKey:se.randomUUID()},t);return s.success?(d.info("payment:success",{tool:"pay",amount:n.amount,merchant:n.merchantName,rail:s.receipt?.rail}),s.receipt&&gp(s.receipt)):d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,message:s.message}),s})}catch(r){if(r instanceof ne)return d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,code:r.code,retryable:r.retryable}),Ee(r,n);throw d.error("payment:failure",{tool:"pay",amount:n.amount,merchant:n.merchantName,error:r.message}),r}}async function Rm(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;d.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await fe(async()=>{let c=await $e("get_visa_smi",a,i,l),u=await $.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:se.randomUUID()},t);return u.success?d.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ne)return d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ee(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw d.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Im(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await qr("generate_image_card",e,t);if(n)return n;let r=await Ye("generate_image_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Pm(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await qr("generate_image_fast_card",e,t);if(n)return n;let r=await Ye("generate_image_fast_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Mm(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await qr("generate_video_tempo_card",e,t);if(n)return n;let r=await Ye("generate_video_tempo_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Om(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await Ye("generate_music_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}return d.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>xe(o)),Rn({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,d.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):d.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Nm(e,t){let n=await Ye("check_music_status_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}return d.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Um(e,t){if(!e.chain||!e.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!e.token_address||!e.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let n=await Ye("query_onchain_prices_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"query_onchain_prices_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}if(d.info("payment:success",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var Dm=["generate_music_tempo_card"],Na=50,Ua=5,Da=new Map;function La(e){let t=Da.get(e);if(t!==void 0)return t;let r=dr(e)?.isAsync===!0||Dm.includes(e);return Da.set(e,r),r}var Lm=36e4,jm=18e4,Vm=15e3,qm=12e4,Fm=2e3;async function Bm(e,t){let n;if(e.requests?.some(k=>k.tool||k.tool_id)&&e.requests)n=e.requests.map(k=>{let P=k.tool||k.tool_id||e.tool;if(!P)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let U=Us(P,k.tier||e.tier,k.prompt??t),{tool:J,tool_id:Y,tier:yt,params:K,...Ce}=k,qn=K&&typeof K=="object"?{...K,...Ce}:Ce;return{resolvedTool:U,params:qn}});else if(e.tool){let k=Us(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(U=>({resolvedTool:k,params:U}))}else throw new Error("Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)throw new Error("Batch requires at least one item.");if(n.length>Na)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Na} items. Please split into smaller batches.`};if([...new Set(n.map(k=>k.resolvedTool))].some(La)&&n.length>Ua)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Ua} items. Please use multiple batches for more.`};let i=[...new Set(n.map(k=>k.resolvedTool))],a=i.length===1,l={};for(let k of i)l[k]=await Ye(k,void 0,t);let c=0;for(let k of n)c+=l[k.resolvedTool].amount;let u=[...new Set(Object.values(l).map(k=>k.merchantName))].join(", "),m=a?i[0]:"mixed";d.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let h=n.some(k=>La(k.resolvedTool)),v=n.some(k=>k.resolvedTool.startsWith("or-")||k.resolvedTool==="run_llm"||k.resolvedTool==="execute_tool"),g=h?Lm:v?jm+n.length*Vm:qm+n.length*Fm,x=se.randomUUID(),O=[],F=0,j=0n;return Lr(async()=>{let k=!dt();if(k)try{await no($,$e,{toolName:"batch",userContext:t})}catch(P){return P instanceof le?Le(P):(d.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:P?.message||String(P)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:P?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let K=0;K<n.length;K+=1){let Ce=n[K],qn=l[Ce.resolvedTool];try{let ee=await Fa({toolId:Ce.resolvedTool,toolParams:Ce.params,estimatedAmountCents:gt(qn),userContext:t,metaTool:"batch",timeoutMs:g,idempotencyKey:rm(x,K,Ce.resolvedTool,Ce.params)});if(O.push({success:ee?.success!==!1,tool:Ce.resolvedTool,...ee,...Ma(x,K,ee)}),ee?.success!==!1){let dn=mt(ee?.amountMicros??ee?.amount_micros),Ao=typeof ee?.amount=="number"?ee.amount:qn.amount;dn!==null&&dn>0n?j+=dn:j+=BigInt(Math.round(Ao*1e6)),F+=Ao}ee?.urls&&ee.urls.forEach(dn=>xe(dn))}catch(ee){if(ee instanceof le&&O.length===0)return Le(ee);d.warn("payment:batch-item-failed",{tool:Ce.resolvedTool,index:K,error:ee?.message||String(ee)}),O.push({success:!1,tool:Ce.resolvedTool,...Ma(x,K),error:ee?.message||String(ee)})}}let P=O.filter(K=>K?.success===!1).length,U=O.length-P,J=O.flatMap(K=>Array.isArray(K?.urls)?K.urls:[]),Y=j>0n?Number(j)/1e6:Math.round((F+Number.EPSILON)*100)/100,yt=U===0?"failure":P===0?"success":"partial";return d.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,totalCharged:Y,merchant:u,successCount:U,failedCount:P,outcome:yt,mode:"session",batchId:x}),{success:U>0,outcome:yt,batch_id:x,tool:a?i[0]:m,count:n.length,successCount:U,failedCount:P,totalCharged:Y,...j>0n?{totalChargedMicros:j.toString(),amountMicros:j.toString(),amount_micros:j.toString()}:{},merchantName:u,results:O,...J.length?{urls:J}:{}}}catch(P){if(P instanceof ne)return d.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,code:P.code,retryable:P.retryable}),Ee(P,{amount:c,merchantName:u});throw d.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,error:P.message}),P}finally{if(k){let P=await ro($);d.info("batch-session:closed",{budgetId:P.budgetId,closedServerSide:P.closedServerSide})}}})}function Hm(){let e=!1,t;try{let r=Dr.join(En.homedir(),".claude","settings.json");if(Ae.existsSync(r)){let s=JSON.parse(Ae.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=_t(o)}}catch{}let n=xr();return n||(t="visa-cli config shell-hud install"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Km(e){let[t,n]=await Promise.all([$.getStatus(e),$.getBalance().catch(o=>(d.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Em();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Hm(),t.version=um,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:lo(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=dt();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function lo(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function Ya(e,t){try{let r=((await $.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return lo(r)}catch(n){d.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Gm(e){let n=(await $.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:lo(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function zm(e,t){let n=await $.getTransactions({limit:e.limit,offset:e.offset},t);return Array.isArray(n?.transactions)&&(n.transactions=n.transactions.filter(r=>!(r.tool_name==null||r.amount===0&&r.status==="failed"))),n}async function Wm(e,t){return await $.feedback(e.message,e.transaction_id,t)}var Jm=100;async function Ym(e,t){if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<Jm)return{success:!1,error:"Minimum top-up is $1.00"};let r=se.randomUUID();d.info("buy_credits:attempt",{amountCents:n});try{return await fe(async()=>{let s=await $e("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`),o=await $.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){d.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return d.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof pt)return $n(s,"buy_credits");throw d.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function An(e,t){return{success:!1,error:t,code:e,message:t}}async function Zm(e,t){if(!e.confirm)return An("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>1e4))return An("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $10,000");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>1e4))return An("INVALID_VALUE","dailyLimit must be between $1 and $10,000");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return An("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");d.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await fe(async()=>{let n=await $e("spending-controls",0,"","update spending controls"),r=await $.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return d.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(d.error("spending_controls:failure",{error:n.message}),n instanceof pt)return $n(n,"update_spending_controls");throw n}}async function Xm(e){let t=await $r({api:$,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function Qm(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};d.info("config:set",{key:e.key});try{let t=nr(e.key,e.value);return d.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof Fe?"UNKNOWN_KEY":t instanceof Be?"SERVER_CONTROLLED":t instanceof nt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(st).sort()}}}async function ep(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};d.info("config:unset",{key:e.key});try{let t=rr(e.key);return d.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof Fe?"UNKNOWN_KEY":t instanceof Be?"SERVER_CONTROLLED":t instanceof nt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(st).sort()}}}async function tp(e){let t=await $.getStatus(e),n=t.attestationRequired!==!1,r=Vr(t),s=z(),o=n?r?s?`${Ur()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ur()} is not available in this process. ${co()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function np(e){d.info("biometric:on");let t=await $.setBiometricPreference({required:!0},e);return t.success?(Ja(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function rp(e,t){if(!e.confirm)return An("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");d.info("biometric:off");try{return await fe(async()=>{let n=await $.getStatus(t),r;if(Vr(n)&&(r=await $e("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ur()} confirmation required to disable \u2014 not available on this device.`);let s=await $.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Ja(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(d.error("biometric:off:failure",{error:n.message}),n instanceof pt)return $n(n,"biometric_off");throw n}}var ja=3e4,sp=3e5;async function Za(e,t,n="login"){let r=se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return xe(s),Xa(r,t,n)}async function Xa(e,t,n="login"){let r=Date.now()+sp;for(;Date.now()<r;)try{let o=await fetch(`${jr()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:ja,...t&&{user_context:t}}),signal:AbortSignal.timeout(ja+5e3)});if(!o.ok){await tt(o,a=>{d.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return d.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=ga(a);if(i.sessionToken){await D.saveSessionToken(i.sessionToken);let u=i.user||"",m=i.last4||"****";return d.info("auth:login_complete",{user:u,last4:m,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${m} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return d.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await tt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function op(e){let t=se.randomUUID(),n;try{n=await $.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(xe(n.recoveryUrl),Xa(t,e,"attestation-recovery"))}async function ip(e,t){if(!e.confirm)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};d.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await Ya(n,t)}`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.removeCard(n,{attestation:o},t);return d.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(d.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof pt)return $n(o,"remove_card");throw o}}async function ap(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};d.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await Ya(n,t)} as default`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.setDefaultCard(n,{attestation:o},t);return d.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(d.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof pt)return $n(o,"set_default_card");throw o}}async function cp(e){return d.info("auth:login_attempt"),Za(`${jr()}/login`,e)}function lp(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<100||t>1e4)throw new Error("capCents must be between 100 ($1) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<1||t>100)throw new Error("capUsd must be between 1 and 100");return Math.floor(t*100)}}async function up(e={},t){let n;try{n=lp(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Lr(async()=>{let r=await Ta($,$e,{toolName:"start_session",userContext:t,capCentsOverride:n});d.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function dp(){let e=dt();if(!e)return{success:!0,active:!1,message:"No active session. Paid calls are pay-as-you-go and will request approval per call."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active session: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function mp(){return Lr(async()=>{let e=dt();if(!e)return{success:!0,message:"No active session to close.",closed:!1};let t=await ro($);d.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=cm(e),r=n.micros,s=Number(r/10000n);return d.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:r.toString(),finalSpendCents:s,finalSpendSource:n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:r.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Session closed. Spent ${am(r)} of $${(e.totalCents/100).toFixed(2)} cap.`:"Session cleared locally; server-side close call did not succeed (likely already closed). Paid calls will use pay-as-you-go until you start a new session."}})}async function pp(e){return d.info("auth:add_card_attempt"),await D.getSessionToken()?Za(`${jr()}/enroll`,e,"enrollment"):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function fp(e,t){if(!e.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};d.info("reset:attempt");let n=!1;try{let r=await $.getStatus(t);if(r&&Vr(r)){let s=await op(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};d.warn("reset:server_attestation_status_unavailable",{error:s})}try{await $.logout(void 0,t)}catch{}if(await D.clearAll(),z())try{await yr()}catch{}return d.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}function gp(e){let t=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let n of t){let r=e[n];r&&typeof r=="string"&&r.startsWith("http")&&xe(r)}Array.isArray(e.urls)&&e.urls.forEach(n=>{n&&typeof n=="string"&&n.startsWith("http")&&xe(n)})}async function hp(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;d.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await $.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((h,v)=>`${v+1}. **${h.name}** (${h.id})
100
+ ${h.description}
101
+ Provider: ${h.provider} | Price: ${Va(h)}
102
+ Params: ${Object.keys(h.inputSchema?.properties||h.inputSchema||{}).join(", ")||"none"}`).join(`
113
103
 
114
- `);return`## ${u.length<=3?u.toUpperCase():u.charAt(0).toUpperCase()+u.slice(1)}
104
+ `);return`## ${c.length<=3?c.toUpperCase():c.charAt(0).toUpperCase()+c.slice(1)}
115
105
 
116
- ${l}`}).join(`
106
+ ${u}`}).join(`
117
107
 
118
- `);return T.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Available ${s.length} tool(s) by category:
108
+ `);return d.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Available ${o.length} tool(s) by category:
119
109
 
120
- ${c}
110
+ ${l}
121
111
 
122
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}let i=s.map((a,c)=>`${c+1}. **${a.name}** (${a.id})
112
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}let i=o.map((a,l)=>`${l+1}. **${a.name}** (${a.id})
123
113
  ${a.description}
124
- Provider: ${a.provider} | Category: ${a.category} | Price: ${xP(a)}
114
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Va(a)}
125
115
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
126
116
 
127
- `);return T.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
117
+ `);return d.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
128
118
 
129
119
  ${i}
130
120
 
131
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw T.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function xP(t){return t.priceDisplay??`$${(t.priceCents/100).toFixed(2)}`}function Wne(t,e){return e==="image"||e==="video"||e==="audio"?e:t?.match(/\.(mp4|webm|mov)/)?"video":"image"}function N_(t,e){return Array.isArray(t.type)?t.type.includes(e):t.type===e}function zne(t,e){let n=t.inputSchema;if(!n||n.type!=="object")return null;let r=n.properties??{};for(let o of n.required??[])if(e[o]===void 0||e[o]===null||e[o]==="")return`${o} is required for ${t.id}.`;for(let[o,s]of Object.entries(e)){let i=r[o];if(!(!i||s===void 0||s===null)){if(i.enum&&!i.enum.includes(s))return`${o} must be one of: ${i.enum.map(String).join(", ")}.`;if(N_(i,"integer")){if(typeof s!="number"||!Number.isInteger(s))return`${o} must be an integer.`}else if(N_(i,"number")){if(typeof s!="number"||!Number.isFinite(s))return`${o} must be a number.`}else if(N_(i,"string")){if(typeof s!="string")return`${o} must be a string.`;if(s.trim()==="")return`${o} is required for ${t.id}.`;if(i.minLength!==void 0&&s.length<i.minLength)return`${o} is too short.`;if(i.maxLength!==void 0&&s.length>i.maxLength)return`${o} is too long.`}else if(N_(i,"boolean")&&typeof s!="boolean")return`${o} must be a boolean.`;if(typeof s=="number"){if(i.minimum!==void 0&&s<i.minimum)return`${o} must be at least ${i.minimum}.`;if(i.maximum!==void 0&&s>i.maximum)return`${o} must be at most ${i.maximum}.`}}}return null}async function Xne(t){let e=n_(t);if(e)return e;try{return await ae.catalogTool(t)}catch(n){return T.warn("catalog:resolve:error",{tool:t,error:n?.message||String(n)}),null}}async function Jne(t,e,n="execute_tool"){let{tool_id:r,params:o,...s}=t,i=o||s;if(!r)return rT("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");T.info("catalog:execute",{tool:r,metaTool:n});let a=await Xne(r);if(!a)return rT(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");let c=zne(a,i);if(c)return T.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),rT(c);let u=await L_(r,i,e,n);if(u)return u;let l=await Mo(r,void 0,e),d=xt.randomUUID();T.info("payment:attempt",{tool:r,amount:l.amount,merchant:l.merchantName});try{return await gn(async()=>{let p;try{p=await Rs({toolId:r,toolParams:i,estimatedAmountCents:ys(l),userContext:e,metaTool:n,timeoutMs:12e4,idempotencyKey:d})}catch(_){if(_ instanceof nn)return Fr(_);throw _}if(T.info("payment:success",{tool:r,amount:l.amount,merchant:l.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(f=>Yn(f));let _=Wne(p.urls[0],p.mediaType);Sl({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:_,cost:p.amount??l.amount,transactionId:p.transactionId,userContext:e})}return p})}catch(p){if(p instanceof Mt)return T.warn("payment:declined",{tool:r,amount:l.amount,merchant:l.merchantName,code:p.code,retryable:p.retryable}),mr(p,l);throw T.error("payment:failure",{tool:r,amount:l.amount,merchant:l.merchantName,error:p.message}),p}}var Wa=class{static async getStatus(e){return Rne(e)}static async pay(e,n){return ine(e,n)}static async getVisaSmi(e,n){return ane(e,n)}static async getCards(e){return yne(e)}static async transactionHistory(e,n){return One(e||{},n)}static async feedback(e,n){return Nne(e,n)}static async updateSpendingControls(e,n){return Ine(e,n)}static async configList(e){return Pne(e||{})}static async configSet(e){return bne(e||{})}static async configUnset(e){return Mne(e||{})}static async biometricStatus(e){return Lne(e)}static async biometricOn(e){return xne(e)}static async biometricOff(e,n){return Dne(e,n)}static async reset(e,n){return qne(e,n)}static async login(e){return Bne(e)}static async closeSession(e){return Fne()}static async startSession(e,n){return Hne(e||{},n)}static async getSessionStatus(e){return $ne()}static async addCard(e){return jne(e)}static async removeCard(e,n){return kne(e,n)}static async setDefaultCard(e,n){return Vne(e,n)}static async buyCredits(e,n){return vne(e,n)}static async batch(e,n){return Tne(e,n)}static async discoverTools(e){return Kne(e)}static async executeTool(e,n,r="execute_tool"){return Jne(e,n,r)}static async shortcut(e,n,r){switch(e){case"generate_image_card":return cne(n,r);case"generate_image_fast_card":return une(n,r);case"generate_video_tempo_card":return lne(n,r);case"generate_music_tempo_card":return dne(n,r);case"check_music_status_tempo_card":return pne(n,r);case"query_onchain_prices_card":return _ne(n,r);default:{T.info("payment:attempt",{tool:e});try{let o=await Rs({toolId:e,toolParams:n,estimatedAmountCents:0,userContext:r,timeoutMs:6e4});return T.info("payment:success",{tool:e,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Yn(s)),o}catch(o){if(o instanceof nn)return Fr(o);if(o instanceof Mt)return T.warn("payment:declined",{tool:e,code:o.code,retryable:o.retryable}),mr(o,{amount:0,merchantName:e});throw T.error("payment:failure",{tool:e,error:o.message}),o}}}}static async submitFeedback(e,n,r){T.info("feedback:submit",{length:e.length});try{let o=await ae.submitFeedback(e,n,r);return T.info("feedback:submitted",{message:"Feedback received"}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw T.error("feedback:error",{error:s}),o}}static async getFeedback(e,n){T.info("feedback:list",{limit:e||20});try{let r=await ae.getFeedback(e,n);return T.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw T.error("feedback:error",{error:o}),r}}};function YP(t,e=process.stderr){if(Vr()||!t?.updateAvailable)return!1;let{latestVersion:n}=t.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${za()}`;return e.write(`
121
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw d.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Va(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function yp(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Or(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function _p(e,t){let n=e.inputSchema;if(!n||n.type!=="object")return null;let r=n.properties??{};for(let s of n.required??[])if(t[s]===void 0||t[s]===null||t[s]==="")return`${s} is required for ${e.id}.`;for(let[s,o]of Object.entries(t)){let i=r[s];if(!(!i||o===void 0||o===null)){if(i.enum&&!i.enum.includes(o))return`${s} must be one of: ${i.enum.map(String).join(", ")}.`;if(Or(i,"integer")){if(typeof o!="number"||!Number.isInteger(o))return`${s} must be an integer.`}else if(Or(i,"number")){if(typeof o!="number"||!Number.isFinite(o))return`${s} must be a number.`}else if(Or(i,"string")){if(typeof o!="string")return`${s} must be a string.`;if(o.trim()==="")return`${s} is required for ${e.id}.`;if(i.minLength!==void 0&&o.length<i.minLength)return`${s} is too short.`;if(i.maxLength!==void 0&&o.length>i.maxLength)return`${s} is too long.`}else if(Or(i,"boolean")&&typeof o!="boolean")return`${s} must be a boolean.`;if(typeof o=="number"){if(i.minimum!==void 0&&o<i.minimum)return`${s} must be at least ${i.minimum}.`;if(i.maximum!==void 0&&o>i.maximum)return`${s} must be at most ${i.maximum}.`}}}return null}async function vp(e){let t=dr(e);if(t)return t;try{return await $.catalogTool(e)}catch(n){return d.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function bp(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return oo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");d.info("catalog:execute",{tool:r,metaTool:n});let a=await vp(r);if(!a)return oo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");let l=_p(a,i);if(l)return d.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),oo(l);let c=await qr(r,i,t,n);if(c)return c;let u=await Ye(r,void 0,t),m=se.randomUUID();d.info("payment:attempt",{tool:r,amount:u.amount,merchant:u.merchantName});try{return await fe(async()=>{let h;try{h=await ft({toolId:r,toolParams:i,estimatedAmountCents:gt(u),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(v){if(v instanceof le)return Le(v);throw v}if(d.info("payment:success",{tool:r,amount:u.amount,merchant:u.merchantName,mode:"session"}),h&&typeof h=="object"&&!Array.isArray(h)&&h.merchantName==null&&(h.merchantName=a?.name??r),h.urls?.length){h.urls.forEach(g=>xe(g));let v=yp(h.urls[0],h.mediaType);Rn({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:h.urls[0],mediaType:v,cost:h.amount??u.amount,transactionId:h.transactionId,userContext:t})}return h})}catch(h){if(h instanceof ne)return d.warn("payment:declined",{tool:r,amount:u.amount,merchant:u.merchantName,code:h.code,retryable:h.retryable}),Ee(h,u);throw d.error("payment:failure",{tool:r,amount:u.amount,merchant:u.merchantName,error:h.message}),h}}var Zt=class{static async getStatus(t){return Km(t)}static async pay(t,n){return $m(t,n)}static async getVisaSmi(t,n){return Rm(t,n)}static async getCards(t){return Gm(t)}static async transactionHistory(t,n){return zm(t||{},n)}static async feedback(t,n){return Wm(t,n)}static async updateSpendingControls(t,n){return Zm(t,n)}static async configList(t){return Xm(t||{})}static async configSet(t){return Qm(t||{})}static async configUnset(t){return ep(t||{})}static async biometricStatus(t){return tp(t)}static async biometricOn(t){return np(t)}static async biometricOff(t,n){return rp(t,n)}static async reset(t,n){return fp(t,n)}static async login(t){return cp(t)}static async closeSession(t){return mp()}static async startSession(t,n){return up(t||{},n)}static async getSessionStatus(t){return dp()}static async addCard(t){return pp(t)}static async removeCard(t,n){return ip(t,n)}static async setDefaultCard(t,n){return ap(t,n)}static async buyCredits(t,n){return Ym(t,n)}static async batch(t,n){return Bm(t,n)}static async discoverTools(t){return hp(t)}static async executeTool(t,n,r="execute_tool"){return bp(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Im(n,r);case"generate_image_fast_card":return Pm(n,r);case"generate_video_tempo_card":return Mm(n,r);case"generate_music_tempo_card":return Om(n,r);case"check_music_status_tempo_card":return Nm(n,r);case"query_onchain_prices_card":return Um(n,r);default:{d.info("payment:attempt",{tool:t});try{let s=await ft({toolId:t,toolParams:n,estimatedAmountCents:0,userContext:r,timeoutMs:6e4});return d.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s}catch(s){if(s instanceof le)return Le(s);if(s instanceof ne)return d.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ee(s,{amount:0,merchantName:t});throw d.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){d.info("feedback:submit",{length:t.length});try{let s=await $.submitFeedback(t,n,r);return d.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw d.error("feedback:error",{error:o}),s}}static async getFeedback(t,n){d.info("feedback:list",{limit:t||20});try{let r=await $.getFeedback(t,n);return d.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw d.error("feedback:error",{error:s}),r}}};function Qa(e,t=process.stderr){if(Me()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${Xt()}`;return t.write(`
132
122
  \x1B[33m\u2191 ${r}\x1B[0m
133
- `),!0}var Zne=20;function WP(t,e,n,r){let o=r.currentVersion==="0.0.0"&&t.version?t.version:r.currentVersion,i=sre(t.spendingControls).dailyLimit,a=Math.max(0,hl(t.dailySpent)),c=i>0?Math.min(i,Math.max(0,hl(t.dailyRemaining??i-a))):0,u=i>0?Math.min(1,a/i):0,d=(Array.isArray(e)?e:[]).filter(tre),p=d.slice(0,3),_=nre(d,3),f=(t.cards??[]).slice(0,3),E=r.latestVersion?gl(r.latestVersion):"",S=r.updateCheckDisabled?"update checks disabled":E?`update ready: v${E}`:"up to date",h=Math.round(u*100),R=Os(t.status,t.enrolled?"approved":"not enrolled"),O=["VISA CLI",`Status: ${t.enrolled?"Visa ready":"Visa setup needed"} | account: ${R} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${S}`,`Spend meter: ${KP(u)} ${String(h).padStart(3," ")}% | remaining ${rc(c)}/day | daily cap ${rc(i)}`,"","Spend",` Remaining ${rc(c)} / ${rc(i)}`,` Usage ${KP(u)} ${h}%`,` Spent today ${rc(a)}`,` Attestation key ${t.hasAttestationKey?"registered":"missing"}`,"","Cards",...f.length>0?f.map(y=>` ${ore(y)}`):[" No cards enrolled"],"","Last 3 services",..._.length>0?_.map((y,M)=>` ${M+1}. ${y}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(y=>` ${rre(y)}`):[" No receipts yet"]];if(E&&!r.updateCheckDisabled){let y=gl(za(E));O.push("",`Update: v${E} ready \u2014 run \`${y}\``),r.updateMessage&&O.push(` ${gl(r.updateMessage)}`)}else r.updateMessage&&O.push("",`Update: ${gl(r.updateMessage)}`);return`${O.join(`
123
+ `),!0}var Sp=20;function tc(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Ep(e.spendingControls).dailyLimit,a=Math.max(0,Pn(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Pn(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,m=(Array.isArray(t)?t:[]).filter(Cp),h=m.slice(0,3),v=kp(m,3),g=(e.cards??[]).slice(0,3),x=r.latestVersion?In(r.latestVersion):"",O=r.updateCheckDisabled?"update checks disabled":x?`update ready: v${x}`:"up to date",F=Math.round(c*100),j=ht(e.status,e.enrolled?"approved":"not enrolled"),P=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${j} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${O}`,`Spend meter: ${ec(c)} ${String(F).padStart(3," ")}% | remaining ${an(l)}/day | daily cap ${an(i)}`,"","Spend",` Remaining ${an(l)} / ${an(i)}`,` Usage ${ec(c)} ${F}%`,` Spent today ${an(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(U=>` ${Ap(U)}`):[" No cards enrolled"],"","Last 3 services",...v.length>0?v.map((U,J)=>` ${J+1}. ${U}`):[" No paid services yet"],"","Recent receipts",...h.length>0?h.map(U=>` ${Tp(U)}`):[" No receipts yet"]];if(x&&!r.updateCheckDisabled){let U=In(Xt(x));P.push("",`Update: v${x} ready \u2014 run \`${U}\``),r.updateMessage&&P.push(` ${In(r.updateMessage)}`)}else r.updateMessage&&P.push("",`Update: ${In(r.updateMessage)}`);return`${P.join(`
134
124
  `)}
135
- `}function Qne(t){return t.tool_name!=null}function ere(t){return hl(t.amount)===0&&t.status==="failed"}function tre(t){return Qne(t)&&!ere(t)}function nre(t,e=1/0){let n=new Set,r=[];for(let o of t){if(r.length>=e)break;let s=Os(o.merchant_name,"Unknown merchant"),i=Os(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function rre(t){let e=Os(t.merchant_name,"Unknown merchant"),n=Os(t.tool_name,"unknown_tool"),r=rc(hl(t.amount)),o=Os(t.status,"unknown"),s=ire(t.created_at);return`${r} ${o.padEnd(9)} ${e} [${n}] ${s}`}function ore(t){let e=Os(t.brand?.toUpperCase(),"CARD"),n=t.isDefault?" default":"";return`${e} ****${t.last4}${n}`}function sre(t){return{dailyLimit:hl(t?.daily_limit??t?.dailyLimit??0)}}function hl(t){let e=Number(typeof t=="string"?t:t??0);return Number.isFinite(e)?e:0}function rc(t){return`$${t.toFixed(2)}`}function KP(t,e=Zne){let n=Math.max(0,Math.min(1,t)),r=Math.round(n*e);return`[${"\u2588".repeat(r)}${"\u2591".repeat(e-r)}]`}function Os(t,e){let n=gl(t??"").trim();return n.length>0?n:e}function ire(t){if(!t)return"unknown time";let e=new Date(t);return Number.isNaN(e.getTime())?Os(t,"unknown time"):e.toISOString().slice(0,16).replace("T"," ")}function gl(t){return t.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var qg=v(nT());var are=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function cre(){let t=new Set;for(let e of are)t.add(e),t.add(e.replace(/-/g,"_")),t.add(e.replace(/_/g,"-"));for(let e of al)t.add(e),t.add(e.replace(/-/g,"_")),t.add(e.replace(/_/g,"-"));return t}var zqe=cre();var cT=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var eYe=new Set(al),tYe=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...cT,...al]);var hn=class extends Error{constructor(e){super(e),this.name="PayValidationError"}},zP=["GET","POST"];function XP(t){let e;try{e=new URL(t)}catch{throw new hn(`Invalid URL: ${t}. Expected a fully-qualified http(s) URL.`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new hn(`Unsupported URL scheme "${e.protocol}". Only http and https are allowed.`);return e}function JP(t){let e=(t??"GET").toUpperCase();if(!zP.includes(e))throw new hn(`Unsupported HTTP method "${t}". Supported: ${zP.join(", ")}.`);return e}function ZP(t){if(t!==void 0){try{JSON.parse(t)}catch(e){throw new hn(`--body is not valid JSON: ${e?.message??"parse error"}`)}return t}}function QP(t){if(!t||typeof t!="object")throw new hn("Merchant returned no payment preview.");let e=t;if(typeof e.amount!="number"||!Number.isFinite(e.amount)||e.amount<=0)throw new hn("Could not determine payment amount from merchant.");if(typeof e.merchantName!="string"||e.merchantName.trim().length===0)throw new hn("Merchant returned an empty merchant name.");if(e.merchantName.length>200)throw new hn(`Merchant name too long (${e.merchantName.length} chars).`);if(typeof e.currency!="string"||e.currency.trim().length===0)throw new hn("Merchant returned an empty currency.");if(e.currency.length>10)throw new hn(`Currency code too long (${e.currency.length} chars).`);return{amount:e.amount,currency:e.currency,merchantName:e.merchantName}}var Ee=v(require("fs")),ce=v(require("path")),eb=v(require("os")),Ze=eb.homedir(),ure=["Claude_","Anthropic.ClaudeDesktop_"],oc=class extends Error{constructor(n,r,o){super(dre(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function tb(t){let e=t;return[e?.message,e?.stderr].filter(n=>typeof n=="string").join(`
136
- `)}function lre(t){let e=t;if(e?.code==="EPERM"||e?.code==="EACCES")return!0;let n=tb(t).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function dre(t,e,n){let r=e.replace(Ze,"~"),o=tb(n).split(`
137
- `).find(Boolean),s=o?` (${o})`:"";return t.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${t.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function Tl(){return process.env.APPDATA||ce.join(Ze,"AppData","Roaming")}function pre(){return process.env.LOCALAPPDATA||ce.join(Ze,"AppData","Local")}function uT(t){return process.platform==="win32"?t.win32:t.posix}function nb(){if(process.platform!=="win32")return;let t=ce.join(pre(),"Packages");if(Ee.existsSync(t))try{let e=Ee.readdirSync(t,"utf-8");for(let n of ure){let r=e.filter(o=>o.startsWith(n)).sort()[0];if(r)return ce.join(t,r,"LocalCache","Roaming","Claude")}}catch{return}}function rb(){if(process.platform==="win32"){let t=nb();return t?ce.join(t,"claude_desktop_config.json"):ce.join(Tl(),"Claude","claude_desktop_config.json")}return ce.join(Ze,"Library","Application Support","Claude","claude_desktop_config.json")}function ob(){if(process.platform!=="win32")return[ce.join(Ze,"Library","Application Support","Claude")];let t=[ce.join(Tl(),"Claude")],e=nb();return e&&t.push(e),t}function x_(t){return t.id==="claude-desktop"?rb():t.globalConfigPath}function _re(t){return t.id==="claude-desktop"?ob():t.detectPaths}var Sr=[{id:"claude",displayName:"Claude Code",globalConfigPath:ce.join(Ze,".claude.json"),configKey:"mcpServers",detectPaths:[ce.join(Ze,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:rb(),configKey:"mcpServers",detectPaths:ob(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:ce.join(Ze,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[ce.join(Ze,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:ce.join(Ze,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[ce.join(Ze,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:ce.join(Ze,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[ce.join(Ze,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:uT({win32:ce.join(Tl(),"Roo","mcp_settings.json"),posix:ce.join(Ze,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[ce.join(Ze,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:ce.join(Ze,".vscode","mcp.json"),configKey:"servers",detectPaths:[ce.join(Ze,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:uT({win32:ce.join(Tl(),"Zed","settings.json"),posix:ce.join(Ze,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:uT({win32:[ce.join(Tl(),"Zed")],posix:[ce.join(Ze,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:t=>({source:"custom",...t})},{id:"codex",displayName:"Codex",globalConfigPath:ce.join(Ze,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[ce.join(Ze,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli config hud enable"}];function lT(t){return Sr.find(e=>e.id===t)}function Al(t){return _re(t).some(e=>{if(e.includes("*")){let n=ce.dirname(e),r=ce.basename(e).replaceAll("*","");if(!Ee.existsSync(n))return!1;try{return Ee.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return Ee.existsSync(e)})}function sb(){return{command:"node",args:[ce.resolve(__dirname,"mcp-server/index.js")]}}function dT(t,e){return e==="project"?"json":t.configFormat??"json"}function fre(t){if(t=t.trim(),t==="true")return!0;if(t==="false")return!1;if(t.startsWith('"')&&t.endsWith('"'))return t.slice(1,-1);if(t.startsWith("[")&&t.endsWith("]")){let n=t.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let e=Number(t);return isNaN(e)?t:e}function pT(t,e){let n=`[mcp_servers.${e}]`,r=t.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<t.length&&!t[o].trim().startsWith("[");)o++;return{start:r,end:o}}function _T(t,e){let n=t.split(`
138
- `),r=pT(n,e);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=fre(i[2]))}return Object.keys(o).length>0?o:void 0}function mre(t,e,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${e}]`,`command = "${n.command}"`,`args = ${r}`],s=t.split(`
139
- `),i=pT(s,e);if(i){s.splice(i.start,i.end-i.start,...o);let c=s.join(`
140
- `);return c.endsWith(`
141
- `)?c:c+`
142
- `}let a=t.trimEnd();return a+(a.length>0?`
143
-
144
- `:"")+o.join(`
125
+ `}function wp(e){return e.tool_name!=null}function xp(e){return Pn(e.amount)===0&&e.status==="failed"}function Cp(e){return wp(e)&&!xp(e)}function kp(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=ht(s.merchant_name,"Unknown merchant"),i=ht(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Tp(e){let t=ht(e.merchant_name,"Unknown merchant"),n=ht(e.tool_name,"unknown_tool"),r=an(Pn(e.amount)),s=ht(e.status,"unknown"),o=$p(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ap(e){let t=ht(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Ep(e){return{dailyLimit:Pn(e?.daily_limit??e?.dailyLimit??0)}}function Pn(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function an(e){return`$${e.toFixed(2)}`}function ec(e,t=Sp){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function ht(e,t){let n=In(e??"").trim();return n.length>0?n:t}function $p(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?ht(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function In(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var Gr=A(so());var Rp=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function Ip(){let e=new Set;for(let t of Rp)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of bn)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var my=Ip();var uo=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var yy=new Set(bn),_y=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...uo,...bn]);var ge=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},nc=["GET","POST"];function rc(e){let t;try{t=new URL(e)}catch{throw new ge(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new ge(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function sc(e){let t=(e??"GET").toUpperCase();if(!nc.includes(t))throw new ge(`Unsupported HTTP method "${e}". Supported: ${nc.join(", ")}.`);return t}function oc(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new ge(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function ic(e){if(!e||typeof e!="object")throw new ge("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new ge("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new ge("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new ge(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new ge("Merchant returned an empty currency.");if(t.currency.length>10)throw new ge(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var N=A(require("fs")),R=A(require("path")),ac=A(require("os")),H=ac.homedir(),Pp=["Claude_","Anthropic.ClaudeDesktop_"],cn=class extends Error{constructor(n,r,s){super(Op(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function cc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
126
+ `)}function Mp(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=cc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Op(e,t,n){let r=t.replace(H,"~"),s=cc(n).split(`
127
+ `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Mn(){return process.env.APPDATA||R.join(H,"AppData","Roaming")}function Np(){return process.env.LOCALAPPDATA||R.join(H,"AppData","Local")}function mo(e){return process.platform==="win32"?e.win32:e.posix}function lc(){if(process.platform!=="win32")return;let e=R.join(Np(),"Packages");if(N.existsSync(e))try{let t=N.readdirSync(e,"utf-8");for(let n of Pp){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return R.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function uc(){if(process.platform==="win32"){let e=lc();return e?R.join(e,"claude_desktop_config.json"):R.join(Mn(),"Claude","claude_desktop_config.json")}return R.join(H,"Library","Application Support","Claude","claude_desktop_config.json")}function dc(){if(process.platform!=="win32")return[R.join(H,"Library","Application Support","Claude")];let e=[R.join(Mn(),"Claude")],t=lc();return t&&e.push(t),e}function Fr(e){return e.id==="claude-desktop"?uc():e.globalConfigPath}function Up(e){return e.id==="claude-desktop"?dc():e.detectPaths}var Re=[{id:"claude",displayName:"Claude Code",globalConfigPath:R.join(H,".claude.json"),configKey:"mcpServers",detectPaths:[R.join(H,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:uc(),configKey:"mcpServers",detectPaths:dc(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:R.join(H,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:R.join(H,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[R.join(H,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:mo({win32:R.join(Mn(),"Roo","mcp_settings.json"),posix:R.join(H,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"servers",detectPaths:[R.join(H,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:mo({win32:R.join(Mn(),"Zed","settings.json"),posix:R.join(H,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:mo({win32:[R.join(Mn(),"Zed")],posix:[R.join(H,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:R.join(H,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[R.join(H,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli config hud enable"}];function po(e){return Re.find(t=>t.id===e)}function On(e){return Up(e).some(t=>{if(t.includes("*")){let n=R.dirname(t),r=R.basename(t).replaceAll("*","");if(!N.existsSync(n))return!1;try{return N.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return N.existsSync(t)})}function mc(){return{command:"node",args:[R.resolve(__dirname,"mcp-server/index.js")]}}function fo(e,t){return t==="project"?"json":e.configFormat??"json"}function Dp(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function go(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function ho(e,t){let n=e.split(`
128
+ `),r=go(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=Dp(i[2]))}return Object.keys(s).length>0?s:void 0}function Lp(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
129
+ `),i=go(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let l=o.join(`
130
+ `);return l.endsWith(`
131
+ `)?l:l+`
132
+ `}let a=e.trimEnd();return a+(a.length>0?`
133
+
134
+ `:"")+s.join(`
145
135
  `)+`
146
- `}function Ere(t,e){let n=t.split(`
147
- `),r=pT(n,e);return r?(n.splice(r.start,r.end-r.start),n.join(`
136
+ `}function jp(e,t){let n=e.split(`
137
+ `),r=go(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
148
138
  `).replace(/\n{3,}/g,`
149
139
 
150
- `)):t}function Rl(t,e="global"){let n=e==="project"?ce.join(process.cwd(),".mcp.json"):x_(t);try{let r=ce.dirname(n);Ee.existsSync(r)||Ee.mkdirSync(r,{recursive:!0});let o=dT(t,e),s=sb();if(o==="toml"){let i=Ee.existsSync(n)?Ee.readFileSync(n,"utf-8"):"",a=mre(i,"visa-cli",s);Ee.writeFileSync(n,a)}else{let i={};if(Ee.existsSync(n))try{i=JSON.parse(Ee.readFileSync(n,"utf-8"))}catch{i={}}i[t.configKey]=i[t.configKey]||{},i[t.configKey]["visa-cli"]=t.buildEntry?t.buildEntry(s):s,Ee.writeFileSync(n,JSON.stringify(i,null,2)+`
151
- `)}}catch(r){throw lre(r)?new oc(t,n,r):r}return{installed:!0,configPath:n,message:t.postInstallHint}}function fT(t,e="global"){let n=e==="project"?ce.join(process.cwd(),".mcp.json"):x_(t);if(!Ee.existsSync(n))return{removed:!1,configPath:n};if(dT(t,e)==="toml"){let i=Ee.readFileSync(n,"utf-8");return _T(i,"visa-cli")?(Ee.writeFileSync(n,Ere(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(Ee.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[t.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],Ee.writeFileSync(n,JSON.stringify(o,null,2)+`
152
- `),{removed:!0,configPath:n})}function ib(t,e="global"){let n=e==="project"?ce.join(process.cwd(),".mcp.json"):x_(t);if(!Ee.existsSync(n))return!1;if(dT(t,e)==="toml")try{let o=Ee.readFileSync(n,"utf-8");return!!_T(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(Ee.readFileSync(n,"utf-8"))?.[t.configKey]?.["visa-cli"]}catch{return!1}}function Sre(t){if(!t||typeof t!="object")return;let e=t;if(e.command!=="node"||!Array.isArray(e.args)||e.args.length===0)return;let n=e.args[e.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function gre(t,e){if(t===e)return!0;let n=ce.resolve(t),r=ce.resolve(e);if(n===r)return!0;try{let o=Ee.realpathSync(n),s=Ee.realpathSync(r);return o===s}catch{return!1}}function yl(){let t=sb(),e=t.args[t.args.length-1],n=[];for(let r of Sr){let o=x_(r);if(!Ee.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let u=Ee.readFileSync(o,"utf-8");i=_T(u,"visa-cli")}catch{continue}else{let u;try{u=JSON.parse(Ee.readFileSync(o,"utf-8"))}catch{continue}i=u?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Sre(i);if(!a||gre(a,e))continue;let c=Ee.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:e,staleReason:c})}return n}function mT(t){return{configPath:Rl(t.client,"global").configPath}}x();var Dz=v(pH(),1);var V=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var te=globalThis;var Pe="9.47.1";function cn(){return Ds(te),te}function Ds(t){let e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||Pe,e[Pe]=e[Pe]||{}}function Do(t,e,n=te){let r=n.__SENTRY__=n.__SENTRY__||{},o=r[Pe]=r[Pe]||{};return o[t]||(o[t]=e())}var sd=["debug","info","warn","error","log","assert","trace"],ARe="Sentry Logger ",Pc={};function qe(t){if(!("console"in te))return t();let e=te.console,n={},r=Object.keys(Pc);r.forEach(o=>{let s=Pc[o];n[o]=e[o],e[o]=s});try{return t()}finally{r.forEach(o=>{e[o]=n[o]})}}function RRe(){JR().enabled=!0}function yRe(){JR().enabled=!1}function _H(){return JR().enabled}function ORe(...t){XR("log",...t)}function NRe(...t){XR("warn",...t)}function CRe(...t){XR("error",...t)}function XR(t,...e){V&&_H()&&qe(()=>{te.console[t](`${ARe}[${t}]:`,...e)})}function JR(){return V?Do("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var g={enable:RRe,disable:yRe,isEnabled:_H,log:ORe,warn:NRe,error:CRe};var fH=/\(error: (.*)\)/,mH=/captureMessage|captureException/;function Pm(...t){let e=t.sort((n,r)=>n[0]-r[0]).map(n=>n[1]);return(n,r=0,o=0)=>{let s=[],i=n.split(`
153
- `);for(let a=r;a<i.length;a++){let c=i[a];if(c.length>1024)continue;let u=fH.test(c)?c.replace(fH,"$1"):c;if(!u.match(/\S*Error: /)){for(let l of e){let d=l(u);if(d){s.push(d);break}}if(s.length>=50+o)break}}return EH(s.slice(o))}}function QR(t){return Array.isArray(t)?Pm(...t):t}function EH(t){if(!t.length)return[];let e=Array.from(t);return/sentryWrapped/.test(Im(e).function||"")&&e.pop(),e.reverse(),mH.test(Im(e).function||"")&&(e.pop(),mH.test(Im(e).function||"")&&e.pop()),e.slice(0,50).map(n=>({...n,filename:n.filename||Im(e).filename,function:n.function||"?"}))}function Im(t){return t[t.length-1]||{}}var ZR="<anonymous>";function id(t){try{return!t||typeof t!="function"?ZR:t.name||ZR}catch{return ZR}}var bm={},SH={};function bc(t,e){bm[t]=bm[t]||[],bm[t].push(e)}function Mc(t,e){if(!SH[t]){SH[t]=!0;try{e()}catch(n){V&&g.error(`Error while instrumenting ${t}`,n)}}}function Lc(t,e){let n=t&&bm[t];if(n)for(let r of n)try{r(e)}catch(o){V&&g.error(`Error while triggering instrumentation handler.
154
- Type: ${t}
155
- Name: ${id(r)}
156
- Error:`,o)}}var ey=null;function gH(t){let e="error";bc(e,t),Mc(e,vRe)}function vRe(){ey=te.onerror,te.onerror=function(t,e,n,r,o){return Lc("error",{column:r,error:o,line:n,msg:t,url:e}),ey?ey.apply(this,arguments):!1},te.onerror.__SENTRY_INSTRUMENTED__=!0}var ty=null;function hH(t){let e="unhandledrejection";bc(e,t),Mc(e,IRe)}function IRe(){ty=te.onunhandledrejection,te.onunhandledrejection=function(t){return Lc("unhandledrejection",t),ty?ty.apply(this,arguments):!0},te.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}var TH=Object.prototype.toString;function Us(t){switch(TH.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Jr(t,Error)}}function Mm(t,e){return TH.call(t)===`[object ${e}]`}function ny(t){return Mm(t,"ErrorEvent")}function ws(t){return Mm(t,"String")}function xc(t){return typeof t=="object"&&t!==null&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function Dc(t){return t===null||xc(t)||typeof t!="object"&&typeof t!="function"}function Uo(t){return Mm(t,"Object")}function ry(t){return typeof Event<"u"&&Jr(t,Event)}function oy(t){return typeof Element<"u"&&Jr(t,Element)}function sy(t){return Mm(t,"RegExp")}function Ar(t){return!!(t?.then&&typeof t.then=="function")}function iy(t){return Uo(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}function Jr(t,e){try{return t instanceof e}catch{return!1}}function ad(t){return!!(typeof t=="object"&&t!==null&&(t.__isVue||t._isVue))}var PRe=te,bRe=80;function AH(t,e={}){if(!t)return"<unknown>";try{let n=t,r=5,o=[],s=0,i=0,a=" > ",c=a.length,u,l=Array.isArray(e)?e:e.keyAttrs,d=!Array.isArray(e)&&e.maxStringLength||bRe;for(;n&&s++<r&&(u=MRe(n,l),!(u==="html"||s>1&&i+o.length*c+u.length>=d));)o.push(u),i+=u.length,n=n.parentNode;return o.reverse().join(a)}catch{return"<unknown>"}}function MRe(t,e){let n=t,r=[];if(!n?.tagName)return"";if(PRe.HTMLElement&&n instanceof HTMLElement&&n.dataset){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}r.push(n.tagName.toLowerCase());let o=e?.length?e.filter(i=>n.getAttribute(i)).map(i=>[i,n.getAttribute(i)]):null;if(o?.length)o.forEach(i=>{r.push(`[${i[0]}="${i[1]}"]`)});else{n.id&&r.push(`#${n.id}`);let i=n.className;if(i&&ws(i)){let a=i.split(/\s+/);for(let c of a)r.push(`.${c}`)}}let s=["aria-label","type","name","title","alt"];for(let i of s){let a=n.getAttribute(i);a&&r.push(`[${i}="${a}"]`)}return r.join("")}function Zr(t,e=0){return typeof t!="string"||e===0||t.length<=e?t:`${t.slice(0,e)}...`}function ay(t,e){let n=t,r=n.length;if(r<=150)return n;e>r&&(e=r);let o=Math.max(e-60,0);o<5&&(o=0);let s=Math.min(o+140,r);return s>r-5&&(s=r),s===r&&(o=Math.max(s-140,0)),n=n.slice(o,s),o>0&&(n=`'{snip} ${n}`),s<r&&(n+=" {snip}"),n}function cy(t,e){if(!Array.isArray(t))return"";let n=[];for(let r=0;r<t.length;r++){let o=t[r];try{ad(o)?n.push("[VueViewModel]"):n.push(String(o))}catch{n.push("[value cannot be serialized]")}}return n.join(e)}function RH(t,e,n=!1){return ws(t)?sy(e)?e.test(t):ws(e)?n?t===e:t.includes(e):!1:!1}function ks(t,e=[],n=!1){return e.some(r=>RH(t,r,n))}function uy(t,e,n){if(!(e in t))return;let r=t[e];if(typeof r!="function")return;let o=n(r);typeof o=="function"&&NH(o,r);try{t[e]=o}catch{V&&g.log(`Failed to replace method "${e}" in object`,t)}}function ct(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch{V&&g.log(`Failed to add non-enumerable property "${e}" to object`,t)}}function NH(t,e){try{let n=e.prototype||{};t.prototype=e.prototype=n,ct(t,"__sentry_original__",e)}catch{}}function ly(t){return t.__sentry_original__}function Lm(t){if(Us(t))return{message:t.message,name:t.name,stack:t.stack,...OH(t)};if(ry(t)){let e={type:t.type,target:yH(t.target),currentTarget:yH(t.currentTarget),...OH(t)};return typeof CustomEvent<"u"&&Jr(t,CustomEvent)&&(e.detail=t.detail),e}else return t}function yH(t){try{return oy(t)?AH(t):Object.prototype.toString.call(t)}catch{return"<unknown>"}}function OH(t){if(typeof t=="object"&&t!==null){let e={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}else return{}}function dy(t,e=40){let n=Object.keys(Lm(t));n.sort();let r=n[0];if(!r)return"[object has no keys]";if(r.length>=e)return Zr(r,e);for(let o=n.length;o>0;o--){let s=n.slice(0,o).join(", ");if(!(s.length>e))return o===n.length?s:Zr(s,e)}return""}function LRe(){let t=te;return t.crypto||t.msCrypto}function Et(t=LRe()){let e=()=>Math.random()*16;try{if(t?.randomUUID)return t.randomUUID().replace(/-/g,"");t?.getRandomValues&&(e=()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch{}return("10000000100040008000"+1e11).replace(/[018]/g,n=>(n^(e()&15)>>n/4).toString(16))}function CH(t){return t.exception?.values?.[0]}function Vs(t){let{message:e,event_id:n}=t;if(e)return e;let r=CH(t);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||n||"<unknown>":n||"<unknown>"}function _y(t,e,n){let r=t.exception=t.exception||{},o=r.values=r.values||[],s=o[0]=o[0]||{};s.value||(s.value=e||""),s.type||(s.type=n||"Error")}function Uc(t,e){let n=CH(t);if(!n)return;let r={type:"generic",handled:!0},o=n.mechanism;if(n.mechanism={...r,...o,...e},e&&"data"in e){let s={...o?.data,...e.data};n.mechanism.data=s}}var xRe=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function py(t){return parseInt(t||"",10)}function fy(t){let e=t.match(xRe)||[],n=py(e[1]),r=py(e[2]),o=py(e[3]);return{buildmetadata:e[5],major:isNaN(n)?void 0:n,minor:isNaN(r)?void 0:r,patch:isNaN(o)?void 0:o,prerelease:e[4]}}function xm(t){if(DRe(t))return!0;try{ct(t,"__sentry_captured__",!0)}catch{}return!1}function DRe(t){try{return t.__sentry_captured__}catch{}}var IH=1e3;function wo(){return Date.now()/IH}function URe(){let{performance:t}=te;if(!t?.now||!t.timeOrigin)return wo;let e=t.timeOrigin;return()=>(e+t.now())/IH}var vH;function Bs(){return(vH??(vH=URe()))()}function PH(t){let e=Bs(),n={sid:Et(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>wRe(n)};return t&&ko(n,t),n}function ko(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),!t.did&&!e.did&&(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||Bs(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=e.sid.length===32?e.sid:Et()),e.init!==void 0&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),typeof e.started=="number"&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if(typeof e.duration=="number")t.duration=e.duration;else{let n=t.timestamp-t.started;t.duration=n>=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),typeof e.errors=="number"&&(t.errors=e.errors),e.status&&(t.status=e.status)}function bH(t,e){let n={};e?n={status:e}:t.status==="ok"&&(n={status:"exited"}),ko(t,n)}function wRe(t){return{sid:`${t.sid}`,init:t.init,started:new Date(t.started*1e3).toISOString(),timestamp:new Date(t.timestamp*1e3).toISOString(),status:t.status,errors:t.errors,did:typeof t.did=="number"||typeof t.did=="string"?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}function Gs(t,e,n=2){if(!e||typeof e!="object"||n<=0)return e;if(t&&Object.keys(e).length===0)return t;let r={...t};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=Gs(r[o],e[o],n-1));return r}function Rr(){return Et()}function Ln(){return Et().substring(16)}var my="_sentrySpan";function sa(t,e){e?ct(t,my,e):delete t[my]}function ia(t){return t[my]}var kRe=100,An=class t{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:Rr(),sampleRand:Math.random()}}clone(){let e=new t;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,sa(e,ia(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&ko(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,n){return this._tags={...this._tags,[e]:n},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,n){return this._extra={...this._extra,[e]:n},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,n){return n===null?delete this._contexts[e]:this._contexts[e]=n,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;let n=typeof e=="function"?e(this):e,r=n instanceof t?n.getScopeData():Uo(n)?e:void 0,{tags:o,extra:s,user:i,contexts:a,level:c,fingerprint:u=[],propagationContext:l}=r||{};return this._tags={...this._tags,...o},this._extra={...this._extra,...s},this._contexts={...this._contexts,...a},i&&Object.keys(i).length&&(this._user=i),c&&(this._level=c),u.length&&(this._fingerprint=u),l&&(this._propagationContext=l),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,sa(this,void 0),this._attachments=[],this.setPropagationContext({traceId:Rr(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(e,n){let r=typeof n=="number"?n:kRe;if(r<=0)return this;let o={timestamp:wo(),...e,message:e.message?Zr(e.message,2048):e.message};return this._breadcrumbs.push(o),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:ia(this)}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Gs(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,n){let r=n?.event_id||Et();if(!this._client)return V&&g.warn("No client configured on scope - will not capture exception!"),r;let o=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:o,...n,event_id:r},this),r}captureMessage(e,n,r){let o=r?.event_id||Et();if(!this._client)return V&&g.warn("No client configured on scope - will not capture message!"),o;let s=new Error(e);return this._client.captureMessage(e,n,{originalException:e,syntheticException:s,...r,event_id:o},this),o}captureEvent(e,n){let r=n?.event_id||Et();return this._client?(this._client.captureEvent(e,{...n,event_id:r},this),r):(V&&g.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}};function wc(){return Do("defaultCurrentScope",()=>new An)}function Qr(){return Do("defaultIsolationScope",()=>new An)}var Ey=class{constructor(e,n){let r;e?r=e:r=new An;let o;n?o=n:o=new An,this._stack=[{scope:r}],this._isolationScope=o}withScope(e){let n=this._pushScope(),r;try{r=e(n)}catch(o){throw this._popScope(),o}return Ar(r)?r.then(o=>(this._popScope(),o),o=>{throw this._popScope(),o}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}};function kc(){let t=cn(),e=Ds(t);return e.stack=e.stack||new Ey(wc(),Qr())}function VRe(t){return kc().withScope(t)}function BRe(t,e){let n=kc();return n.withScope(()=>(n.getStackTop().scope=t,e(t)))}function MH(t){return kc().withScope(()=>t(kc().getIsolationScope()))}function LH(){return{withIsolationScope:MH,withScope:VRe,withSetScope:BRe,withSetIsolationScope:(t,e)=>MH(e),getCurrentScope:()=>kc().getScope(),getIsolationScope:()=>kc().getIsolationScope()}}function Sy(t){let e=cn(),n=Ds(e);n.acs=t}function yr(t){let e=Ds(t);return e.acs?e.acs:LH()}function ue(){let t=cn();return yr(t).getCurrentScope()}function Re(){let t=cn();return yr(t).getIsolationScope()}function Dm(){return Do("globalScope",()=>new An)}function eo(...t){let e=cn(),n=yr(e);if(t.length===2){let[r,o]=t;return r?n.withSetScope(r,o):n.withScope(o)}return n.withScope(t[0])}function cd(...t){let e=cn(),n=yr(e);if(t.length===2){let[r,o]=t;return r?n.withSetIsolationScope(r,o):n.withIsolationScope(o)}return n.withIsolationScope(t[0])}function K(){return ue().getClient()}function Vc(t){let e=t.getPropagationContext(),{traceId:n,parentSpanId:r,propagationSpanId:o}=e,s={trace_id:n,span_id:o||Ln()};return r&&(s.parent_span_id=r),s}var St="sentry.source",Or="sentry.sample_rate",gy="sentry.previous_trace_sample_rate",se="sentry.op",ye="sentry.origin";var hy="sentry.measurement_unit",Ty="sentry.measurement_value",to="sentry.custom_span_name",Bc="sentry.profile_id",Gc="sentry.exclusive_time",Ay="cache.hit",Ry="cache.key",yy="cache.item_size";function Um(t){if(t<400&&t>=100)return{code:1};if(t>=400&&t<500)switch(t){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(t>=500&&t<600)switch(t){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}var xH="_sentryScope",DH="_sentryIsolationScope";function ud(t,e,n){t&&(ct(t,DH,n),ct(t,xH,e))}function Nr(t){return{scope:t[xH],isolationScope:t[DH]}}var ld="sentry-",wH=/^sentry-/,kH=8192;function Hs(t){let e=ca(t);if(!e)return;let n=Object.entries(e).reduce((r,[o,s])=>{if(o.match(wH)){let i=o.slice(ld.length);r[i]=s}return r},{});if(Object.keys(n).length>0)return n}function aa(t){if(!t)return;let e=Object.entries(t).reduce((n,[r,o])=>(o&&(n[`${ld}${r}`]=o),n),{});return wm(e)}function ca(t){if(!(!t||!ws(t)&&!Array.isArray(t)))return Array.isArray(t)?t.reduce((e,n)=>{let r=UH(n);return Object.entries(r).forEach(([o,s])=>{e[o]=s}),e},{}):UH(t)}function UH(t){return t.split(",").map(e=>e.split("=").map(n=>{try{return decodeURIComponent(n.trim())}catch{return}})).reduce((e,[n,r])=>(n&&r&&(e[n]=r),e),{})}function wm(t){if(Object.keys(t).length!==0)return Object.entries(t).reduce((e,[n,r],o)=>{let s=`${encodeURIComponent(n)}=${encodeURIComponent(r)}`,i=o===0?s:`${e},${s}`;return i.length>kH?(V&&g.warn(`Not adding key: ${n} with val: ${r} to baggage header due to exceeding baggage size limits.`),e):i},"")}function xn(t){if(typeof t=="boolean")return Number(t);let e=typeof t=="string"?parseFloat(t):t;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}var km=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function VH(t){if(!t)return;let e=t.match(km);if(!e)return;let n;return e[3]==="1"?n=!0:e[3]==="0"&&(n=!1),{traceId:e[1],parentSampled:n,parentSpanId:e[2]}}function dd(t,e){let n=VH(t),r=Hs(e);if(!n?.traceId)return{traceId:Rr(),sampleRand:Math.random()};let o=GRe(n,r);r&&(r.sample_rand=o.toString());let{traceId:s,parentSpanId:i,parentSampled:a}=n;return{traceId:s,parentSpanId:i,sampled:a,dsc:r||{},sampleRand:o}}function $s(t=Rr(),e=Ln(),n){let r="";return n!==void 0&&(r=n?"-1":"-0"),`${t}-${e}${r}`}function GRe(t,e){let n=xn(e?.sample_rand);if(n!==void 0)return n;let r=xn(e?.sample_rate);return r&&t?.parentSampled!==void 0?t.parentSampled?Math.random()*r:r+Math.random()*(1-r):Math.random()}var Bm=0,Gm=1,BH=!1;function HH(t){let{spanId:e,traceId:n}=t.spanContext(),{data:r,op:o,parent_span_id:s,status:i,origin:a,links:c}=W(t);return{parent_span_id:s,span_id:e,trace_id:n,data:r,op:o,status:i,origin:a,links:c}}function Fs(t){let{spanId:e,traceId:n,isRemote:r}=t.spanContext(),o=r?e:W(t).parent_span_id,s=Nr(t).scope,i=r?s?.getPropagationContext().propagationSpanId||Ln():e;return{parent_span_id:o,span_id:i,trace_id:n}}function Hm(t){let{traceId:e,spanId:n}=t.spanContext(),r=no(t);return $s(e,n,r)}function ua(t){if(t&&t.length>0)return t.map(({context:{spanId:e,traceId:n,traceFlags:r,...o},attributes:s})=>({span_id:e,trace_id:n,sampled:r===Gm,attributes:s,...o}))}function Rn(t){return typeof t=="number"?GH(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?GH(t.getTime()):Bs()}function GH(t){return t>9999999999?t/1e3:t}function W(t){if(FRe(t))return t.getSpanJSON();let{spanId:e,traceId:n}=t.spanContext();if($Re(t)){let{attributes:r,startTime:o,name:s,endTime:i,status:a,links:c}=t,u="parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0;return{span_id:e,trace_id:n,data:r,description:s,parent_span_id:u,start_timestamp:Rn(o),timestamp:Rn(i)||void 0,status:la(a),op:r[se],origin:r[ye],links:ua(c)}}return{span_id:e,trace_id:n,start_timestamp:0,data:{}}}function $Re(t){let e=t;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function FRe(t){return typeof t.getSpanJSON=="function"}function no(t){let{traceFlags:e}=t.spanContext();return e===Gm}function la(t){if(!(!t||t.code===0))return t.code===1?"ok":t.message||"unknown_error"}var pd="_sentryChildSpans",Oy="_sentryRootSpan";function Hc(t,e){let n=t[Oy]||t;ct(e,Oy,n),t[pd]?t[pd].add(e):ct(t,pd,new Set([e]))}function $m(t){let e=new Set;function n(r){if(!e.has(r)&&no(r)){e.add(r);let o=r[pd]?Array.from(r[pd]):[];for(let s of o)n(s)}}return n(t),Array.from(e)}function Ye(t){return t[Oy]||t}function ro(){let t=cn(),e=yr(t);return e.getActiveSpan?e.getActiveSpan():ia(ue())}function _d(){BH||(qe(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),BH=!0)}var $H=!1;function FH(){if($H)return;function t(){let e=ro(),n=e&&Ye(e);if(n){let r="internal_error";V&&g.log(`[Tracing] Root span: ${r} -> Global error occurred`),n.setStatus({code:2,message:r})}}t.tag="sentry_tracingErrorCallback",$H=!0,gH(t),hH(t)}function vt(t){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=t||K()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var $c="production";var jRe=/^o(\d+)\./,qRe=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function YRe(t){return t==="http"||t==="https"}function vr(t,e=!1){let{host:n,path:r,pass:o,port:s,projectId:i,protocol:a,publicKey:c}=t;return`${a}://${c}${e&&o?`:${o}`:""}@${n}${s?`:${s}`:""}/${r&&`${r}/`}${i}`}function KRe(t){let e=qRe.exec(t);if(!e){qe(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});return}let[n,r,o="",s="",i="",a=""]=e.slice(1),c="",u=a,l=u.split("/");if(l.length>1&&(c=l.slice(0,-1).join("/"),u=l.pop()),u){let d=u.match(/^\d+/);d&&(u=d[0])}return jH({host:s,pass:o,path:c,projectId:u,port:i,protocol:n,publicKey:r})}function jH(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function WRe(t){if(!V)return!0;let{port:e,projectId:n,protocol:r}=t;return["protocol","publicKey","host","projectId"].find(i=>t[i]?!1:(g.error(`Invalid Sentry Dsn: ${i} missing`),!0))?!1:n.match(/^\d+$/)?YRe(r)?e&&isNaN(parseInt(e,10))?(g.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(g.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(g.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),!1)}function qH(t){return t.match(jRe)?.[1]}function YH(t){let e=typeof t=="string"?KRe(t):jH(t);if(!(!e||!WRe(e)))return e}var KH="_frozenDsc";function Fm(t,e){ct(t,KH,e)}function Ny(t,e){let n=e.getOptions(),{publicKey:r,host:o}=e.getDsn()||{},s;n.orgId?s=String(n.orgId):o&&(s=qH(o));let i={environment:n.environment||$c,release:n.release,public_key:r,trace_id:t,org_id:s};return e.emit("createDsc",i),i}function Vo(t,e){let n=e.getPropagationContext();return n.dsc||Ny(n.traceId,t)}function tt(t){let e=K();if(!e)return{};let n=Ye(t),r=W(n),o=r.data,s=n.spanContext().traceState,i=s?.get("sentry.sample_rate")??o[Or]??o[gy];function a(f){return(typeof i=="number"||typeof i=="string")&&(f.sample_rate=`${i}`),f}let c=n[KH];if(c)return a(c);let u=s?.get("sentry.dsc"),l=u&&Hs(u);if(l)return a(l);let d=Ny(t.spanContext().traceId,e),p=o[St],_=r.description;return p!=="url"&&_&&(d.transaction=_),vt()&&(d.sampled=String(no(n)),d.sample_rand=s?.get("sentry.sample_rand")??Nr(n).scope?.getPropagationContext().sampleRand.toString()),a(d),e.emit("createDsc",d,n),d}var da=class{constructor(e={}){this._traceId=e.traceId||Rr(),this._spanId=e.spanId||Ln()}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:Bm}}end(e){}setAttribute(e,n){return this}setAttributes(e){return this}setStatus(e){return this}updateName(e){return this}isRecording(){return!1}addEvent(e,n,r){return this}addLink(e){return this}addLinks(e){return this}recordException(e,n){}};function Ir(t,e=100,n=1/0){try{return Cy("",t,e,n)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function vy(t,e=3,n=100*1024){let r=Ir(t,e);return ZRe(r)>n?vy(t,e-1,n):r}function Cy(t,e,n=1/0,r=1/0,o=QRe()){let[s,i]=o;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let a=zRe(t,e);if(!a.startsWith("[object "))return a;if(e.__sentry_skip_normalization__)return e;let c=typeof e.__sentry_override_normalization_depth__=="number"?e.__sentry_override_normalization_depth__:n;if(c===0)return a.replace("object ","");if(s(e))return"[Circular ~]";let u=e;if(u&&typeof u.toJSON=="function")try{let _=u.toJSON();return Cy("",_,c-1,r,o)}catch{}let l=Array.isArray(e)?[]:{},d=0,p=Lm(e);for(let _ in p){if(!Object.prototype.hasOwnProperty.call(p,_))continue;if(d>=r){l[_]="[MaxProperties ~]";break}let f=p[_];l[_]=Cy(_,f,c-1,r,o),d++}return i(e),l}function zRe(t,e){try{if(t==="domain"&&e&&typeof e=="object"&&e._events)return"[Domain]";if(t==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&e===global)return"[Global]";if(typeof window<"u"&&e===window)return"[Window]";if(typeof document<"u"&&e===document)return"[Document]";if(ad(e))return"[VueViewModel]";if(iy(e))return"[SyntheticEvent]";if(typeof e=="number"&&!Number.isFinite(e))return`[${e}]`;if(typeof e=="function")return`[Function: ${id(e)}]`;if(typeof e=="symbol")return`[${String(e)}]`;if(typeof e=="bigint")return`[BigInt: ${String(e)}]`;let n=XRe(e);return/^HTML(\w*)Element$/.test(n)?`[HTMLElement: ${n}]`:`[object ${n}]`}catch(n){return`**non-serializable** (${n})`}}function XRe(t){let e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function JRe(t){return~-encodeURI(t).split(/%..|./).length}function ZRe(t){return JRe(JSON.stringify(t))}function QRe(){let t=new WeakSet;function e(r){return t.has(r)?!0:(t.add(r),!1)}function n(r){t.delete(r)}return[e,n]}function Dn(t,e=[]){return[t,e]}function Py(t,e){let[n,r]=t;return[n,[...r,e]]}function jm(t,e){let n=t[1];for(let r of n){let o=r[0].type;if(e(r,o))return!0}return!1}function Iy(t){let e=Ds(te);return e.encodePolyfill?e.encodePolyfill(t):new TextEncoder().encode(t)}function fd(t){let[e,n]=t,r=JSON.stringify(e);function o(s){typeof r=="string"?r=typeof s=="string"?r+s:[Iy(r),s]:r.push(typeof s=="string"?Iy(s):s)}for(let s of n){let[i,a]=s;if(o(`
157
- ${JSON.stringify(i)}
158
- `),typeof a=="string"||a instanceof Uint8Array)o(a);else{let c;try{c=JSON.stringify(a)}catch{c=JSON.stringify(Ir(a))}o(c)}}return typeof r=="string"?r:eye(r)}function eye(t){let e=t.reduce((o,s)=>o+s.length,0),n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function by(t){return[{type:"span"},t]}function My(t){let e=typeof t.data=="string"?Iy(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}var tye={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",log:"log_item"};function qm(t){return tye[t]}function Ym(t){if(!t?.sdk)return;let{name:e,version:n}=t.sdk;return{name:e,version:n}}function Ly(t,e,n,r){let o=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date().toISOString(),...e&&{sdk:e},...!!n&&r&&{dsn:vr(r)},...o&&{trace:o}}}function nye(t,e){return e&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||e.name,t.sdk.version=t.sdk.version||e.version,t.sdk.integrations=[...t.sdk.integrations||[],...e.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...e.packages||[]]),t}function WH(t,e,n,r){let o=Ym(n),s={sent_at:new Date().toISOString(),...o&&{sdk:o},...!!r&&e&&{dsn:vr(e)}},i="aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()];return Dn(s,[i])}function zH(t,e,n,r){let o=Ym(n),s=t.type&&t.type!=="replay_event"?t.type:"event";nye(t,n?.sdk);let i=Ly(t,o,r,e);return delete t.sdkProcessingMetadata,Dn(i,[[{type:s},t]])}function XH(t,e){function n(l){return!!l.trace_id&&!!l.public_key}let r=tt(t[0]),o=e?.getDsn(),s=e?.getOptions().tunnel,i={sent_at:new Date().toISOString(),...n(r)&&{trace:r},...!!s&&o&&{dsn:vr(o)}},a=e?.getOptions().beforeSendSpan,c=a?l=>{let d=W(l),p=a(d);return p||(_d(),d)}:W,u=[];for(let l of t){let d=c(l);d&&u.push(by(d))}return Dn(i,u)}function md(t){if(!V)return;let{description:e="< unknown name >",op:n="< unknown op >",parent_span_id:r}=W(t),{spanId:o}=t.spanContext(),s=no(t),i=Ye(t),a=i===t,c=`[Tracing] Starting ${s?"sampled":"unsampled"} ${a?"root ":""}span`,u=[`op: ${n}`,`name: ${e}`,`ID: ${o}`];if(r&&u.push(`parent ID: ${r}`),!a){let{op:l,description:d}=W(i);u.push(`root ID: ${i.spanContext().spanId}`),l&&u.push(`root op: ${l}`),d&&u.push(`root description: ${d}`)}g.log(`${c}
159
- ${u.join(`
160
- `)}`)}function Ed(t){if(!V)return;let{description:e="< unknown name >",op:n="< unknown op >"}=W(t),{spanId:r}=t.spanContext(),s=Ye(t)===t,i=`[Tracing] Finishing "${n}" ${s?"root ":""}span "${e}" with ID ${r}`;g.log(i)}function pa(t){if(!t||t.length===0)return;let e={};return t.forEach(n=>{let r=n.attributes||{},o=r[hy],s=r[Ty];typeof o=="string"&&typeof s=="number"&&(e[n.name]={value:s,unit:o})}),e}var JH=1e3,Fc=class{constructor(e={}){this._traceId=e.traceId||Rr(),this._spanId=e.spanId||Ln(),this._startTime=e.startTimestamp||Bs(),this._links=e.links,this._attributes={},this.setAttributes({[ye]:"manual",[se]:e.op,...e.attributes}),this._name=e.name,e.parentSpanId&&(this._parentSpanId=e.parentSpanId),"sampled"in e&&(this._sampled=e.sampled),e.endTimestamp&&(this._endTime=e.endTimestamp),this._events=[],this._isStandaloneSpan=e.isStandalone,this._endTime&&this._onSpanEnded()}addLink(e){return this._links?this._links.push(e):this._links=[e],this}addLinks(e){return this._links?this._links.push(...e):this._links=e,this}recordException(e,n){}spanContext(){let{_spanId:e,_traceId:n,_sampled:r}=this;return{spanId:e,traceId:n,traceFlags:r?Gm:Bm}}setAttribute(e,n){return n===void 0?delete this._attributes[e]:this._attributes[e]=n,this}setAttributes(e){return Object.keys(e).forEach(n=>this.setAttribute(n,e[n])),this}updateStartTime(e){this._startTime=Rn(e)}setStatus(e){return this._status=e,this}updateName(e){return this._name=e,this.setAttribute(St,"custom"),this}end(e){this._endTime||(this._endTime=Rn(e),Ed(this),this._onSpanEnded())}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes[se],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:la(this._status),timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[ye],profile_id:this._attributes[Bc],exclusive_time:this._attributes[Gc],measurements:pa(this._events),is_segment:this._isStandaloneSpan&&Ye(this)===this||void 0,segment_id:this._isStandaloneSpan?Ye(this).spanContext().spanId:void 0,links:ua(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(e,n,r){V&&g.log("[Tracing] Adding an event to span:",e);let o=ZH(n)?n:r||Bs(),s=ZH(n)?{}:n||{},i={name:e,time:Rn(o),attributes:s};return this._events.push(i),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){let e=K();if(e&&e.emit("spanEnd",this),!(this._isStandaloneSpan||this===Ye(this)))return;if(this._isStandaloneSpan){this._sampled?oye(XH([this],e)):(V&&g.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),e&&e.recordDroppedEvent("sample_rate","span"));return}let r=this._convertSpanToTransaction();r&&(Nr(this).scope||ue()).captureEvent(r)}_convertSpanToTransaction(){if(!QH(W(this)))return;this._name||(V&&g.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>");let{scope:e,isolationScope:n}=Nr(this),r=e?.getScopeData().sdkProcessingMetadata?.normalizedRequest;if(this._sampled!==!0)return;let s=$m(this).filter(l=>l!==this&&!rye(l)).map(l=>W(l)).filter(QH),i=this._attributes[St];delete this._attributes[to],s.forEach(l=>{delete l.data[to]});let a={contexts:{trace:HH(this)},spans:s.length>JH?s.sort((l,d)=>l.start_timestamp-d.start_timestamp).slice(0,JH):s,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:e,capturedSpanIsolationScope:n,dynamicSamplingContext:tt(this)},request:r,...i&&{transaction_info:{source:i}}},c=pa(this._events);return c&&Object.keys(c).length&&(V&&g.log("[Measurements] Adding measurements to transaction event",JSON.stringify(c,void 0,2)),a.measurements=c),a}};function ZH(t){return t&&typeof t=="number"||t instanceof Date||Array.isArray(t)}function QH(t){return!!t.start_timestamp&&!!t.timestamp&&!!t.span_id&&!!t.trace_id}function rye(t){return t instanceof Fc&&t.isStandaloneSpan()}function oye(t){let e=K();if(!e)return;let n=t[1];if(!n||n.length===0){e.recordDroppedEvent("before_send","span");return}e.sendEnvelope(t)}function Bo(t,e,n=()=>{}){let r;try{r=t()}catch(o){throw e(o),n(),o}return sye(r,e,n)}function sye(t,e,n){return Ar(t)?t.then(r=>(n(),r),r=>{throw e(r),n(),r}):(n(),t)}function Sd(t,e,n){if(!vt(t))return[!1];let r,o;typeof t.tracesSampler=="function"?(o=t.tracesSampler({...e,inheritOrSampleWith:a=>typeof e.parentSampleRate=="number"?e.parentSampleRate:typeof e.parentSampled=="boolean"?Number(e.parentSampled):a}),r=!0):e.parentSampled!==void 0?o=e.parentSampled:typeof t.tracesSampleRate<"u"&&(o=t.tracesSampleRate,r=!0);let s=xn(o);if(s===void 0)return V&&g.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(o)} of type ${JSON.stringify(typeof o)}.`),[!1];if(!s)return V&&g.log(`[Tracing] Discarding transaction because ${typeof t.tracesSampler=="function"?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0"}`),[!1,s,r];let i=n<s;return i||V&&g.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(o)})`),[i,s,r]}var Km="__SENTRY_SUPPRESS_TRACING__";function gd(t,e){let n=zm();if(n.startSpan)return n.startSpan(t,e);let r=n$(t),{forceTransaction:o,parentSpan:s,scope:i}=t,a=i?.clone();return eo(a,()=>o$(s)(()=>{let u=ue(),l=r$(u,s),p=t.onlyIfParent&&!l?new da:t$({parentSpan:l,spanArguments:r,forceTransaction:o,scope:u});return sa(u,p),Bo(()=>e(p),()=>{let{status:_}=W(p);p.isRecording()&&(!_||_==="ok")&&p.setStatus({code:2,message:"internal_error"})},()=>{p.end()})}))}function Wm(t,e){let n=zm();if(n.startSpanManual)return n.startSpanManual(t,e);let r=n$(t),{forceTransaction:o,parentSpan:s,scope:i}=t,a=i?.clone();return eo(a,()=>o$(s)(()=>{let u=ue(),l=r$(u,s),p=t.onlyIfParent&&!l?new da:t$({parentSpan:l,spanArguments:r,forceTransaction:o,scope:u});return sa(u,p),Bo(()=>e(p,()=>p.end()),()=>{let{status:_}=W(p);p.isRecording()&&(!_||_==="ok")&&p.setStatus({code:2,message:"internal_error"})})}))}function hd(t,e){let n=zm();return n.withActiveSpan?n.withActiveSpan(t,e):eo(r=>(sa(r,t||void 0),e(r)))}function jc(t){let e=zm();return e.suppressTracing?e.suppressTracing(t):eo(n=>{n.setSDKProcessingMetadata({[Km]:!0});let r=t();return n.setSDKProcessingMetadata({[Km]:void 0}),r})}function t$({parentSpan:t,spanArguments:e,forceTransaction:n,scope:r}){if(!vt()){let i=new da;if(n||!t){let a={sampled:"false",sample_rate:"0",transaction:e.name,...tt(i)};Fm(i,a)}return i}let o=Re(),s;if(t&&!n)s=iye(t,r,e),Hc(t,s);else if(t){let i=tt(t),{traceId:a,spanId:c}=t.spanContext(),u=no(t);s=e$({traceId:a,parentSpanId:c,...e},r,u),Fm(s,i)}else{let{traceId:i,dsc:a,parentSpanId:c,sampled:u}={...o.getPropagationContext(),...r.getPropagationContext()};s=e$({traceId:i,parentSpanId:c,...e},r,u),a&&Fm(s,a)}return md(s),ud(s,r,o),s}function n$(t){let n={isStandalone:(t.experimental||{}).standalone,...t};if(t.startTime){let r={...n};return r.startTimestamp=Rn(t.startTime),delete r.startTime,r}return n}function zm(){let t=cn();return yr(t)}function e$(t,e,n){let r=K(),o=r?.getOptions()||{},{name:s=""}=t,i={spanAttributes:{...t.attributes},spanName:s,parentSampled:n};r?.emit("beforeSampling",i,{decision:!1});let a=i.parentSampled??n,c=i.spanAttributes,u=e.getPropagationContext(),[l,d,p]=e.getScopeData().sdkProcessingMetadata[Km]?[!1]:Sd(o,{name:s,parentSampled:a,attributes:c,parentSampleRate:xn(u.dsc?.sample_rate)},u.sampleRand),_=new Fc({...t,attributes:{[St]:"custom",[Or]:d!==void 0&&p?d:void 0,...c},sampled:l});return!l&&r&&(V&&g.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),r.recordDroppedEvent("sample_rate","transaction")),r&&r.emit("spanStart",_),_}function iye(t,e,n){let{spanId:r,traceId:o}=t.spanContext(),s=e.getScopeData().sdkProcessingMetadata[Km]?!1:no(t),i=s?new Fc({...n,parentSpanId:r,traceId:o,sampled:s}):new da({traceId:o});Hc(t,i);let a=K();return a&&(a.emit("spanStart",i),n.endTimestamp&&a.emit("spanEnd",i)),i}function r$(t,e){if(e)return e;if(e===null)return;let n=ia(t);if(!n)return;let r=K();return(r?r.getOptions():{}).parentSpanIsAlwaysRootSpan?Ye(n):n}function o$(t){return t!==void 0?e=>hd(t,e):e=>e()}var xy=0,s$=1,i$=2;function Pr(t){return new oo(e=>{e(t)})}function Xm(t){return new oo((e,n)=>{n(t)})}var oo=class t{constructor(e){this._state=xy,this._handlers=[],this._runExecutor(e)}then(e,n){return new t((r,o)=>{this._handlers.push([!1,s=>{if(!e)r(s);else try{r(e(s))}catch(i){o(i)}},s=>{if(!n)o(s);else try{r(n(s))}catch(i){o(i)}}]),this._executeHandlers()})}catch(e){return this.then(n=>n,e)}finally(e){return new t((n,r)=>{let o,s;return this.then(i=>{s=!1,o=i,e&&e()},i=>{s=!0,o=i,e&&e()}).then(()=>{if(s){r(o);return}n(o)})})}_executeHandlers(){if(this._state===xy)return;let e=this._handlers.slice();this._handlers=[],e.forEach(n=>{n[0]||(this._state===s$&&n[1](this._value),this._state===i$&&n[2](this._value),n[0]=!0)})}_runExecutor(e){let n=(s,i)=>{if(this._state===xy){if(Ar(i)){i.then(r,o);return}this._state=s,this._value=i,this._executeHandlers()}},r=s=>{n(s$,s)},o=s=>{n(i$,s)};try{e(r,o)}catch(s){o(s)}}};function Jm(t,e,n,r=0){return new oo((o,s)=>{let i=t[r];if(e===null||typeof i!="function")o(e);else{let a=i({...e},n);V&&i.id&&a===null&&g.log(`Event processor "${i.id}" dropped event`),Ar(a)?a.then(c=>Jm(t,c,n,r+1).then(o)).then(null,s):Jm(t,a,n,r+1).then(o).then(null,s)}})}function a$(t,e){let{fingerprint:n,span:r,breadcrumbs:o,sdkProcessingMetadata:s}=e;aye(t,e),r&&lye(t,r),dye(t,n),cye(t,o),uye(t,s)}function Dy(t,e){let{extra:n,tags:r,user:o,contexts:s,level:i,sdkProcessingMetadata:a,breadcrumbs:c,fingerprint:u,eventProcessors:l,attachments:d,propagationContext:p,transactionName:_,span:f}=e;Zm(t,"extra",n),Zm(t,"tags",r),Zm(t,"user",o),Zm(t,"contexts",s),t.sdkProcessingMetadata=Gs(t.sdkProcessingMetadata,a,2),i&&(t.level=i),_&&(t.transactionName=_),f&&(t.span=f),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),u.length&&(t.fingerprint=[...t.fingerprint,...u]),l.length&&(t.eventProcessors=[...t.eventProcessors,...l]),d.length&&(t.attachments=[...t.attachments,...d]),t.propagationContext={...t.propagationContext,...p}}function Zm(t,e,n){t[e]=Gs(t[e],n,1)}function aye(t,e){let{extra:n,tags:r,user:o,contexts:s,level:i,transactionName:a}=e;Object.keys(n).length&&(t.extra={...n,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(o).length&&(t.user={...o,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),i&&(t.level=i),a&&t.type!=="transaction"&&(t.transaction=a)}function cye(t,e){let n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}function uye(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function lye(t,e){t.contexts={trace:Fs(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:tt(e),...t.sdkProcessingMetadata};let n=Ye(e),r=W(n).description;r&&!t.transaction&&t.type==="transaction"&&(t.transaction=r)}function dye(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}var Qm,c$,eE;function u$(t){let e=te._sentryDebugIds;if(!e)return{};let n=Object.keys(e);return eE&&n.length===c$||(c$=n.length,eE=n.reduce((r,o)=>{Qm||(Qm={});let s=Qm[o];if(s)r[s[0]]=s[1];else{let i=t(o);for(let a=i.length-1;a>=0;a--){let u=i[a]?.filename,l=e[o];if(u&&l){r[u]=l,Qm[o]=[u,l];break}}}return r},{})),eE}function l$(t,e,n,r,o,s){let{normalizeDepth:i=3,normalizeMaxBreadth:a=1e3}=t,c={...e,event_id:e.event_id||n.event_id||Et(),timestamp:e.timestamp||wo()},u=n.integrations||t.integrations.map(S=>S.name);pye(c,t),mye(c,u),o&&o.emit("applyFrameMetadata",e),e.type===void 0&&_ye(c,t.stackParser);let l=Sye(r,n.captureContext);n.mechanism&&Uc(c,n.mechanism);let d=o?o.getEventProcessors():[],p=Dm().getScopeData();if(s){let S=s.getScopeData();Dy(p,S)}if(l){let S=l.getScopeData();Dy(p,S)}let _=[...n.attachments||[],...p.attachments];_.length&&(n.attachments=_),a$(c,p);let f=[...d,...p.eventProcessors];return Jm(f,c,n).then(S=>(S&&fye(S),typeof i=="number"&&i>0?Eye(S,i,a):S))}function pye(t,e){let{environment:n,release:r,dist:o,maxValueLength:s=250}=e;t.environment=t.environment||n||$c,!t.release&&r&&(t.release=r),!t.dist&&o&&(t.dist=o);let i=t.request;i?.url&&(i.url=Zr(i.url,s))}function _ye(t,e){let n=u$(e);t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(o=>{o.filename&&(o.debug_id=n[o.filename])})})}function fye(t){let e={};if(t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(o=>{o.debug_id&&(o.abs_path?e[o.abs_path]=o.debug_id:o.filename&&(e[o.filename]=o.debug_id),delete o.debug_id)})}),Object.keys(e).length===0)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];let n=t.debug_meta.images;Object.entries(e).forEach(([r,o])=>{n.push({type:"sourcemap",code_file:r,debug_id:o})})}function mye(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function Eye(t,e,n){if(!t)return null;let r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(o=>({...o,...o.data&&{data:Ir(o.data,e,n)}}))},...t.user&&{user:Ir(t.user,e,n)},...t.contexts&&{contexts:Ir(t.contexts,e,n)},...t.extra&&{extra:Ir(t.extra,e,n)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Ir(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map(o=>({...o,...o.data&&{data:Ir(o.data,e,n)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=Ir(t.contexts.flags,3,n)),r}function Sye(t,e){if(!e)return t;let n=t?t.clone():new An;return n.update(e),n}function d$(t){if(t)return gye(t)?{captureContext:t}:Tye(t)?{captureContext:t}:t}function gye(t){return t instanceof An||typeof t=="function"}var hye=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function Tye(t){return Object.keys(t).some(e=>hye.includes(e))}function un(t,e){return ue().captureException(t,d$(e))}function tE(t,e){let n=typeof e=="string"?e:void 0,r=typeof e!="string"?{captureContext:e}:void 0;return ue().captureMessage(t,n,r)}function nE(t,e){return ue().captureEvent(t,e)}function rE(){let t=K();return t?.getOptions().enabled!==!1&&!!t?.getTransport()}function oE(t){let e=Re(),n=ue(),{userAgent:r}=te.navigator||{},o=PH({user:n.getUser()||e.getUser(),...r&&{userAgent:r},...t}),s=e.getSession();return s?.status==="ok"&&ko(s,{status:"exited"}),Td(),e.setSession(o),o}function Td(){let t=Re(),n=ue().getSession()||t.getSession();n&&bH(n),Aye(),t.setSession()}function Aye(){let t=Re(),e=K(),n=t.getSession();n&&e&&e.captureSession(n)}var Rye="7";function yye(t){let e=t.protocol?`${t.protocol}:`:"",n=t.port?`:${t.port}`:"";return`${e}//${t.host}${n}${t.path?`/${t.path}`:""}/api/`}function Oye(t){return`${yye(t)}${t.projectId}/envelope/`}function Nye(t,e){let n={sentry_version:Rye};return t.publicKey&&(n.sentry_key=t.publicKey),e&&(n.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(n).toString()}function p$(t,e,n){return e||`${Oye(t)}?${Nye(t,n)}`}var _$=[];function Cye(t){let e={};return t.forEach(n=>{let{name:r}=n,o=e[r];o&&!o.isDefaultInstance&&n.isDefaultInstance||(e[r]=n)}),Object.values(e)}function Uy(t){let e=t.defaultIntegrations||[],n=t.integrations;e.forEach(o=>{o.isDefaultInstance=!0});let r;if(Array.isArray(n))r=[...e,...n];else if(typeof n=="function"){let o=n(e);r=Array.isArray(o)?o:[o]}else r=e;return Cye(r)}function f$(t,e){let n={};return e.forEach(r=>{r&&ky(t,r,n)}),n}function wy(t,e){for(let n of e)n?.afterAllSetup&&n.afterAllSetup(t)}function ky(t,e,n){if(n[e.name]){V&&g.log(`Integration skipped because it was already installed: ${e.name}`);return}if(n[e.name]=e,_$.indexOf(e.name)===-1&&typeof e.setupOnce=="function"&&(e.setupOnce(),_$.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(t),typeof e.preprocessEvent=="function"){let r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(o,s)=>r(o,s,t))}if(typeof e.processEvent=="function"){let r=e.processEvent.bind(e),o=Object.assign((s,i)=>r(s,i,t),{id:e.name});t.addEventProcessor(o)}V&&g.log(`Integration installed: ${e.name}`)}function m$(t,e,n){let r=[{type:"client_report"},{timestamp:n||wo(),discarded_events:t}];return Dn(e?{dsn:e}:{},[r])}function sE(t){let e=[];t.message&&e.push(t.message);try{let n=t.exception.values[t.exception.values.length-1];n?.value&&(e.push(n.value),n.type&&e.push(`${n.type}: ${n.value}`))}catch{}return e}function E$(t){let{trace_id:e,parent_span_id:n,span_id:r,status:o,origin:s,data:i,op:a}=t.contexts?.trace??{};return{data:i??{},description:t.transaction,op:a,parent_span_id:n,span_id:r??"",start_timestamp:t.start_timestamp??0,status:o,timestamp:t.timestamp,trace_id:e??"",origin:s,profile_id:i?.[Bc],exclusive_time:i?.[Gc],measurements:t.measurements,is_segment:!0}}function S$(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,data:{...t.data,...t.profile_id&&{[Bc]:t.profile_id},...t.exclusive_time&&{[Gc]:t.exclusive_time}}}},measurements:t.measurements}}var g$="Not capturing exception because it's already been captured.",h$="Discarded session because of missing or non-string release",R$=Symbol.for("SentryInternalError"),y$=Symbol.for("SentryDoNotSendEventError");function iE(t){return{message:t,[R$]:!0}}function Vy(t){return{message:t,[y$]:!0}}function T$(t){return!!t&&typeof t=="object"&&R$ in t}function A$(t){return!!t&&typeof t=="object"&&y$ in t}var aE=class{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],e.dsn?this._dsn=YH(e.dsn):V&&g.warn("No DSN provided, client will not send events."),this._dsn){let n=p$(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:n})}}captureException(e,n,r){let o=Et();if(xm(e))return V&&g.log(g$),o;let s={event_id:o,...n};return this._process(this.eventFromException(e,s).then(i=>this._captureEvent(i,s,r))),s.event_id}captureMessage(e,n,r,o){let s={event_id:Et(),...r},i=xc(e)?e:String(e),a=Dc(e)?this.eventFromMessage(i,n,s):this.eventFromException(e,s);return this._process(a.then(c=>this._captureEvent(c,s,o))),s.event_id}captureEvent(e,n,r){let o=Et();if(n?.originalException&&xm(n.originalException))return V&&g.log(g$),o;let s={event_id:o,...n},i=e.sdkProcessingMetadata||{},a=i.capturedSpanScope,c=i.capturedSpanIsolationScope;return this._process(this._captureEvent(e,s,a||r,c)),s.event_id}captureSession(e){this.sendSession(e),ko(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(e){let n=this._transport;return n?(this.emit("flush"),this._isClientDoneProcessing(e).then(r=>n.flush(e).then(o=>r&&o))):Pr(!0)}close(e){return this.flush(e).then(n=>(this.getOptions().enabled=!1,this.emit("close"),n))}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){let n=this._integrations[e.name];ky(this,e,this._integrations),n||wy(this,[e])}sendEvent(e,n={}){this.emit("beforeSendEvent",e,n);let r=zH(e,this._dsn,this._options._metadata,this._options.tunnel);for(let s of n.attachments||[])r=Py(r,My(s));let o=this.sendEnvelope(r);o&&o.then(s=>this.emit("afterSendEvent",e,s),null)}sendSession(e){let{release:n,environment:r=$c}=this._options;if("aggregates"in e){let s=e.attrs||{};if(!s.release&&!n){V&&g.warn(h$);return}s.release=s.release||n,s.environment=s.environment||r,e.attrs=s}else{if(!e.release&&!n){V&&g.warn(h$);return}e.release=e.release||n,e.environment=e.environment||r}this.emit("beforeSendSession",e);let o=WH(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(o)}recordDroppedEvent(e,n,r=1){if(this._options.sendClientReports){let o=`${e}:${n}`;V&&g.log(`Recording outcome: "${o}"${r>1?` (${r} times)`:""}`),this._outcomes[o]=(this._outcomes[o]||0)+r}}on(e,n){let r=this._hooks[e]=this._hooks[e]||[];return r.push(n),()=>{let o=r.indexOf(n);o>-1&&r.splice(o,1)}}emit(e,...n){let r=this._hooks[e];r&&r.forEach(o=>o(...n))}sendEnvelope(e){return this.emit("beforeEnvelope",e),this._isEnabled()&&this._transport?this._transport.send(e).then(null,n=>(V&&g.error("Error while sending envelope:",n),n)):(V&&g.error("Transport disabled"),Pr({}))}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=f$(this,e),wy(this,e)}_updateSessionFromEvent(e,n){let r=n.level==="fatal",o=!1,s=n.exception?.values;if(s){o=!0;for(let c of s)if(c.mechanism?.handled===!1){r=!0;break}}let i=e.status==="ok";(i&&e.errors===0||i&&r)&&(ko(e,{...r&&{status:"crashed"},errors:e.errors||Number(o||r)}),this.captureSession(e))}_isClientDoneProcessing(e){return new oo(n=>{let r=0,o=1,s=setInterval(()=>{this._numProcessing==0?(clearInterval(s),n(!0)):(r+=o,e&&r>=e&&(clearInterval(s),n(!1)))},o)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,n,r,o){let s=this.getOptions(),i=Object.keys(this._integrations);return!n.integrations&&i?.length&&(n.integrations=i),this.emit("preprocessEvent",e,n),e.type||o.setLastEventId(e.event_id||n.event_id),l$(s,e,n,r,this,o).then(a=>{if(a===null)return a;this.emit("postprocessEvent",a,n),a.contexts={trace:Vc(r),...a.contexts};let c=Vo(this,r);return a.sdkProcessingMetadata={dynamicSamplingContext:c,...a.sdkProcessingMetadata},a})}_captureEvent(e,n={},r=ue(),o=Re()){return V&&By(e)&&g.log(`Captured error event \`${sE(e)[0]||"<unknown>"}\``),this._processEvent(e,n,r,o).then(s=>s.event_id,s=>{V&&(A$(s)?g.log(s.message):T$(s)?g.warn(s.message):g.warn(s))})}_processEvent(e,n,r,o){let s=this.getOptions(),{sampleRate:i}=s,a=O$(e),c=By(e),u=e.type||"error",l=`before send for type \`${u}\``,d=typeof i>"u"?void 0:xn(i);if(c&&typeof d=="number"&&Math.random()>d)return this.recordDroppedEvent("sample_rate","error"),Xm(Vy(`Discarding event because it's not included in the random sample (sampling rate = ${i})`));let p=u==="replay_event"?"replay":u;return this._prepareEvent(e,n,r,o).then(_=>{if(_===null)throw this.recordDroppedEvent("event_processor",p),Vy("An event processor returned `null`, will not send event.");if(n.data&&n.data.__sentry__===!0)return _;let E=Iye(this,s,_,n);return vye(E,l)}).then(_=>{if(_===null){if(this.recordDroppedEvent("before_send",p),a){let h=1+(e.spans||[]).length;this.recordDroppedEvent("before_send","span",h)}throw Vy(`${l} returned \`null\`, will not send event.`)}let f=r.getSession()||o.getSession();if(c&&f&&this._updateSessionFromEvent(f,_),a){let S=_.sdkProcessingMetadata?.spanCountBeforeProcessing||0,h=_.spans?_.spans.length:0,R=S-h;R>0&&this.recordDroppedEvent("before_send","span",R)}let E=_.transaction_info;if(a&&E&&_.transaction!==e.transaction){let S="custom";_.transaction_info={...E,source:S}}return this.sendEvent(_,n),_}).then(null,_=>{throw A$(_)||T$(_)?_:(this.captureException(_,{data:{__sentry__:!0},originalException:_}),iE(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
161
- Reason: ${_}`))})}_process(e){this._numProcessing++,e.then(n=>(this._numProcessing--,n),n=>(this._numProcessing--,n))}_clearOutcomes(){let e=this._outcomes;return this._outcomes={},Object.entries(e).map(([n,r])=>{let[o,s]=n.split(":");return{reason:o,category:s,quantity:r}})}_flushOutcomes(){V&&g.log("Flushing outcomes...");let e=this._clearOutcomes();if(e.length===0){V&&g.log("No outcomes to send");return}if(!this._dsn){V&&g.log("No dsn provided, will not send outcomes");return}V&&g.log("Sending outcomes:",e);let n=m$(e,this._options.tunnel&&vr(this._dsn));this.sendEnvelope(n)}};function vye(t,e){let n=`${e} must return \`null\` or a valid event.`;if(Ar(t))return t.then(r=>{if(!Uo(r)&&r!==null)throw iE(n);return r},r=>{throw iE(`${e} rejected with ${r}`)});if(!Uo(t)&&t!==null)throw iE(n);return t}function Iye(t,e,n,r){let{beforeSend:o,beforeSendTransaction:s,beforeSendSpan:i}=e,a=n;if(By(a)&&o)return o(a,r);if(O$(a)){if(i){let c=i(E$(a));if(c?a=Gs(n,S$(c)):_d(),a.spans){let u=[];for(let l of a.spans){let d=i(l);d?u.push(d):(_d(),u.push(l))}a.spans=u}}if(s){if(a.spans){let c=a.spans.length;a.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:c}}return s(a,r)}}return a}function By(t){return t.type===void 0}function O$(t){return t.type==="transaction"}function N$(t,e){return e?eo(e,()=>{let n=ro(),r=n?Fs(n):Vc(e);return[n?tt(n):Vo(t,e),r]}):[void 0,void 0]}function C$(t,e,n,r,o){let s={sent_at:new Date().toISOString()};n?.sdk&&(s.sdk={name:n.sdk.name,version:n.sdk.version}),r&&o&&(s.dsn=vr(o)),e&&(s.trace=e);let i=Pye(t);return Dn(s,[i])}function Pye(t){return[{type:"check_in"},t]}function bye(t){return[{type:"log",item_count:t.length,content_type:"application/vnd.sentry.items.log+json"},{items:t}]}function v$(t,e,n,r){let o={};return e?.sdk&&(o.sdk={name:e.sdk.name,version:e.sdk.version}),n&&r&&(o.dsn=vr(r)),Dn(o,[bye(t)])}function _a(t,e){let n=e??Mye(t)??[];if(n.length===0)return;let r=t.getOptions(),o=v$(n,r._metadata,r.tunnel,t.getDsn());I$().set(t,[]),t.emit("flushLogs"),t.sendEnvelope(o)}function Mye(t){return I$().get(t)}function I$(){return Do("clientToLogBufferMap",()=>new WeakMap)}function P$(t,e){return t(e.stack||"",1)}function Gy(t,e){let n={type:e.name||e.constructor.name,value:e.message},r=P$(t,e);return r.length&&(n.stacktrace={frames:r}),n}function Lye(t){for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];if(n instanceof Error)return n}}function xye(t){if("name"in t&&typeof t.name=="string"){let r=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(r+=` with message '${t.message}'`),r}else if("message"in t&&typeof t.message=="string")return t.message;let e=dy(t);if(ny(t))return`Event \`ErrorEvent\` captured as exception with message \`${t.message}\``;let n=Dye(t);return`${n&&n!=="Object"?`'${n}'`:"Object"} captured as exception with keys: ${e}`}function Dye(t){try{let e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function Uye(t,e,n,r){if(Us(n))return[n,void 0];if(e.synthetic=!0,Uo(n)){let s=t?.getOptions().normalizeDepth,i={__serialized__:vy(n,s)},a=Lye(n);if(a)return[a,i];let c=xye(n),u=r?.syntheticException||new Error(c);return u.message=c,[u,i]}let o=r?.syntheticException||new Error(n);return o.message=`${n}`,[o,void 0]}function b$(t,e,n,r){let s=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[i,a]=Uye(t,s,n,r),c={exception:{values:[Gy(e,i)]}};return a&&(c.extra=a),_y(c,void 0,void 0),Uc(c,s),{...c,event_id:r?.event_id}}function M$(t,e,n="info",r,o){let s={event_id:r?.event_id,level:n};if(o&&r?.syntheticException){let i=P$(t,r.syntheticException);i.length&&(s.exception={values:[{value:e,stacktrace:{frames:i}}]},Uc(s,{synthetic:!0}))}if(xc(e)){let{__sentry_template_string__:i,__sentry_template_values__:a}=e;return s.logentry={message:i,params:a},s}return s.message=e,s}var wye=5e3,Ad=class extends aE{constructor(e){if(FH(),super(e),this._logWeight=0,this._isLogTimerActive=!1,this._options.enableLogs??this._options._experiments?.enableLogs){let r=this;r.on("flushLogs",()=>{r._logWeight=0,clearTimeout(r._logFlushIdleTimeout),r._isLogTimerActive=!1}),r.on("afterCaptureLog",o=>{r._logWeight+=kye(o),r._logWeight>=8e5?_a(r):r._isLogTimerActive||(r._isLogTimerActive=!0,r._logFlushIdleTimeout=setTimeout(()=>{_a(r)},wye))}),r.on("flush",()=>{_a(r)})}}eventFromException(e,n){let r=b$(this,this._options.stackParser,e,n);return r.level="error",Pr(r)}eventFromMessage(e,n="info",r){return Pr(M$(this._options.stackParser,e,n,r,this._options.attachStacktrace))}captureException(e,n,r){return L$(n),super.captureException(e,n,r)}captureEvent(e,n,r){return!e.type&&e.exception?.values&&e.exception.values.length>0&&L$(n),super.captureEvent(e,n,r)}captureCheckIn(e,n,r){let o="checkInId"in e&&e.checkInId?e.checkInId:Et();if(!this._isEnabled())return V&&g.warn("SDK not enabled, will not capture check-in."),o;let s=this.getOptions(),{release:i,environment:a,tunnel:c}=s,u={check_in_id:o,monitor_slug:e.monitorSlug,status:e.status,release:i,environment:a};"duration"in e&&(u.duration=e.duration),n&&(u.monitor_config={schedule:n.schedule,checkin_margin:n.checkinMargin,max_runtime:n.maxRuntime,timezone:n.timezone,failure_issue_threshold:n.failureIssueThreshold,recovery_threshold:n.recoveryThreshold});let[l,d]=N$(this,r);d&&(u.contexts={trace:d});let p=C$(u,l,this.getSdkMetadata(),c,this.getDsn());return V&&g.log("Sending checkin:",e.monitorSlug,e.status),this.sendEnvelope(p),o}_prepareEvent(e,n,r,o){return this._options.platform&&(e.platform=e.platform||this._options.platform),this._options.runtime&&(e.contexts={...e.contexts,runtime:e.contexts?.runtime||this._options.runtime}),this._options.serverName&&(e.server_name=e.server_name||this._options.serverName),super._prepareEvent(e,n,r,o)}};function L$(t){let e=Re().getScopeData().sdkProcessingMetadata.requestSession;if(e){let n=t?.mechanism?.handled??!0;n&&e.status!=="crashed"?e.status="errored":n||(e.status="crashed")}}function kye(t){let e=0;return t.message&&(e+=t.message.length*2),t.attributes&&Object.values(t.attributes).forEach(n=>{Array.isArray(n)?e+=n.length*x$(n[0]):Dc(n)?e+=x$(n):e+=100}),e}function x$(t){return typeof t=="string"?t.length*2:typeof t=="number"?8:typeof t=="boolean"?4:0}var Hy=Symbol.for("SentryBufferFullError");function D$(t){let e=[];function n(){return t===void 0||e.length<t}function r(i){return e.splice(e.indexOf(i),1)[0]||Promise.resolve(void 0)}function o(i){if(!n())return Xm(Hy);let a=i();return e.indexOf(a)===-1&&e.push(a),a.then(()=>r(a)).then(null,()=>r(a).then(null,()=>{})),a}function s(i){return new oo((a,c)=>{let u=e.length;if(!u)return a(!0);let l=setTimeout(()=>{i&&i>0&&a(!1)},i);e.forEach(d=>{Pr(d).then(()=>{--u||(clearTimeout(l),a(!0))},c)})})}return{$:e,add:o,drain:s}}function Vye(t,e=Date.now()){let n=parseInt(`${t}`,10);if(!isNaN(n))return n*1e3;let r=Date.parse(`${t}`);return isNaN(r)?6e4:r-e}function Bye(t,e){return t[e]||t.all||0}function U$(t,e,n=Date.now()){return Bye(t,e)>n}function w$(t,{statusCode:e,headers:n},r=Date.now()){let o={...t},s=n?.["x-sentry-rate-limits"],i=n?.["retry-after"];if(s)for(let a of s.trim().split(",")){let[c,u,,,l]=a.split(":",5),d=parseInt(c,10),p=(isNaN(d)?60:d)*1e3;if(!u)o.all=r+p;else for(let _ of u.split(";"))_==="metric_bucket"?(!l||l.split(";").includes("custom"))&&(o[_]=r+p):o[_]=r+p}else i?o.all=r+Vye(i,r):e===429&&(o.all=r+60*1e3);return o}var Gye=64;function Rd(t,e,n=D$(t.bufferSize||Gye)){let r={},o=i=>n.drain(i);function s(i){let a=[];if(jm(i,(d,p)=>{let _=qm(p);U$(r,_)?t.recordDroppedEvent("ratelimit_backoff",_):a.push(d)}),a.length===0)return Pr({});let c=Dn(i[0],a),u=d=>{jm(c,(p,_)=>{t.recordDroppedEvent(d,qm(_))})},l=()=>e({body:fd(c)}).then(d=>(d.statusCode!==void 0&&(d.statusCode<200||d.statusCode>=300)&&V&&g.warn(`Sentry responded with status code ${d.statusCode} to sent event.`),r=w$(r,d),d),d=>{throw u("network_error"),V&&g.error("Encountered error running transport request:",d),d});return n.add(l).then(d=>d,d=>{if(d===Hy)return V&&g.error("Skipped sending event because buffer is full."),u("queue_overflow"),Pr({});throw d})}return{send:s,flush:o}}function fa(t,e,n=[e],r="npm"){let o=t._metadata||{};o.sdk||(o.sdk={name:`sentry.javascript.${e}`,packages:n.map(s=>({name:`${r}:@sentry/${s}`,version:Pe})),version:Pe}),t._metadata=o}function qc(t={}){let e=t.client||K();if(!rE()||!e)return{};let n=cn(),r=yr(n);if(r.getTraceData)return r.getTraceData(t);let o=t.scope||ue(),s=t.span||ro(),i=s?Hm(s):Hye(o),a=s?tt(s):Vo(e,o),c=aa(a);return km.test(i)?{"sentry-trace":i,baggage:c}:(g.warn("Invalid sentry-trace data. Cannot generate trace data"),{})}function Hye(t){let{traceId:e,sampled:n,propagationSpanId:r}=t.getPropagationContext();return $s(e,r,n)}function $y(t,e,n){let r,o,s,i=n?.maxWait?Math.max(n.maxWait,e):0,a=n?.setTimeoutImpl||setTimeout;function c(){return u(),r=t(),r}function u(){o!==void 0&&clearTimeout(o),s!==void 0&&clearTimeout(s),o=s=void 0}function l(){return o!==void 0||s!==void 0?c():r}function d(){return o&&clearTimeout(o),o=a(c,e),i&&s===void 0&&(s=a(c,i)),r}return d.cancel=u,d.flush=l,d}function k$(t){let e=Object.create(null);try{Object.entries(t).forEach(([n,r])=>{typeof r=="string"&&(e[n]=r)})}catch{}return e}function cE(t){let e=t.headers||{},r=(typeof e["x-forwarded-host"]=="string"?e["x-forwarded-host"]:void 0)||(typeof e.host=="string"?e.host:void 0),s=(typeof e["x-forwarded-proto"]=="string"?e["x-forwarded-proto"]:void 0)||t.protocol||(t.socket?.encrypted?"https":"http"),i=t.url||"",a=$ye({url:i,host:r,protocol:s}),c=t.body||void 0,u=t.cookies;return{url:a,method:t.method,query_string:V$(i),headers:k$(e),cookies:u,data:c}}function $ye({url:t,protocol:e,host:n}){if(t?.startsWith("http"))return t;if(t&&n)return`${e}://${n}${t}`}function V$(t){if(t)try{let e=new URL(t,"http://s.io").search.slice(1);return e.length?e:void 0}catch{return}}var Fye=100;function Un(t,e){let n=K(),r=Re();if(!n)return;let{beforeBreadcrumb:o=null,maxBreadcrumbs:s=Fye}=n.getOptions();if(s<=0)return;let a={timestamp:wo(),...t},c=o?qe(()=>o(a,e)):a;c!==null&&(n.emit&&n.emit("beforeAddBreadcrumb",c,e),r.addBreadcrumb(c,s))}var B$,jye="FunctionToString",G$=new WeakMap,qye=(()=>({name:jye,setupOnce(){B$=Function.prototype.toString;try{Function.prototype.toString=function(...t){let e=ly(this),n=G$.has(K())&&e!==void 0?e:this;return B$.apply(n,t)}}catch{}},setup(t){G$.set(t,!0)}})),uE=qye;var Yye=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/,/^Java exception was raised during method invocation$/],Kye="EventFilters",Fy=(t={})=>{let e;return{name:Kye,setup(n){let r=n.getOptions();e=H$(t,r)},processEvent(n,r,o){if(!e){let s=o.getOptions();e=H$(t,s)}return Wye(n,e)?null:n}}},dE=((t={})=>({...Fy(t),name:"InboundFilters"}));function H$(t={},e={}){return{allowUrls:[...t.allowUrls||[],...e.allowUrls||[]],denyUrls:[...t.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...t.ignoreErrors||[],...e.ignoreErrors||[],...t.disableErrorDefaults?[]:Yye],ignoreTransactions:[...t.ignoreTransactions||[],...e.ignoreTransactions||[]]}}function Wye(t,e){if(t.type){if(t.type==="transaction"&&Xye(t,e.ignoreTransactions))return V&&g.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.
162
- Event: ${Vs(t)}`),!0}else{if(zye(t,e.ignoreErrors))return V&&g.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
163
- Event: ${Vs(t)}`),!0;if(eOe(t))return V&&g.warn(`Event dropped due to not having an error message, error type or stacktrace.
164
- Event: ${Vs(t)}`),!0;if(Jye(t,e.denyUrls))return V&&g.warn(`Event dropped due to being matched by \`denyUrls\` option.
165
- Event: ${Vs(t)}.
166
- Url: ${lE(t)}`),!0;if(!Zye(t,e.allowUrls))return V&&g.warn(`Event dropped due to not being matched by \`allowUrls\` option.
167
- Event: ${Vs(t)}.
168
- Url: ${lE(t)}`),!0}return!1}function zye(t,e){return e?.length?sE(t).some(n=>ks(n,e)):!1}function Xye(t,e){if(!e?.length)return!1;let n=t.transaction;return n?ks(n,e):!1}function Jye(t,e){if(!e?.length)return!1;let n=lE(t);return n?ks(n,e):!1}function Zye(t,e){if(!e?.length)return!0;let n=lE(t);return n?ks(n,e):!0}function Qye(t=[]){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n&&n.filename!=="<anonymous>"&&n.filename!=="[native code]")return n.filename||null}return null}function lE(t){try{let n=[...t.exception?.values??[]].reverse().find(r=>r.mechanism?.parent_id===void 0&&r.stacktrace?.frames?.length)?.stacktrace?.frames;return n?Qye(n):null}catch{return V&&g.error(`Cannot extract url for event ${Vs(t)}`),null}}function eOe(t){return t.exception?.values?.length?!t.message&&!t.exception.values.some(e=>e.stacktrace||e.type&&e.type!=="Error"||e.value):!1}function j$(t,e,n,r,o,s){if(!o.exception?.values||!s||!Jr(s.originalException,Error))return;let i=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;i&&(o.exception.values=jy(t,e,r,s.originalException,n,o.exception.values,i,0))}function jy(t,e,n,r,o,s,i,a){if(s.length>=n+1)return s;let c=[...s];if(Jr(r[o],Error)){$$(i,a);let u=t(e,r[o]),l=c.length;F$(u,o,l,a),c=jy(t,e,n,r[o],o,[u,...c],u,l)}return Array.isArray(r.errors)&&r.errors.forEach((u,l)=>{if(Jr(u,Error)){$$(i,a);let d=t(e,u),p=c.length;F$(d,`errors[${l}]`,p,a),c=jy(t,e,n,u,o,[d,...c],d,p)}}),c}function $$(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism={...t.mechanism,...t.type==="AggregateError"&&{is_exception_group:!0},exception_id:e}}function F$(t,e,n,r){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism={...t.mechanism,type:"chained",source:e,exception_id:n,parent_id:r}}var tOe="cause",nOe=5,rOe="LinkedErrors",oOe=((t={})=>{let e=t.limit||nOe,n=t.key||tOe;return{name:rOe,preprocessEvent(r,o,s){let i=s.getOptions();j$(Gy,i.stackParser,n,e,r,o)}}}),pE=oOe;function q$(t){let e={},n=0;for(;n<t.length;){let r=t.indexOf("=",n);if(r===-1)break;let o=t.indexOf(";",n);if(o===-1)o=t.length;else if(o<r){n=t.lastIndexOf(";",r-1)+1;continue}let s=t.slice(n,r).trim();if(e[s]===void 0){let i=t.slice(r+1,o).trim();i.charCodeAt(0)===34&&(i=i.slice(1,-1));try{e[s]=i.indexOf("%")!==-1?decodeURIComponent(i):i}catch{e[s]=i}}n=o+1}return e}var qy=["X-Client-IP","X-Forwarded-For","Fly-Client-IP","CF-Connecting-IP","Fastly-Client-Ip","True-Client-Ip","X-Real-IP","X-Cluster-Client-IP","X-Forwarded","Forwarded-For","Forwarded","X-Vercel-Forwarded-For"];function Y$(t){return qy.map(o=>{let s=t[o],i=Array.isArray(s)?s.join(";"):s;return o==="Forwarded"?sOe(i):i?.split(",").map(a=>a.trim())}).reduce((o,s)=>s?o.concat(s):o,[]).find(o=>o!==null&&iOe(o))||null}function sOe(t){if(!t)return null;for(let e of t.split(";"))if(e.startsWith("for="))return e.slice(4);return null}function iOe(t){return/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/.test(t)}var aOe={cookies:!0,data:!0,headers:!0,query_string:!0,url:!0},cOe="RequestData",uOe=((t={})=>{let e={...aOe,...t.include};return{name:cOe,processEvent(n,r,o){let{sdkProcessingMetadata:s={}}=n,{normalizedRequest:i,ipAddress:a}=s,c={...e,ip:e.ip??o.getOptions().sendDefaultPii};return i&&lOe(n,i,{ipAddress:a},c),n}}}),_E=uOe;function lOe(t,e,n,r){if(t.request={...t.request,...dOe(e,r)},r.ip){let o=e.headers&&Y$(e.headers)||n.ipAddress;o&&(t.user={...t.user,ip_address:o})}}function dOe(t,e){let n={},r={...t.headers};if(e.headers&&(n.headers=r,e.cookies||delete r.cookie,e.ip||qy.forEach(o=>{delete r[o]})),n.method=t.method,e.url&&(n.url=t.url),e.cookies){let o=t.cookies||(r?.cookie?q$(r.cookie):void 0);n.cookies=o||{}}return e.query_string&&(n.query_string=t.query_string),e.data&&(n.data=t.data),n}function K$(t){let e="console";bc(e,t),Mc(e,pOe)}function pOe(){"console"in te&&sd.forEach(function(t){t in te.console&&uy(te.console,t,function(e){return Pc[t]=e,function(...n){Lc("console",{args:n,level:t}),Pc[t]?.apply(te.console,n)}})})}function W$(t){return t==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(t)?t:"log"}var _Oe=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function fOe(t){let e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,n=_Oe.exec(e);return n?n.slice(1):[]}function Yy(t){let e=fOe(t),n=e[0]||"",r=e[1];return!n&&!r?".":(r&&(r=r.slice(0,r.length-1)),n+r)}var mOe="Console",fE=(t={})=>{let e=new Set(t.levels||sd);return{name:mOe,setup(n){K$(({args:r,level:o})=>{K()!==n||!e.has(o)||EOe(o,r)})}}};function EOe(t,e){let n={category:"console",data:{arguments:e,logger:"console"},level:W$(t),message:z$(e)};if(t==="assert")if(e[0]===!1){let r=e.slice(1);n.message=r.length>0?`Assertion failed: ${z$(r)}`:"Assertion failed",n.data.arguments=r}else return;Un(n,{input:e,level:t})}function z$(t){return"util"in te&&typeof te.util.format=="function"?te.util.format(...t):cy(t," ")}function js(t){if(!t)return{};let e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};let n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}function Yc(t){return t.split(/[?#]/,1)[0]}function qs(t){let{protocol:e,host:n,path:r}=t,o=n?.replace(/^.*@/,"[filtered]:[filtered]@").replace(/(:80)$/,"").replace(/(:443)$/,"")||"";return`${e?`${e}://`:""}${o}${r}`}var Ky="ai.prompt",X$="ai.response.object",J$="ai.response.text",Z$="ai.response.toolCalls",Q$="ai.prompt.messages",eF="ai.prompt.tools",so="ai.model.id",tF="ai.model.provider",nF="ai.response.providerMetadata",rF="ai.telemetry.functionId",oF="ai.usage.completionTokens",sF="ai.usage.promptTokens",Wy="gen_ai.response.model",mE="gen_ai.usage.input_tokens",EE="gen_ai.usage.output_tokens",zy="ai.toolCall.name",Xy="ai.toolCall.id",iF="ai.toolCall.args",aF="ai.toolCall.result";function cF(t,e){t.setAttribute(ye,e)}function SOe(t){let{data:e,description:n}=W(t);if(!n)return;if(e[zy]&&e[Xy]&&n==="ai.toolCall"){TOe(t,e);return}let r=e[so],o=e[tF];typeof r!="string"||typeof o!="string"||!r||!o||AOe(t,n,e)}function gOe(t){if(t.type==="transaction"&&t.spans)for(let e of t.spans)hOe(e);return t}function hOe(t){let{data:e,origin:n}=t;if(n==="auto.vercelai.otel"){nr(e,oF,EE),nr(e,sF,mE),typeof e[EE]=="number"&&typeof e[mE]=="number"&&(e["gen_ai.usage.total_tokens"]=e[EE]+e[mE]),nr(e,Q$,"gen_ai.request.messages"),nr(e,J$,"gen_ai.response.text"),nr(e,Z$,"gen_ai.response.tool_calls"),nr(e,X$,"gen_ai.response.object"),nr(e,eF,"gen_ai.request.available_tools"),nr(e,iF,"gen_ai.tool.input"),nr(e,aF,"gen_ai.tool.output"),ROe(e);for(let r of Object.keys(e))r.startsWith("ai.")&&nr(e,r,`vercel.${r}`)}}function nr(t,e,n){t[e]!=null&&(t[n]=t[e],delete t[e])}function TOe(t,e){cF(t,"auto.vercelai.otel"),t.setAttribute(se,"gen_ai.execute_tool"),nr(e,zy,"gen_ai.tool.name"),nr(e,Xy,"gen_ai.tool.call.id"),e["gen_ai.tool.type"]||t.setAttribute("gen_ai.tool.type","function");let n=e["gen_ai.tool.name"];n&&t.updateName(`execute_tool ${n}`)}function AOe(t,e,n){cF(t,"auto.vercelai.otel");let r=e.replace("ai.","");t.setAttribute("ai.pipeline.name",r),t.updateName(r);let o=n[rF];if(o&&typeof o=="string"&&e.split(".").length-1===1&&(t.updateName(`${r} ${o}`),t.setAttribute("gen_ai.function_id",o)),n[Ky]&&t.setAttribute("gen_ai.prompt",n[Ky]),n[so]&&!n[Wy]&&t.setAttribute(Wy,n[so]),t.setAttribute("ai.streaming",e.includes("stream")),e==="ai.generateText"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.generateText.doGenerate"){t.setAttribute(se,"gen_ai.generate_text"),t.updateName(`generate_text ${n[so]}`);return}if(e==="ai.streamText"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.streamText.doStream"){t.setAttribute(se,"gen_ai.stream_text"),t.updateName(`stream_text ${n[so]}`);return}if(e==="ai.generateObject"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.generateObject.doGenerate"){t.setAttribute(se,"gen_ai.generate_object"),t.updateName(`generate_object ${n[so]}`);return}if(e==="ai.streamObject"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.streamObject.doStream"){t.setAttribute(se,"gen_ai.stream_object"),t.updateName(`stream_object ${n[so]}`);return}if(e==="ai.embed"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.embed.doEmbed"){t.setAttribute(se,"gen_ai.embed"),t.updateName(`embed ${n[so]}`);return}if(e==="ai.embedMany"){t.setAttribute(se,"gen_ai.invoke_agent");return}if(e==="ai.embedMany.doEmbed"){t.setAttribute(se,"gen_ai.embed_many"),t.updateName(`embed_many ${n[so]}`);return}if(e.startsWith("ai.stream")){t.setAttribute(se,"ai.run");return}}function SE(t){t.on("spanStart",SOe),t.addEventProcessor(Object.assign(gOe,{id:"VercelAiEventProcessor"}))}function ROe(t){let e=t[nF];if(e)try{let n=JSON.parse(e);n.openai&&(br(t,"gen_ai.usage.input_tokens.cached",n.openai.cachedPromptTokens),br(t,"gen_ai.usage.output_tokens.reasoning",n.openai.reasoningTokens),br(t,"gen_ai.usage.output_tokens.prediction_accepted",n.openai.acceptedPredictionTokens),br(t,"gen_ai.usage.output_tokens.prediction_rejected",n.openai.rejectedPredictionTokens),br(t,"gen_ai.conversation.id",n.openai.responseId)),n.anthropic&&(br(t,"gen_ai.usage.input_tokens.cached",n.anthropic.cacheReadInputTokens),br(t,"gen_ai.usage.input_tokens.cache_write",n.anthropic.cacheCreationInputTokens)),n.bedrock?.usage&&(br(t,"gen_ai.usage.input_tokens.cached",n.bedrock.usage.cacheReadInputTokens),br(t,"gen_ai.usage.input_tokens.cache_write",n.bedrock.usage.cacheWriteInputTokens)),n.deepseek&&(br(t,"gen_ai.usage.input_tokens.cached",n.deepseek.promptCacheHitTokens),br(t,"gen_ai.usage.input_tokens.cache_miss",n.deepseek.promptCacheMissTokens))}catch{}}function br(t,e,n){n!=null&&(t[e]=n)}var uF="gen_ai.system",gE="gen_ai.request.model",lF="gen_ai.request.temperature",dF="gen_ai.request.frequency_penalty",pF="gen_ai.request.presence_penalty",_F="gen_ai.request.top_p",Jy="gen_ai.response.finish_reasons",fF="gen_ai.response.model",mF="gen_ai.response.id",EF="gen_ai.usage.input_tokens",SF="gen_ai.usage.output_tokens",gF="gen_ai.usage.total_tokens",hF="gen_ai.operation.name",Zy="gen_ai.request.messages",Qy="gen_ai.response.text",TF="openai.response.id",AF="openai.response.model",RF="openai.response.timestamp",yF="openai.usage.completion_tokens",OF="openai.usage.prompt_tokens",eO={CHAT:"chat"};var Ys="OpenAI",NF=["responses.create","chat.completions.create"];function hE(t){return t.includes("chat.completions")?eO.CHAT:t.includes("responses")?eO.CHAT:t.split(".").pop()||"unknown"}function CF(t){return`gen_ai.${hE(t)}`}function vF(t){return NF.includes(t)}function IF(t,e){return t?`${t}.${e}`:e}function PF(t){return t!==null&&typeof t=="object"&&"object"in t&&t.object==="chat.completion"}function bF(t){return t!==null&&typeof t=="object"&&"object"in t&&t.object==="response"}function yOe(t,e){let n={[uF]:"openai",[hF]:hE(e)};if(t.length>0&&typeof t[0]=="object"&&t[0]!==null){let r=t[0];n[gE]=r.model??"unknown","temperature"in r&&(n[lF]=r.temperature),"top_p"in r&&(n[_F]=r.top_p),"frequency_penalty"in r&&(n[dF]=r.frequency_penalty),"presence_penalty"in r&&(n[pF]=r.presence_penalty)}else n[gE]="unknown";return n}function MF(t,e,n,r){e!==void 0&&t.setAttributes({[OF]:e,[EF]:e}),n!==void 0&&t.setAttributes({[yF]:n,[SF]:n}),r!==void 0&&t.setAttributes({[gF]:r})}function LF(t,e,n,r){e&&t.setAttributes({[TF]:e,[mF]:e}),n&&t.setAttributes({[AF]:n,[fF]:n}),r&&t.setAttributes({[RF]:new Date(r*1e3).toISOString()})}function OOe(t,e){if(LF(t,e.id,e.model,e.created),e.usage&&MF(t,e.usage.prompt_tokens,e.usage.completion_tokens,e.usage.total_tokens),Array.isArray(e.choices)){let n=e.choices.map(r=>r.finish_reason).filter(r=>r!==null);n.length>0&&t.setAttributes({[Jy]:JSON.stringify(n)})}}function NOe(t,e){LF(t,e.id,e.model,e.created_at),e.status&&t.setAttributes({[Jy]:JSON.stringify([e.status])}),e.usage&&MF(t,e.usage.input_tokens,e.usage.output_tokens,e.usage.total_tokens)}function COe(t,e,n){if(!e||typeof e!="object")return;let r=e;if(PF(r)){if(OOe(t,r),n&&r.choices?.length){let o=r.choices.map(s=>s.message?.content||"");t.setAttributes({[Qy]:JSON.stringify(o)})}}else bF(r)&&(NOe(t,r),n&&r.output_text&&t.setAttributes({[Qy]:r.output_text}))}function vOe(t,e){"messages"in e&&t.setAttributes({[Zy]:JSON.stringify(e.messages)}),"input"in e&&t.setAttributes({[Zy]:JSON.stringify(e.input)})}function IOe(){let e=ue().getClient(),n=e?.getIntegrationByName(Ys),r=n?!!e?.getOptions().sendDefaultPii:!1;return{recordInputs:n?.options?.recordInputs??r,recordOutputs:n?.options?.recordOutputs??r}}function POe(t,e,n,r){return async function(...s){let i=r||IOe(),a=yOe(s,e),c=a[gE]||"unknown",u=hE(e);return gd({name:`${u} ${c}`,op:CF(e),attributes:a},async l=>{try{i.recordInputs&&s[0]&&typeof s[0]=="object"&&vOe(l,s[0]);let d=await t.apply(n,s);return COe(l,d,i.recordOutputs),d}catch(d){throw un(d),d}})}}function xF(t,e="",n){return new Proxy(t,{get(r,o){let s=r[o],i=IF(e,String(o));return typeof s=="function"&&vF(i)?POe(s,i,r,n):typeof s=="function"?s.bind(r):s&&typeof s=="object"?xF(s,i,n):s}})}function tO(t,e){return xF(t,"",e)}function yd(t){if(t!==void 0)return t>=400&&t<500?"warning":t>=500?"error":void 0}function UF(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function wF(t){let e=/^\s*[-]{4,}$/,n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return r=>{let o=r.match(n);if(o){let s,i,a,c,u;if(o[1]){a=o[1];let p=a.lastIndexOf(".");if(a[p-1]==="."&&p--,p>0){s=a.slice(0,p),i=a.slice(p+1);let _=s.indexOf(".Module");_>0&&(a=a.slice(_+1),s=s.slice(0,_))}c=void 0}i&&(c=s,u=i),i==="<anonymous>"&&(u=void 0,a=void 0),a===void 0&&(u=u||"?",a=c?`${c}.${u}`:u);let l=o[2]?.startsWith("file://")?o[2].slice(7):o[2],d=o[5]==="native";return l?.match(/\/[A-Z]:/)&&(l=l.slice(1)),!l&&o[5]&&!d&&(l=o[5]),{filename:l?decodeURI(l):void 0,module:t?t(l):void 0,function:a,lineno:DF(o[3]),colno:DF(o[4]),in_app:UF(l||"",d)}}if(r.match(e))return{filename:r}}}function nO(t){return[90,wF(t)]}function DF(t){return parseInt(t||"",10)||void 0}var yn=class{constructor(e){this._maxSize=e,this._cache=new Map}get size(){return this._cache.size}get(e){let n=this._cache.get(e);if(n!==void 0)return this._cache.delete(e),this._cache.set(e,n),n}set(e,n){this._cache.size>=this._maxSize&&this._cache.delete(this._cache.keys().next().value),this._cache.set(e,n)}remove(e){let n=this._cache.get(e);return n&&this._cache.delete(e),n}clear(){this._cache.clear()}keys(){return Array.from(this._cache.keys())}values(){let e=[];return this._cache.forEach(n=>e.push(n)),e}};var rO=v(fe(),1),Od={};function q(t,e,n){return n?eNe(t,e,n):QOe(t,e)}function QOe(t,e){return Object.assign(n=>{let r=Od[t];if(r)return n&&r.setConfig(n),r;let o=e(n);return Od[t]=o,(0,rO.registerInstrumentations)({instrumentations:[o]}),o},{id:t})}function eNe(t,e,n){return Object.assign(r=>{let o=n(r),s=Od[t];if(s)return s.setConfig(o),s;let i=new e(o);return Od[t]=i,(0,rO.registerInstrumentations)({instrumentations:[i]}),i},{id:t})}function Nd(t){let e=!1,n=[];if(!tNe(t))e=!0;else{let o=t._wrap;t._wrap=(...s)=>(e=!0,n.forEach(i=>i()),n=[],o(...s))}return o=>{e?o():n.push(o)}}function tNe(t){return typeof t._wrap=="function"}var co=require("node:diagnostics_channel");x();var b3=v(Se(),1),kd=v(fe(),1);ve();x();x();var or=v(Se(),1),Ws=v(EN(),1),NN="sentry.parentIsRemote",du="sentry.graphql.operation";function CN(t){if("parentSpanId"in t)return t.parentSpanId;if("parentSpanContext"in t)return t.parentSpanContext?.spanId}function vN(t){let e=t;return!!e.attributes&&typeof e.attributes=="object"}function fwe(t){return typeof t.kind=="number"}function mwe(t){return!!t.status}function s3(t){return!!t.name}function Ewe(t){if(!vN(t))return{};let e=t.attributes[Wc]||t.attributes[Kc],n={url:e,"http.method":t.attributes[ma]||t.attributes[Cd]};!n["http.method"]&&n.url&&(n["http.method"]="GET");try{if(typeof e=="string"){let r=js(e);n.url=qs(r),r.search&&(n["http.query"]=r.search),r.hash&&(n["http.fragment"]=r.hash)}}catch{}return n}function Swe(t){return fwe(t)?t.kind:Dt.INTERNAL}var SN="sentry-trace",gN="baggage",IN="sentry.dsc",PN="sentry.sampled_not_recording",i3="sentry.url",gwe="sentry.sample_rand",hwe="sentry.sample_rate",a3=gr("sentry_scopes"),hN=gr("sentry_fork_isolation_scope"),TN=gr("sentry_fork_set_scope"),AN=gr("sentry_fork_set_isolation_scope"),c3="_scopeContext";function pu(t){return t.getValue(a3)}function u3(t,e){return t.setValue(a3,e)}function Twe(t,e){ct(t,c3,e)}function Dd(t){return t[c3]}function lu(t){let{traceFlags:e,traceState:n}=t,r=n?n.get(PN)==="1":!1;if(e===Kn.SAMPLED)return!0;if(r)return!1;let o=n?n.get(IN):void 0,s=o?Hs(o):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function l3(t,e,n){let r=e[ma]||e[Cd];if(r)return Rwe({attributes:e,name:t,kind:n},r);let o=e[sO],s=typeof e[se]=="string"&&e[se].startsWith("cache.");if(o&&!s)return Awe({attributes:e,name:t});let i=e[St]==="custom"?"custom":"route";if(e[lO])return{...xd(t,e,"route"),op:"rpc"};if(e[uO])return{...xd(t,e,i),op:"message"};let u=e[aO];return u?{...xd(t,e,i),op:u.toString()}:{op:void 0,description:t,source:"custom"}}function d3(t){let e=vN(t)?t.attributes:{},n=s3(t)?t.name:"<unknown>",r=Swe(t);return l3(n,e,r)}function Awe({attributes:t,name:e}){let n=t[to];if(typeof n=="string")return{op:"db",description:n,source:t[St]||"custom"};if(t[St]==="custom")return{op:"db",description:e,source:"custom"};let r=t[iO];return{op:"db",description:r?r.toString():e,source:"task"}}function Rwe({name:t,kind:e,attributes:n},r){let o=["http"];switch(e){case Dt.CLIENT:o.push("client");break;case Dt.SERVER:o.push("server");break}n["sentry.http.prefetch"]&&o.push("prefetch");let{urlPath:s,url:i,query:a,fragment:c,hasRoute:u}=Owe(n,e);if(!s)return{...xd(t,n),op:o.join(".")};let l=n[du],d=`${r} ${s}`,p=l?`${d} (${ywe(l)})`:d,_=u||s==="/"?"route":"url",f={};i&&(f.url=i),a&&(f["http.query"]=a),c&&(f["http.fragment"]=c);let E=e===Dt.CLIENT||e===Dt.SERVER,h=!`${n[ye]||"manual"}`.startsWith("auto"),R=n[St]==="custom",A=n[to],O=!R&&A==null&&(E||!h),{description:y,source:M}=O?{description:p,source:_}:xd(t,n);return{op:o.join("."),description:y,source:M,data:f}}function ywe(t){if(Array.isArray(t)){let e=t.slice().sort();return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")}, +${e.length-5}`}return`${t}`}function Owe(t,e){let n=t[cO],r=t[Kc]||t[Wc],o=t[io],s=typeof r=="string"?js(r):void 0,i=s?qs(s):void 0,a=s?.search||void 0,c=s?.hash||void 0;return typeof o=="string"?{urlPath:o,url:i,query:a,fragment:c,hasRoute:!0}:e===Dt.SERVER&&typeof n=="string"?{urlPath:Yc(n),url:i,query:a,fragment:c,hasRoute:!1}:s?{urlPath:i,url:i,query:a,fragment:c,hasRoute:!1}:typeof n=="string"?{urlPath:Yc(n),url:i,query:a,fragment:c,hasRoute:!1}:{urlPath:void 0,url:i,query:a,fragment:c,hasRoute:!1}}function xd(t,e,n="custom"){let r=e[St]||n,o=e[to];return o&&typeof o=="string"?{description:o,source:r}:{description:t,source:r}}function p3(t){t.on("createDsc",(e,n)=>{if(!n)return;let s=W(n).data[St],{description:i}=s3(n)?d3(n):{description:void 0};if(s!=="url"&&i&&(e.transaction=i),vt()){let a=lu(n.spanContext());e.sampled=a==null?void 0:String(a)}})}function _3(){return oe.getActiveSpan()}var ao=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function f3({dsc:t,sampled:e}){let n=t?aa(t):void 0,r=new or.TraceState,o=n?r.set(IN,n):r;return e===!1?o.set(PN,"1"):o}var m3=new Set;function E3(){return Array.from(m3)}function ES(t){m3.add(t)}var _S=class extends or.W3CBaggagePropagator{constructor(){super(),ES("SentryPropagator"),this._urlMatchesTargetsMap=new yn(100)}inject(e,n,r){if((0,or.isTracingSuppressed)(e)){ao&&g.log("[Tracing] Not injecting trace data for url because tracing is suppressed.");return}let o=oe.getSpan(e),s=o&&vwe(o),i=K()?.getOptions()?.tracePropagationTargets;if(!Ud(s,i,this._urlMatchesTargetsMap)){ao&&g.log("[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:",s);return}let a=Cwe(n),c=rn.getBaggage(e)||rn.createBaggage({}),{dynamicSamplingContext:u,traceId:l,spanId:d,sampled:p}=S3(e);if(a){let _=ca(a);_&&Object.entries(_).forEach(([f,E])=>{c=c.setEntry(f,{value:E})})}u&&(c=Object.entries(u).reduce((_,[f,E])=>E?_.setEntry(`${ld}${f}`,{value:E}):_,c)),l&&l!==zi&&r.set(n,SN,$s(l,d,p)),super.inject(rn.setBaggage(e,c),n,r)}extract(e,n,r){let o=r.get(n,SN),s=r.get(n,gN),i=o?Array.isArray(o)?o[0]:o:void 0;return h3(g3(e,{sentryTrace:i,baggage:s}))}fields(){return[SN,gN]}},t3="[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:";function Ud(t,e,n){if(typeof t!="string"||!e)return!0;let r=n?.get(t);if(r!==void 0)return ao&&!r&&g.log(t3,t),r;let o=ks(t,e);return n?.set(t,o),ao&&!o&&g.log(t3,t),o}function S3(t,e={}){let n=oe.getSpan(t);if(n?.spanContext().isRemote){let a=n.spanContext();return{dynamicSamplingContext:tt(n),traceId:a.traceId,spanId:void 0,sampled:lu(a)}}if(n){let a=n.spanContext();return{dynamicSamplingContext:tt(n),traceId:a.traceId,spanId:a.spanId,sampled:lu(a)}}let r=e.scope||pu(t)?.scope||ue(),o=e.client||K(),s=r.getPropagationContext();return{dynamicSamplingContext:o?Vo(o,r):void 0,traceId:s.traceId,spanId:s.propagationSpanId,sampled:s.sampled}}function g3(t,{sentryTrace:e,baggage:n}){let r=dd(e,n),{traceId:o,parentSpanId:s,sampled:i,dsc:a}=r;if(!s)return t;let c=Iwe({traceId:o,spanId:s,sampled:i,dsc:a});return oe.setSpanContext(t,c)}function Nwe(t,e,n){let r=h3(g3(t,e));return X.with(r,n)}function h3(t){let e=pu(t),n={scope:e?e.scope:ue().clone(),isolationScope:e?e.isolationScope:Re()};return u3(t,n)}function Cwe(t){try{let e=t[gN];return Array.isArray(e)?e.join(","):e}catch{return}}function vwe(t){let e=W(t).data,n=e[Kc]||e[Wc];if(typeof n=="string")return n;let r=t.spanContext().traceState?.get(i3);if(r)return r}function Iwe({spanId:t,traceId:e,sampled:n,dsc:r}){let o=f3({dsc:r,sampled:n});return{traceId:e,spanId:t,isRemote:!0,traceFlags:n?Kn.SAMPLED:Kn.NONE,traceState:o}}function Pwe(t,e){let n=bN(),{name:r,parentSpan:o}=t;return xN(o)(()=>{let i=LN(t.scope,t.forceTransaction),c=t.onlyIfParent&&!oe.getSpan(i)?(0,or.suppressTracing)(i):i,u=MN(t);return n.startActiveSpan(r,u,c,l=>Bo(()=>e(l),()=>{W(l).status===void 0&&l.setStatus({code:Me.ERROR})},()=>l.end()))})}function bwe(t,e){let n=bN(),{name:r,parentSpan:o}=t;return xN(o)(()=>{let i=LN(t.scope,t.forceTransaction),c=t.onlyIfParent&&!oe.getSpan(i)?(0,or.suppressTracing)(i):i,u=MN(t);return n.startActiveSpan(r,u,c,l=>Bo(()=>e(l,()=>l.end()),()=>{W(l).status===void 0&&l.setStatus({code:Me.ERROR})}))})}function Mwe(t){let e=bN(),{name:n,parentSpan:r}=t;return xN(r)(()=>{let s=LN(t.scope,t.forceTransaction),a=t.onlyIfParent&&!oe.getSpan(s)?(0,or.suppressTracing)(s):s,c=MN(t);return e.startSpan(n,c,a)})}function T3(t,e){let n=t?oe.setSpan(X.active(),t):oe.deleteSpan(X.active());return X.with(n,()=>e(ue()))}function bN(){return K()?.tracer||oe.getTracer("@sentry/opentelemetry",Pe)}function MN(t){let{startTime:e,attributes:n,kind:r,op:o,links:s}=t,i=typeof e=="number"?Lwe(e):e;return{attributes:o?{[se]:o,...n}:n,kind:r,links:s,startTime:i}}function Lwe(t){return t<9999999999?t*1e3:t}function LN(t,e){let n=xwe(t),r=oe.getSpan(n);if(!r||!e)return n;let o=oe.deleteSpan(n),{spanId:s,traceId:i}=r.spanContext(),a=lu(r.spanContext()),c=Ye(r),u=tt(c),l=f3({dsc:u,sampled:a}),d={traceId:i,spanId:s,isRemote:!0,traceFlags:a?Kn.SAMPLED:Kn.NONE,traceState:l};return oe.setSpanContext(o,d)}function xwe(t){if(t){let e=Dd(t);if(e)return e}return X.active()}function Dwe(t,e){return Nwe(X.active(),t,e)}function A3(t,e){let n=Dd(e),r=n&&oe.getSpan(n),o=r?Fs(r):Vc(e);return[r?tt(r):Vo(t,e),o]}function xN(t){return t!==void 0?e=>T3(t,e):e=>e()}function Uwe(t){let e=(0,or.suppressTracing)(X.active());return X.with(e,t)}function R3(t){t.on("preprocessEvent",e=>{let n=_3();if(!n||e.type==="transaction")return;e.contexts={trace:Fs(n),...e.contexts};let r=Ye(n);return e.sdkProcessingMetadata={dynamicSamplingContext:tt(r),...e.sdkProcessingMetadata},e})}function wwe({span:t,scope:e,client:n}={}){let r=(e&&Dd(e))??X.active();if(t){let{scope:c}=Nr(t);r=c&&Dd(c)||oe.setSpan(X.active(),t)}let{traceId:o,spanId:s,sampled:i,dynamicSamplingContext:a}=S3(r,{scope:e,client:n});return{"sentry-trace":$s(o,s,i),baggage:aa(a)}}function y3(){function t(){let a=X.active(),c=pu(a);return c||{scope:wc(),isolationScope:Qr()}}function e(a){let c=X.active();return X.with(c,()=>a(s()))}function n(a,c){let u=Dd(a)||X.active();return X.with(u.setValue(TN,a),()=>c(a))}function r(a){let c=X.active();return X.with(c.setValue(hN,!0),()=>a(i()))}function o(a,c){let u=X.active();return X.with(u.setValue(AN,a),()=>c(i()))}function s(){return t().scope}function i(){return t().isolationScope}Sy({withScope:e,withSetScope:n,withSetIsolationScope:o,withIsolationScope:r,getCurrentScope:s,getIsolationScope:i,startSpan:Pwe,startSpanManual:bwe,startInactiveSpan:Mwe,getActiveSpan:_3,suppressTracing:Uwe,getTraceData:wwe,continueTrace:Dwe,withActiveSpan:T3})}function O3(t){class e extends t{constructor(...r){super(...r),ES("SentryContextManager")}with(r,o,s,...i){let a=pu(r),c=a?.scope||ue(),u=a?.isolationScope||Re(),l=r.getValue(hN)===!0,d=r.getValue(TN),p=r.getValue(AN),_=d||c.clone(),f=p||(l?u.clone():u),h=u3(r,{scope:_,isolationScope:f}).deleteValue(hN).deleteValue(TN).deleteValue(AN);return Twe(_,h),super.with(h,o,s,...i)}}return e}function kwe(t){let e=new Map;for(let n of t)Vwe(e,n);return Array.from(e,function([n,r]){return r})}function N3(t){return t.attributes[NN]===!0?void 0:CN(t)}function Vwe(t,e){let n=e.spanContext().spanId,r=N3(e);if(!r){RN(t,{id:n,span:e,children:[]});return}let o=Bwe(t,r),s=RN(t,{id:n,span:e,parentNode:o,children:[]});o.children.push(s)}function Bwe(t,e){let n=t.get(e);return n||RN(t,{id:e,children:[]})}function RN(t,e){let n=t.get(e.id);return n?.span?n:n&&!n.span?(n.span=e.span,n.parentNode=e.parentNode,n):(t.set(e.id,e),e)}var C3={1:"cancelled",2:"unknown_error",3:"invalid_argument",4:"deadline_exceeded",5:"not_found",6:"already_exists",7:"permission_denied",8:"resource_exhausted",9:"failed_precondition",10:"aborted",11:"out_of_range",12:"unimplemented",13:"internal_error",14:"unavailable",15:"data_loss",16:"unauthenticated"},Gwe=t=>Object.values(C3).includes(t);function v3(t){let e=vN(t)?t.attributes:{},n=mwe(t)?t.status:void 0;if(n){if(n.code===Me.OK)return{code:1};if(n.code===Me.ERROR){if(typeof n.message>"u"){let o=n3(e);if(o)return o}return n.message&&Gwe(n.message)?{code:2,message:n.message}:{code:2,message:"unknown_error"}}}let r=n3(e);return r||(n?.code===Me.UNSET?{code:1}:{code:2,message:"unknown_error"})}function n3(t){let e=t[Ks]||t[TE],n=t[dO],r=typeof e=="number"?e:typeof e=="string"?parseInt(e):void 0;if(typeof r=="number")return Um(r);if(typeof n=="string")return{code:2,message:C3[n]||"unknown_error"}}var r3=1e3,o3=300,yN=class{constructor(e){this._finishedSpanBucketSize=e?.timeout||o3,this._finishedSpanBuckets=new Array(this._finishedSpanBucketSize).fill(void 0),this._lastCleanupTimestampInS=Math.floor(Date.now()/1e3),this._spansToBucketEntry=new WeakMap,this._sentSpans=new Map,this._debouncedFlush=$y(this.flush.bind(this),1,{maxWait:100})}export(e){let n=Math.floor(Date.now()/1e3);if(this._lastCleanupTimestampInS!==n){let i=0;this._finishedSpanBuckets.forEach((a,c)=>{a&&a.timestampInS<=n-this._finishedSpanBucketSize&&(i+=a.spans.size,this._finishedSpanBuckets[c]=void 0)}),i>0&&ao&&g.log(`SpanExporter dropped ${i} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`),this._lastCleanupTimestampInS=n}let r=n%this._finishedSpanBucketSize,o=this._finishedSpanBuckets[r]||{timestampInS:n,spans:new Set};this._finishedSpanBuckets[r]=o,o.spans.add(e),this._spansToBucketEntry.set(e,o);let s=N3(e);(!s||this._sentSpans.has(s))&&this._debouncedFlush()}flush(){let e=this._finishedSpanBuckets.flatMap(i=>i?Array.from(i.spans):[]);this._flushSentSpanCache();let n=this._maybeSend(e),r=n.size,o=e.length-r;ao&&g.log(`SpanExporter exported ${r} spans, ${o} spans are waiting for their parent spans to finish`);let s=Date.now()+o3*1e3;for(let i of n){this._sentSpans.set(i.spanContext().spanId,s);let a=this._spansToBucketEntry.get(i);a&&a.spans.delete(i)}this._debouncedFlush.cancel()}clear(){this._finishedSpanBuckets=this._finishedSpanBuckets.fill(void 0),this._sentSpans.clear(),this._debouncedFlush.cancel()}_maybeSend(e){let n=kwe(e),r=new Set,o=this._getCompletedRootNodes(n);for(let s of o){let i=s.span;r.add(i);let a=$we(i);if(s.parentNode&&this._sentSpans.has(s.parentNode.id)){let l=a.contexts?.trace?.data;l&&(l["sentry.parent_span_already_sent"]=!0)}let c=a.spans||[];for(let l of s.children)ON(l,c,r);a.spans=c.length>r3?c.sort((l,d)=>l.start_timestamp-d.start_timestamp).slice(0,r3):c;let u=pa(i.events);u&&(a.measurements=u),nE(a)}return r}_flushSentSpanCache(){let e=Date.now();for(let[n,r]of this._sentSpans.entries())r<=e&&this._sentSpans.delete(n)}_nodeIsCompletedRootNodeOrHasSentParent(e){return!!e.span&&(!e.parentNode||this._sentSpans.has(e.parentNode.id))}_getCompletedRootNodes(e){return e.filter(n=>this._nodeIsCompletedRootNodeOrHasSentParent(n))}};function Hwe(t){let e=t.attributes,n=e[ye],r=e[se],o=e[St];return{origin:n,op:r,source:o}}function $we(t){let{op:e,description:n,data:r,origin:o="manual",source:s}=I3(t),i=Nr(t),a=t.attributes[Or],c={[St]:s,[Or]:a,[se]:e,[ye]:o,...r,...P3(t.attributes)},{links:u}=t,{traceId:l,spanId:d}=t.spanContext(),p=CN(t),_=v3(t),f={parent_span_id:p,span_id:d,trace_id:l,data:c,origin:o,op:e,status:la(_),links:ua(u)},E=c[Ks],S=typeof E=="number"?{response:{status_code:E}}:void 0;return{contexts:{trace:f,otel:{resource:t.resource.attributes},...S},spans:[],start_timestamp:Rn(t.startTime),timestamp:Rn(t.endTime),transaction:n,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:i.scope,capturedSpanIsolationScope:i.isolationScope,sampleRate:a,dynamicSamplingContext:tt(t)},...s&&{transaction_info:{source:s}}}}function ON(t,e,n){let r=t.span;if(r&&n.add(r),!r){t.children.forEach(A=>{ON(A,e,n)});return}let s=r.spanContext().spanId,i=r.spanContext().traceId,a=CN(r),{attributes:c,startTime:u,endTime:l,links:d}=r,{op:p,description:_,data:f,origin:E="manual"}=I3(r),S={[ye]:E,[se]:p,...P3(c),...f},h=v3(r),R={span_id:s,trace_id:i,data:S,description:_,parent_span_id:a,start_timestamp:Rn(u),timestamp:Rn(l)||void 0,status:la(h),op:p,origin:E,measurements:pa(r.events),links:ua(d)};e.push(R),t.children.forEach(A=>{ON(A,e,n)})}function I3(t){let{op:e,source:n,origin:r}=Hwe(t),{op:o,description:s,source:i,data:a}=d3(t),c=e||o,u=n||i,l={...a,...Fwe(t)};return{op:c,description:s,source:u,origin:r,data:l}}function P3(t){let e={...t};return delete e[Or],delete e[NN],delete e[to],e}function Fwe(t){let e=t.attributes,n={};t.kind!==Dt.INTERNAL&&(n["otel.kind"]=Dt[t.kind]);let r=e[TE];r&&(n[Ks]=r);let o=Ewe(t);return o.url&&(n.url=o.url),o["http.query"]&&(n["http.query"]=o["http.query"].slice(1)),o["http.fragment"]&&(n["http.fragment"]=o["http.fragment"].slice(1)),n}function jwe(t,e){let n=oe.getSpan(e),r=pu(e);n&&!n.spanContext().isRemote&&Hc(n,t),n?.spanContext().isRemote&&t.setAttribute(NN,!0),e===sc&&(r={scope:wc(),isolationScope:Qr()}),r&&ud(t,r.scope,r.isolationScope),md(t),K()?.emit("spanStart",t)}function qwe(t){Ed(t),K()?.emit("spanEnd",t)}var fS=class{constructor(e){ES("SentrySpanProcessor"),this._exporter=new yN(e)}async forceFlush(){this._exporter.flush()}async shutdown(){this._exporter.clear()}onStart(e,n){jwe(e,n)}onEnd(e){qwe(e),this._exporter.export(e)}},mS=class{constructor(e){this._client=e,ES("SentrySampler")}shouldSample(e,n,r,o,s,i){let a=this._client.getOptions(),c=Wwe(e),u=c?.spanContext();if(!vt(a))return uu({decision:void 0,context:e,spanAttributes:s});let l=s[Cd]||s[ma];if(o===Dt.CLIENT&&l&&(!c||u?.isRemote))return uu({decision:void 0,context:e,spanAttributes:s});let d=c?Ywe(c,n,r):void 0;if(!(!c||u?.isRemote))return uu({decision:d?Ws.SamplingDecision.RECORD_AND_SAMPLED:Ws.SamplingDecision.NOT_RECORD,context:e,spanAttributes:s});let{description:_,data:f,op:E}=l3(r,s,o),S={...f,...s};E&&(S[se]=E);let h={decision:!0};if(this._client.emit("beforeSampling",{spanAttributes:S,spanName:_,parentSampled:d,parentContext:u},h),!h.decision)return uu({decision:void 0,context:e,spanAttributes:s});let{isolationScope:R}=pu(e)??{},A=u?.traceState?u.traceState.get(IN):void 0,O=A?Hs(A):void 0,y=xn(O?.sample_rand)??Math.random(),[M,I,J]=Sd(a,{name:_,attributes:S,normalizedRequest:R?.getScopeData().sdkProcessingMetadata.normalizedRequest,parentSampled:d,parentSampleRate:xn(O?.sample_rate)},y),H=`${l}`.toUpperCase();return H==="OPTIONS"||H==="HEAD"?(ao&&g.log(`[Tracing] Not sampling span because HTTP method is '${H}' for ${r}`),uu({decision:Ws.SamplingDecision.NOT_RECORD,context:e,spanAttributes:s,sampleRand:y,downstreamTraceSampleRate:0})):(!M&&d===void 0&&(ao&&g.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),this._client.recordDroppedEvent("sample_rate","transaction")),{...uu({decision:M?Ws.SamplingDecision.RECORD_AND_SAMPLED:Ws.SamplingDecision.NOT_RECORD,context:e,spanAttributes:s,sampleRand:y,downstreamTraceSampleRate:J?I:void 0}),attributes:{[Or]:J?I:void 0}})}toString(){return"SentrySampler"}};function Ywe(t,e,n){let r=t.spanContext();if(xo(r)&&r.traceId===e){if(r.isRemote){let s=lu(t.spanContext());return ao&&g.log(`[Tracing] Inheriting remote parent's sampled decision for ${n}: ${s}`),s}let o=lu(r);return ao&&g.log(`[Tracing] Inheriting parent's sampled decision for ${n}: ${o}`),o}}function uu({decision:t,context:e,spanAttributes:n,sampleRand:r,downstreamTraceSampleRate:o}){let s=Kwe(e,n);return o!==void 0&&(s=s.set(hwe,`${o}`)),r!==void 0&&(s=s.set(gwe,`${r}`)),t==null?{decision:Ws.SamplingDecision.NOT_RECORD,traceState:s}:t===Ws.SamplingDecision.NOT_RECORD?{decision:t,traceState:s.set(PN,"1")}:{decision:t,traceState:s}}function Kwe(t,e){let o=oe.getSpan(t)?.spanContext()?.traceState||new or.TraceState,s=e[Kc]||e[Wc];return s&&typeof s=="string"&&(o=o.set(i3,s)),o}function Wwe(t){let e=oe.getSpan(t);return e&&xo(e.spanContext())?e:void 0}var _e=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function wd(t,e){if(!t)return e;let n=ca(t),r=ca(e);if(!r)return t;let o={...n};return Object.entries(r).forEach(([s,i])=>{o[s]||(o[s]=i)}),wm(o)}function _u(t){let e=t.protocol||"",n=t.hostname||t.host||"",r=!t.port||t.port===80||t.port===443||/^(.*):(\d+)$/.test(n)?"":`:${t.port}`,o=t.path?t.path:"/";return`${e}//${n}${r}${o}`}var On="@sentry/instrumentation-http",zwe=1024*1024,Ra=class extends kd.InstrumentationBase{constructor(e={}){super(On,Pe,e),this._propagationDecisionMap=new yn(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){let e=!1,n=(c=>{let u=c;this._patchServerEmitOnce(u.server)}),r=(c=>{let u=c;this._onOutgoingRequestFinish(u.request,u.response)}),o=(c=>{let u=c;this._onOutgoingRequestFinish(u.request,void 0)}),s=(c=>{let u=c;this._onOutgoingRequestCreated(u.request)}),i=c=>(e||(e=!0,(0,co.subscribe)("http.server.request.start",n),(0,co.subscribe)("http.client.response.finish",r),(0,co.subscribe)("http.client.request.error",o),this.getConfig().propagateTraceInOutgoingRequests&&(0,co.subscribe)("http.client.request.created",s)),c),a=()=>{(0,co.unsubscribe)("http.server.request.start",n),(0,co.unsubscribe)("http.client.response.finish",r),(0,co.unsubscribe)("http.client.request.error",o),(0,co.unsubscribe)("http.client.request.created",s)};return[new kd.InstrumentationNodeModuleDefinition("http",["*"],i,a),new kd.InstrumentationNodeModuleDefinition("https",["*"],i,a)]}_onOutgoingRequestFinish(e,n){_e&&g.log(On,"Handling finished outgoing request");let r=this.getConfig().breadcrumbs,o=typeof r>"u"?!0:r,s=this._ignoreOutgoingRequestsMap.get(e)??this._shouldIgnoreOutgoingRequest(e);this._ignoreOutgoingRequestsMap.set(e,s),o&&!s&&Xwe(e,n)}_onOutgoingRequestCreated(e){let n=this._ignoreOutgoingRequestsMap.get(e)??this._shouldIgnoreOutgoingRequest(e);if(this._ignoreOutgoingRequestsMap.set(e,n),n)return;let r=_u(e),o=K()?.getOptions().tracePropagationTargets,s=Ud(r,o,this._propagationDecisionMap)?qc():void 0;if(!s)return;let{"sentry-trace":i,baggage:a}=s;if(i&&!e.getHeader("sentry-trace"))try{e.setHeader("sentry-trace",i),_e&&g.log(On,"Added sentry-trace header to outgoing request")}catch(c){_e&&g.error(On,"Failed to add sentry-trace header to outgoing request:",Us(c)?c.message:"Unknown error")}if(a){let c=wd(e.getHeader("baggage"),a);if(c)try{e.setHeader("baggage",c),_e&&g.log(On,"Added baggage header to outgoing request")}catch(u){_e&&g.error(On,"Failed to add baggage header to outgoing request:",Us(u)?u.message:"Unknown error")}}}_patchServerEmitOnce(e){let n=e.emit;if(n.__sentry_patched__)return;_e&&g.log(On,"Patching server.emit");let r=this,{ignoreIncomingRequestBody:o,maxIncomingRequestBodySize:s="medium"}=r.getConfig(),i=new Proxy(n,{apply(a,c,u){if(u[0]!=="request")return a.apply(c,u);_e&&g.log(On,"Handling incoming request");let l=Re().clone(),d=u[1],p=u[2],_=cE(d),f=d.ip||d.socket?.remoteAddress,E=d.url||"/";!o?.(E,d)&&s!=="none"&&Zwe(d,l,s),l.setSDKProcessingMetadata({normalizedRequest:_,ipAddress:f});let S=(d.method||"GET").toUpperCase(),h=Yc(E),R=`${S} ${h}`;return l.setTransactionName(R),r.getConfig().trackIncomingRequestsAsSessions!==!1&&e1e({requestIsolationScope:l,response:p,sessionFlushingDelayMS:r.getConfig().sessionFlushingDelayMS??6e4}),cd(l,()=>{if(ue().getPropagationContext().propagationSpanId=Ln(),!r.getConfig().extractIncomingTraceFromHeader)return a.apply(c,u);let A=rn.extract(X.active(),_.headers);return X.with(A,()=>a.apply(c,u))})}});ct(i,"__sentry_patched__",!0),e.emit=i}_shouldIgnoreOutgoingRequest(e){if((0,b3.isTracingSuppressed)(X.active()))return!0;let n=this.getConfig().ignoreOutgoingRequests;if(!n)return!1;let r=Qwe(e),o=_u(e);return n(o,r)}};function Xwe(t,e){let n=Jwe(t),r=e?.statusCode,o=yd(r);Un({category:"http",data:{status_code:r,...n},type:"http",level:o},{event:"response",request:t,response:e})}function Jwe(t){try{let e=t.getHeader("host")||t.host,n=new URL(t.path,`${t.protocol}//${e}`),r=js(n.toString()),o={url:qs(r),"http.method":t.method||"GET"};return r.search&&(o["http.query"]=r.search),r.hash&&(o["http.fragment"]=r.hash),o}catch{return{}}}function Zwe(t,e,n){let r=0,o=[];_e&&g.log(On,"Patching request.on");let s=new WeakMap,i=n==="small"?1e3:n==="medium"?1e4:zwe;try{t.on=new Proxy(t.on,{apply:(a,c,u)=>{let[l,d,...p]=u;if(l==="data"){_e&&g.log(On,`Handling request.on("data") with maximum body size of ${i}b`);let _=new Proxy(d,{apply:(f,E,S)=>{try{let h=S[0],R=Buffer.from(h);r<i?(o.push(R),r+=R.byteLength):_e&&g.log(On,`Dropping request body chunk because maximum body length of ${i}b is exceeded.`)}catch{_e&&g.error(On,"Encountered error while storing body chunk.")}return Reflect.apply(f,E,S)}});return s.set(d,_),Reflect.apply(a,c,[l,_,...p])}return Reflect.apply(a,c,u)}}),t.off=new Proxy(t.off,{apply:(a,c,u)=>{let[,l]=u,d=s.get(l);if(d){s.delete(l);let p=u.slice();return p[1]=d,Reflect.apply(a,c,p)}return Reflect.apply(a,c,u)}}),t.on("end",()=>{try{let a=Buffer.concat(o).toString("utf-8");if(a){let u=Buffer.byteLength(a,"utf-8")>i?`${Buffer.from(a).subarray(0,i-3).toString("utf-8")}...`:a;e.setSDKProcessingMetadata({normalizedRequest:{data:u}})}}catch(a){_e&&g.error(On,"Error building captured request body",a)}})}catch(a){_e&&g.error(On,"Error patching request to capture body",a)}}function Qwe(t){return{method:t.method,protocol:t.protocol,host:t.host,hostname:t.host,path:t.path,headers:t.getHeaders()}}function e1e({requestIsolationScope:t,response:e,sessionFlushingDelayMS:n}){t.setSDKProcessingMetadata({requestSession:{status:"ok"}}),e.once("close",()=>{let r=K(),o=t.getScopeData().sdkProcessingMetadata.requestSession;if(r&&o){_e&&g.log(`Recorded request session with status: ${o.status}`);let s=new Date;s.setSeconds(0,0);let i=s.toISOString(),a=DN.get(r),c=a?.[i]||{exited:0,crashed:0,errored:0};if(c[{ok:"exited",crashed:"crashed",errored:"errored"}[o.status]]++,a)a[i]=c;else{_e&&g.log("Opened new request session aggregate.");let u={[i]:c};DN.set(r,u);let l=()=>{clearTimeout(p),d(),DN.delete(r);let _=Object.entries(u).map(([f,E])=>({started:f,exited:E.exited,errored:E.errored,crashed:E.crashed}));r.sendSession({aggregates:_})},d=r.on("flush",()=>{_e&&g.log("Sending request session aggregate due to client flush"),l()}),p=setTimeout(()=>{_e&&g.log("Sending request session aggregate due to flushing schedule"),l()},n).unref()}}})}var DN=new Map;var M3="Http",t1e=q(`${M3}.sentry`,t=>new Ra(t)),L3=(t={})=>{let e=t.dropSpansForIncomingRequestStatusCodes??[[401,404],[300,399]];return{name:M3,setupOnce(){t1e({...t,extractIncomingTraceFromHeader:!0,propagateTraceInOutgoingRequests:!0})},processEvent(n){if(n.type==="transaction"){let r=n.contexts?.trace?.data?.["http.response.status_code"];if(typeof r=="number"&&e.some(o=>{if(typeof o=="number")return o===r;let[s,i]=o;return r>=s&&r<=i}))return null}return n}}};x();var U3=v(Se(),1),w3=v(fe(),1);var fu=v(require("diagnostics_channel"),1);var ya=fy(process.versions.node),Vd=ya.major,x3=ya.minor;var SS="sentry-trace",UN="baggage",D3=/baggage: (.*)\r\n/,Oa=class extends w3.InstrumentationBase{constructor(e={}){super("@sentry/instrumentation-node-fetch",Pe,e),this._channelSubs=[],this._propagationDecisionMap=new yn(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){}disable(){super.disable(),this._channelSubs.forEach(e=>e.unsubscribe()),this._channelSubs=[]}enable(){super.enable(),this._channelSubs=this._channelSubs||[],!(this._channelSubs.length>0)&&(this._subscribeToChannel("undici:request:create",this._onRequestCreated.bind(this)),this._subscribeToChannel("undici:request:headers",this._onResponseHeaders.bind(this)))}_onRequestCreated({request:e}){if(!(this.getConfig().enabled!==!1))return;let o=this._shouldIgnoreOutgoingRequest(e);if(this._ignoreOutgoingRequestsMap.set(e,o),o)return;let s=wN(e.origin,e.path),i=K()?.getOptions().tracePropagationTargets,a=Ud(s,i,this._propagationDecisionMap)?qc():void 0;if(!a)return;let{"sentry-trace":c,baggage:u}=a;if(Array.isArray(e.headers)){let l=e.headers;c&&!l.includes(SS)&&l.push(SS,c);let d=l.findIndex(p=>p===UN);if(u&&d===-1)l.push(UN,u);else if(u){let p=l[d+1],_=wd(p,u);_&&(l[d+1]=_)}}else{let l=e.headers;c&&!l.includes(`${SS}:`)&&(e.headers+=`${SS}: ${c}\r
169
- `);let d=e.headers.match(D3)?.[1];if(u&&!d)e.headers+=`${UN}: ${u}\r
170
- `;else if(u){let p=wd(d,u);p&&(e.headers=e.headers.replace(D3,`baggage: ${p}\r
171
- `))}}}_onResponseHeaders({request:e,response:n}){let r=this.getConfig();if(!(r.enabled!==!1))return;let s=r.breadcrumbs,i=typeof s>"u"?!0:s,a=this._ignoreOutgoingRequestsMap.get(e);i&&!a&&n1e(e,n)}_subscribeToChannel(e,n){let r=Vd>18||Vd===18&&x3>=19,o;if(r)fu.subscribe?.(e,n),o=()=>fu.unsubscribe?.(e,n);else{let s=fu.channel(e);s.subscribe(n),o=()=>s.unsubscribe(n)}this._channelSubs.push({name:e,unsubscribe:o})}_shouldIgnoreOutgoingRequest(e){if((0,U3.isTracingSuppressed)(X.active()))return!0;let n=wN(e.origin,e.path),r=this.getConfig().ignoreOutgoingRequests;return typeof r!="function"||!n?!1:r(n)}};function n1e(t,e){let n=r1e(t),r=e.statusCode,o=yd(r);Un({category:"http",data:{status_code:r,...n},type:"http",level:o},{event:"response",request:t,response:e})}function r1e(t){try{let e=wN(t.origin,t.path),n=js(e),r={url:qs(n),"http.method":t.method||"GET"};return n.search&&(r["http.query"]=n.search),n.hash&&(r["http.fragment"]=n.hash),r}catch{return{}}}function wN(t,e="/"){try{return new URL(e,t).toString()}catch{let n=`${t}`;return n.endsWith("/")&&e.startsWith("/")?`${n}${e.slice(1)}`:!n.endsWith("/")&&!e.startsWith("/")?`${n}/${e.slice(1)}`:`${n}${e}`}}var o1e="NodeFetch",s1e=q(`${o1e}.sentry`,Oa,t=>t),i1e=((t={})=>({name:"NodeFetch",setupOnce(){s1e(t)}})),k3=i1e;var B3=require("node:child_process"),gS=require("node:fs"),It=v(require("node:os"),1),G3=require("node:path"),kN=require("node:util");var a1e=(0,kN.promisify)(gS.readFile),c1e=(0,kN.promisify)(gS.readdir),u1e="Context",l1e=((t={})=>{let e,n={app:!0,os:!0,device:!0,culture:!0,cloudResource:!0,...t};async function r(s){e===void 0&&(e=o());let i=d1e(await e);return s.contexts={...s.contexts,app:{...i.app,...s.contexts?.app},os:{...i.os,...s.contexts?.os},device:{...i.device,...s.contexts?.device},culture:{...i.culture,...s.contexts?.culture},cloud_resource:{...i.cloud_resource,...s.contexts?.cloud_resource}},s}async function o(){let s={};if(n.os&&(s.os=await p1e()),n.app&&(s.app=f1e()),n.device&&(s.device=m1e(n.device)),n.culture){let i=_1e();i&&(s.culture=i)}return n.cloudResource&&(s.cloud_resource=A1e()),s}return{name:u1e,processEvent(s){return r(s)}}}),H3=l1e;function d1e(t){if(t.app?.app_memory&&(t.app.app_memory=process.memoryUsage().rss),t.app?.free_memory&&typeof process.availableMemory=="function"){let e=process.availableMemory?.();e!=null&&(t.app.free_memory=e)}return t.device?.free_memory&&(t.device.free_memory=It.freemem()),t}async function p1e(){let t=It.platform();switch(t){case"darwin":return h1e();case"linux":return T1e();default:return{name:E1e[t]||t,version:It.release()}}}function _1e(){try{if(typeof process.versions.icu!="string")return;let t=new Date(9e8);if(new Intl.DateTimeFormat("es",{month:"long"}).format(t)==="enero"){let n=Intl.DateTimeFormat().resolvedOptions();return{locale:n.locale,timezone:n.timeZone}}}catch{}}function f1e(){let t=process.memoryUsage().rss,n={app_start_time:new Date(Date.now()-process.uptime()*1e3).toISOString(),app_memory:t};if(typeof process.availableMemory=="function"){let r=process.availableMemory?.();r!=null&&(n.free_memory=r)}return n}function m1e(t){let e={},n;try{n=It.uptime()}catch{}if(typeof n=="number"&&(e.boot_time=new Date(Date.now()-n*1e3).toISOString()),e.arch=It.arch(),(t===!0||t.memory)&&(e.memory_size=It.totalmem(),e.free_memory=It.freemem()),t===!0||t.cpu){let r=It.cpus(),o=r?.[0];o&&(e.processor_count=r.length,e.cpu_description=o.model,e.processor_frequency=o.speed)}return e}var E1e={aix:"IBM AIX",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows"},S1e=[{name:"fedora-release",distros:["Fedora"]},{name:"redhat-release",distros:["Red Hat Linux","Centos"]},{name:"redhat_version",distros:["Red Hat Linux"]},{name:"SuSE-release",distros:["SUSE Linux"]},{name:"lsb-release",distros:["Ubuntu Linux","Arch Linux"]},{name:"debian_version",distros:["Debian"]},{name:"debian_release",distros:["Debian"]},{name:"arch-release",distros:["Arch Linux"]},{name:"gentoo-release",distros:["Gentoo Linux"]},{name:"novell-release",distros:["SUSE Linux"]},{name:"alpine-release",distros:["Alpine Linux"]}],g1e={alpine:t=>t,arch:t=>uo(/distrib_release=(.*)/,t),centos:t=>uo(/release ([^ ]+)/,t),debian:t=>t,fedora:t=>uo(/release (..)/,t),mint:t=>uo(/distrib_release=(.*)/,t),red:t=>uo(/release ([^ ]+)/,t),suse:t=>uo(/VERSION = (.*)\n/,t),ubuntu:t=>uo(/distrib_release=(.*)/,t)};function uo(t,e){let n=t.exec(e);return n?n[1]:void 0}async function h1e(){let t={kernel_version:It.release(),name:"Mac OS X",version:`10.${Number(It.release().split(".")[0])-4}`};try{let e=await new Promise((n,r)=>{(0,B3.execFile)("/usr/bin/sw_vers",(o,s)=>{if(o){r(o);return}n(s)})});t.name=uo(/^ProductName:\s+(.*)$/m,e),t.version=uo(/^ProductVersion:\s+(.*)$/m,e),t.build=uo(/^BuildVersion:\s+(.*)$/m,e)}catch{}return t}function V3(t){return t.split(" ")[0].toLowerCase()}async function T1e(){let t={kernel_version:It.release(),name:"Linux"};try{let e=await c1e("/etc"),n=S1e.find(a=>e.includes(a.name));if(!n)return t;let r=(0,G3.join)("/etc",n.name),o=(await a1e(r,{encoding:"utf-8"})).toLowerCase(),{distros:s}=n;t.name=s.find(a=>o.indexOf(V3(a))>=0)||s[0];let i=V3(t.name);t.version=g1e[i]?.(o)}catch{}return t}function A1e(){return process.env.VERCEL?{"cloud.provider":"vercel","cloud.region":process.env.VERCEL_REGION}:process.env.AWS_REGION?{"cloud.provider":"aws","cloud.region":process.env.AWS_REGION,"cloud.platform":process.env.AWS_EXECUTION_ENV}:process.env.GCP_PROJECT?{"cloud.provider":"gcp"}:process.env.ALIYUN_REGION_ID?{"cloud.provider":"alibaba_cloud","cloud.region":process.env.ALIYUN_REGION_ID}:process.env.WEBSITE_SITE_NAME&&process.env.REGION_NAME?{"cloud.provider":"azure","cloud.region":process.env.REGION_NAME}:process.env.IBM_CLOUD_REGION?{"cloud.provider":"ibm_cloud","cloud.region":process.env.IBM_CLOUD_REGION}:process.env.TENCENTCLOUD_REGION?{"cloud.provider":"tencent_cloud","cloud.region":process.env.TENCENTCLOUD_REGION,"cloud.account.id":process.env.TENCENTCLOUD_APPID,"cloud.availability_zone":process.env.TENCENTCLOUD_ZONE}:process.env.NETLIFY?{"cloud.provider":"netlify"}:process.env.FLY_REGION?{"cloud.provider":"fly.io","cloud.region":process.env.FLY_REGION}:process.env.DYNO?{"cloud.provider":"heroku"}:void 0}var j3=require("node:fs"),q3=require("node:readline");var VN=new yn(10),Y3=new yn(20),R1e=7,y1e="ContextLines",O1e=1e3,N1e=1e4;function C1e(t,e,n){let r=t.get(e);return r===void 0?(t.set(e,n),n):r}function v1e(t){return!!(t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:"))}function I1e(t){return t.lineno!==void 0&&t.lineno>N1e||t.colno!==void 0&&t.colno>O1e}function P1e(t,e){let n=VN.get(t);if(n===void 0)return!1;for(let r=e[0];r<=e[1];r++)if(n[r]===void 0)return!1;return!0}function b1e(t,e){if(!t.length)return[];let n=0,r=t[0];if(typeof r!="number")return[];let o=F3(r,e),s=[];for(;;){if(n===t.length-1){s.push(o);break}let i=t[n+1];if(typeof i!="number")break;i<=o[1]?o[1]=i+e:(s.push(o),o=F3(i,e)),n++}return s}function M1e(t,e,n){return new Promise((r,o)=>{let s=(0,j3.createReadStream)(t),i=(0,q3.createInterface)({input:s});function a(){s.destroy(),r()}let c=0,u=0,l=e[u];if(l===void 0){a();return}let d=l[0],p=l[1];function _(f){Y3.set(t,1),_e&&g.error(`Failed to read file: ${t}. Error: ${f}`),i.close(),i.removeAllListeners(),a()}s.on("error",_),i.on("error",_),i.on("close",a),i.on("line",f=>{if(c++,!(c<d)&&(n[c]=ay(f,0),c>=p)){if(u===e.length-1){i.close(),i.removeAllListeners();return}u++;let E=e[u];if(E===void 0){i.close(),i.removeAllListeners();return}d=E[0],p=E[1]}})})}async function L1e(t,e){let n={};if(e>0&&t.exception?.values){for(let s of t.exception.values)if(s.stacktrace?.frames?.length)for(let i=s.stacktrace.frames.length-1;i>=0;i--){let a=s.stacktrace.frames[i],c=a?.filename;if(!a||typeof c!="string"||typeof a.lineno!="number"||v1e(c)||I1e(a))continue;n[c]||(n[c]=[]),n[c].push(a.lineno)}}let r=Object.keys(n);if(r.length==0)return t;let o=[];for(let s of r){if(Y3.get(s))continue;let i=n[s];if(!i)continue;i.sort((u,l)=>u-l);let a=b1e(i,e);if(a.every(u=>P1e(s,u)))continue;let c=C1e(VN,s,{});o.push(M1e(s,a,c))}if(await Promise.all(o).catch(()=>{_e&&g.log("Failed to read one or more source files and resolve context lines")}),e>0&&t.exception?.values)for(let s of t.exception.values)s.stacktrace?.frames&&s.stacktrace.frames.length>0&&x1e(s.stacktrace.frames,e,VN);return t}function x1e(t,e,n){for(let r of t)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let o=n.get(r.filename);if(o===void 0)continue;D1e(r.lineno,r,e,o)}}function $3(t){delete t.pre_context,delete t.context_line,delete t.post_context}function D1e(t,e,n,r){if(e.lineno===void 0||r===void 0){_e&&g.error("Cannot resolve context for frame with no lineno or file contents");return}e.pre_context=[];for(let s=K3(t,n);s<t;s++){let i=r[s];if(i===void 0){$3(e),_e&&g.error(`Could not find line ${s} in file ${e.filename}`);return}e.pre_context.push(i)}if(r[t]===void 0){$3(e),_e&&g.error(`Could not find line ${t} in file ${e.filename}`);return}e.context_line=r[t];let o=W3(t,n);e.post_context=[];for(let s=t+1;s<=o;s++){let i=r[s];if(i===void 0)break;e.post_context.push(i)}}function K3(t,e){return Math.max(1,t-e)}function W3(t,e){return t+e}function F3(t,e){return[K3(t,e),W3(t,e)]}var U1e=((t={})=>{let e=t.frameContextLines!==void 0?t.frameContextLines:R1e;return{name:y1e,processEvent(n){return L1e(n,e)}}}),z3=U1e;var Q3=require("node:worker_threads");var hS;async function TS(){if(hS===void 0)try{hS=!!(await import("node:inspector")).url()}catch{hS=!1}return hS}var Bd="__SENTRY_ERROR_LOCAL_VARIABLES__";function J3(t,e,n){let r=0,o=5,s=0;return setInterval(()=>{s===0?r>t&&(o*=2,n(o),o>86400&&(o=86400),s=o):(s-=1,s===0&&e()),r=0},1e3).unref(),()=>{r+=1}}function X3(t){return t!==void 0&&(t.length===0||t==="?"||t==="<anonymous>")}function AS(t,e){return t===e||`Object.${t}`===e||t===`Object.${e}`||X3(t)&&X3(e)}var w1e="LyohIEBzZW50cnkvbm9kZS1jb3JlIDkuNDcuMSAoNDExZTEwMikgfCBodHRwczovL2dpdGh1Yi5jb20vZ2V0c2VudHJ5L3NlbnRyeS1qYXZhc2NyaXB0ICovCmltcG9ydHtTZXNzaW9uIGFzIGV9ZnJvbSJub2RlOmluc3BlY3Rvci9wcm9taXNlcyI7aW1wb3J0e3dvcmtlckRhdGEgYXMgdH1mcm9tIm5vZGU6d29ya2VyX3RocmVhZHMiO2NvbnN0IG49Z2xvYmFsVGhpcyxpPXt9O2NvbnN0IG89Il9fU0VOVFJZX0VSUk9SX0xPQ0FMX1ZBUklBQkxFU19fIjtjb25zdCBhPXQ7ZnVuY3Rpb24gcyguLi5lKXthLmRlYnVnJiZmdW5jdGlvbihlKXtpZighKCJjb25zb2xlImluIG4pKXJldHVybiBlKCk7Y29uc3QgdD1uLmNvbnNvbGUsbz17fSxhPU9iamVjdC5rZXlzKGkpO2EuZm9yRWFjaChlPT57Y29uc3Qgbj1pW2VdO29bZV09dFtlXSx0W2VdPW59KTt0cnl7cmV0dXJuIGUoKX1maW5hbGx5e2EuZm9yRWFjaChlPT57dFtlXT1vW2VdfSl9fSgoKT0+Y29uc29sZS5sb2coIltMb2NhbFZhcmlhYmxlcyBXb3JrZXJdIiwuLi5lKSl9YXN5bmMgZnVuY3Rpb24gYyhlLHQsbixpKXtjb25zdCBvPWF3YWl0IGUucG9zdCgiUnVudGltZS5nZXRQcm9wZXJ0aWVzIix7b2JqZWN0SWQ6dCxvd25Qcm9wZXJ0aWVzOiEwfSk7aVtuXT1vLnJlc3VsdC5maWx0ZXIoZT0+Imxlbmd0aCIhPT1lLm5hbWUmJiFpc05hTihwYXJzZUludChlLm5hbWUsMTApKSkuc29ydCgoZSx0KT0+cGFyc2VJbnQoZS5uYW1lLDEwKS1wYXJzZUludCh0Lm5hbWUsMTApKS5tYXAoZT0+ZS52YWx1ZT8udmFsdWUpfWFzeW5jIGZ1bmN0aW9uIHIoZSx0LG4saSl7Y29uc3Qgbz1hd2FpdCBlLnBvc3QoIlJ1bnRpbWUuZ2V0UHJvcGVydGllcyIse29iamVjdElkOnQsb3duUHJvcGVydGllczohMH0pO2lbbl09by5yZXN1bHQubWFwKGU9PltlLm5hbWUsZS52YWx1ZT8udmFsdWVdKS5yZWR1Y2UoKGUsW3Qsbl0pPT4oZVt0XT1uLGUpLHt9KX1mdW5jdGlvbiB1KGUsdCl7ZS52YWx1ZSYmKCJ2YWx1ZSJpbiBlLnZhbHVlP3ZvaWQgMD09PWUudmFsdWUudmFsdWV8fG51bGw9PT1lLnZhbHVlLnZhbHVlP3RbZS5uYW1lXT1gPCR7ZS52YWx1ZS52YWx1ZX0+YDp0W2UubmFtZV09ZS52YWx1ZS52YWx1ZToiZGVzY3JpcHRpb24iaW4gZS52YWx1ZSYmImZ1bmN0aW9uIiE9PWUudmFsdWUudHlwZT90W2UubmFtZV09YDwke2UudmFsdWUuZGVzY3JpcHRpb259PmA6InVuZGVmaW5lZCI9PT1lLnZhbHVlLnR5cGUmJih0W2UubmFtZV09Ijx1bmRlZmluZWQ+IikpfWFzeW5jIGZ1bmN0aW9uIGwoZSx0KXtjb25zdCBuPWF3YWl0IGUucG9zdCgiUnVudGltZS5nZXRQcm9wZXJ0aWVzIix7b2JqZWN0SWQ6dCxvd25Qcm9wZXJ0aWVzOiEwfSksaT17fTtmb3IoY29uc3QgdCBvZiBuLnJlc3VsdClpZih0LnZhbHVlPy5vYmplY3RJZCYmIkFycmF5Ij09PXQudmFsdWUuY2xhc3NOYW1lKXtjb25zdCBuPXQudmFsdWUub2JqZWN0SWQ7YXdhaXQgYyhlLG4sdC5uYW1lLGkpfWVsc2UgaWYodC52YWx1ZT8ub2JqZWN0SWQmJiJPYmplY3QiPT09dC52YWx1ZS5jbGFzc05hbWUpe2NvbnN0IG49dC52YWx1ZS5vYmplY3RJZDthd2FpdCByKGUsbix0Lm5hbWUsaSl9ZWxzZSB0LnZhbHVlJiZ1KHQsaSk7cmV0dXJuIGl9bGV0IGY7KGFzeW5jIGZ1bmN0aW9uKCl7Y29uc3QgdD1uZXcgZTt0LmNvbm5lY3RUb01haW5UaHJlYWQoKSxzKCJDb25uZWN0ZWQgdG8gbWFpbiB0aHJlYWQiKTtsZXQgbj0hMTt0Lm9uKCJEZWJ1Z2dlci5yZXN1bWVkIiwoKT0+e249ITF9KSx0Lm9uKCJEZWJ1Z2dlci5wYXVzZWQiLGU9PntuPSEwLGFzeW5jIGZ1bmN0aW9uKGUse3JlYXNvbjp0LGRhdGE6e29iamVjdElkOm59LGNhbGxGcmFtZXM6aX0pe2lmKCJleGNlcHRpb24iIT09dCYmInByb21pc2VSZWplY3Rpb24iIT09dClyZXR1cm47aWYoZj8uKCksbnVsbD09bilyZXR1cm47Y29uc3QgYT1bXTtmb3IobGV0IHQ9MDt0PGkubGVuZ3RoO3QrKyl7Y29uc3R7c2NvcGVDaGFpbjpuLGZ1bmN0aW9uTmFtZTpvLHRoaXM6c309aVt0XSxjPW4uZmluZChlPT4ibG9jYWwiPT09ZS50eXBlKSxyPSJnbG9iYWwiIT09cy5jbGFzc05hbWUmJnMuY2xhc3NOYW1lP2Ake3MuY2xhc3NOYW1lfS4ke299YDpvO2lmKHZvaWQgMD09PWM/Lm9iamVjdC5vYmplY3RJZClhW3RdPXtmdW5jdGlvbjpyfTtlbHNle2NvbnN0IG49YXdhaXQgbChlLGMub2JqZWN0Lm9iamVjdElkKTthW3RdPXtmdW5jdGlvbjpyLHZhcnM6bn19fWF3YWl0IGUucG9zdCgiUnVudGltZS5jYWxsRnVuY3Rpb25PbiIse2Z1bmN0aW9uRGVjbGFyYXRpb246YGZ1bmN0aW9uKCkgeyB0aGlzLiR7b30gPSB0aGlzLiR7b30gfHwgJHtKU09OLnN0cmluZ2lmeShhKX07IH1gLHNpbGVudDohMCxvYmplY3RJZDpufSksYXdhaXQgZS5wb3N0KCJSdW50aW1lLnJlbGVhc2VPYmplY3QiLHtvYmplY3RJZDpufSl9KHQsZS5wYXJhbXMpLnRoZW4oYXN5bmMoKT0+e24mJmF3YWl0IHQucG9zdCgiRGVidWdnZXIucmVzdW1lIil9LGFzeW5jIGU9PntuJiZhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnJlc3VtZSIpfSl9KSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLmVuYWJsZSIpO2NvbnN0IGk9ITEhPT1hLmNhcHR1cmVBbGxFeGNlcHRpb25zO2lmKGF3YWl0IHQucG9zdCgiRGVidWdnZXIuc2V0UGF1c2VPbkV4Y2VwdGlvbnMiLHtzdGF0ZTppPyJhbGwiOiJ1bmNhdWdodCJ9KSxpKXtjb25zdCBlPWEubWF4RXhjZXB0aW9uc1BlclNlY29uZHx8NTA7Zj1mdW5jdGlvbihlLHQsbil7bGV0IGk9MCxvPTUsYT0wO3JldHVybiBzZXRJbnRlcnZhbCgoKT0+ezA9PT1hP2k+ZSYmKG8qPTIsbihvKSxvPjg2NDAwJiYobz04NjQwMCksYT1vKTooYS09MSwwPT09YSYmdCgpKSxpPTB9LDFlMykudW5yZWYoKSwoKT0+e2krPTF9fShlLGFzeW5jKCk9PntzKCJSYXRlLWxpbWl0IGxpZnRlZC4iKSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zIix7c3RhdGU6ImFsbCJ9KX0sYXN5bmMgZT0+e3MoYFJhdGUtbGltaXQgZXhjZWVkZWQuIERpc2FibGluZyBjYXB0dXJpbmcgb2YgY2F1Z2h0IGV4Y2VwdGlvbnMgZm9yICR7ZX0gc2Vjb25kcy5gKSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zIix7c3RhdGU6InVuY2F1Z2h0In0pfSl9fSkoKS5jYXRjaChlPT57cygiRmFpbGVkIHRvIHN0YXJ0IGRlYnVnZ2VyIixlKX0pLHNldEludGVydmFsKCgpPT57fSwxZTQpOw==";function Z3(...t){g.log("[LocalVariables]",...t)}var ez=((t={})=>{function e(s,i){let a=(s.stacktrace?.frames||[]).filter(c=>c.function!=="new Promise");for(let c=0;c<a.length;c++){let u=a.length-c-1,l=i[c],d=a[u];if(!d||!l)break;l.vars===void 0||d.in_app===!1||!AS(d.function,l.function)||(d.vars=l.vars)}}function n(s,i){if(i.originalException&&typeof i.originalException=="object"&&Bd in i.originalException&&Array.isArray(i.originalException[Bd])){for(let a of s.exception?.values||[])e(a,i.originalException[Bd]);i.originalException[Bd]=void 0}return s}async function r(){let s=await import("node:inspector");s.url()||s.open(0)}function o(s){let i=new Q3.Worker(new URL(`data:application/javascript;base64,${w1e}`),{workerData:s,execArgv:[],env:{...process.env,NODE_OPTIONS:void 0}});process.on("exit",()=>{i.terminate()}),i.once("error",a=>{Z3("Worker error",a)}),i.once("exit",a=>{Z3("Worker exit",a)}),i.unref()}return{name:"LocalVariablesAsync",async setup(s){if(!s.getOptions().includeLocalVariables)return;if(await TS()){g.warn("Local variables capture has been disabled because the debugger was already enabled");return}let a={...t,debug:g.isEnabled()};r().then(()=>{try{o(a)}catch(c){g.error("Failed to start worker",c)}},c=>{g.error("Failed to start inspector",c)})},processEvent(s,i){return n(s,i)}}});function tz(t){if(t!==void 0)return t.slice(-10).reduce((e,n)=>`${e},${n.function},${n.lineno},${n.colno}`,"")}function k1e(t,e){if(e!==void 0)return tz(t(e,1))}function nz(t){let e=[],n=!1;function r(i){e=[],!n&&(n=!0,t(i))}e.push(r);function o(i){e.push(i)}function s(i){let a=e.pop()||r;try{a(i)}catch{r(i)}}return{add:o,next:s}}var BN=class t{constructor(e){this._session=e}static async create(e){if(e)return e;let n=await import("node:inspector");return new t(new n.Session)}configureAndConnect(e,n){this._session.connect(),this._session.on("Debugger.paused",r=>{e(r,()=>{this._session.post("Debugger.resume")})}),this._session.post("Debugger.enable"),this._session.post("Debugger.setPauseOnExceptions",{state:n?"all":"uncaught"})}setPauseOnExceptions(e){this._session.post("Debugger.setPauseOnExceptions",{state:e?"all":"uncaught"})}getLocalVariables(e,n){this._getProperties(e,r=>{let{add:o,next:s}=nz(n);for(let i of r)if(i.value?.objectId&&i.value.className==="Array"){let a=i.value.objectId;o(c=>this._unrollArray(a,i.name,c,s))}else if(i.value?.objectId&&i.value.className==="Object"){let a=i.value.objectId;o(c=>this._unrollObject(a,i.name,c,s))}else i.value&&o(a=>this._unrollOther(i,a,s));s({})})}_getProperties(e,n){this._session.post("Runtime.getProperties",{objectId:e,ownProperties:!0},(r,o)=>{n(r?[]:o.result)})}_unrollArray(e,n,r,o){this._getProperties(e,s=>{r[n]=s.filter(i=>i.name!=="length"&&!isNaN(parseInt(i.name,10))).sort((i,a)=>parseInt(i.name,10)-parseInt(a.name,10)).map(i=>i.value?.value),o(r)})}_unrollObject(e,n,r,o){this._getProperties(e,s=>{r[n]=s.map(i=>[i.name,i.value?.value]).reduce((i,[a,c])=>(i[a]=c,i),{}),o(r)})}_unrollOther(e,n,r){e.value&&("value"in e.value?e.value.value===void 0||e.value.value===null?n[e.name]=`<${e.value.value}>`:n[e.name]=e.value.value:"description"in e.value&&e.value.type!=="function"?n[e.name]=`<${e.value.description}>`:e.value.type==="undefined"&&(n[e.name]="<undefined>")),r(n)}},V1e="LocalVariables",B1e=((t={},e)=>{let n=new yn(20),r,o=!1;function s(a){let c=tz(a.stacktrace?.frames);if(c===void 0)return;let u=n.remove(c);if(u===void 0)return;let l=(a.stacktrace?.frames||[]).filter(d=>d.function!=="new Promise");for(let d=0;d<l.length;d++){let p=l.length-d-1,_=u[d],f=l[p];if(!f||!_)break;_.vars===void 0||f.in_app===!1||!AS(f.function,_.function)||(f.vars=_.vars)}}function i(a){for(let c of a.exception?.values||[])s(c);return a}return{name:V1e,async setupOnce(){let c=K()?.getOptions();if(!c?.includeLocalVariables)return;if(Vd<18){g.log("The `LocalVariables` integration is only supported on Node >= v18.");return}if(await TS()){g.warn("Local variables capture has been disabled because the debugger was already enabled");return}BN.create(e).then(l=>{function d(_,{params:{reason:f,data:E,callFrames:S}},h){if(f!=="exception"&&f!=="promiseRejection"){h();return}r?.();let R=k1e(_,E.description);if(R==null){h();return}let{add:A,next:O}=nz(y=>{n.set(R,y),h()});for(let y=0;y<Math.min(S.length,5);y++){let{scopeChain:M,functionName:I,this:J}=S[y],H=M.find(G=>G.type==="local"),me=J.className==="global"||!J.className?I:`${J.className}.${I}`;if(H?.object.objectId===void 0)A(G=>{G[y]={function:me},O(G)});else{let G=H.object.objectId;A(j=>l.getLocalVariables(G,Ne=>{j[y]={function:me,vars:Ne},O(j)}))}}O([])}let p=t.captureAllExceptions!==!1;if(l.configureAndConnect((_,f)=>d(c.stackParser,_,f),p),p){let _=t.maxExceptionsPerSecond||50;r=J3(_,()=>{g.log("Local variables rate-limit lifted."),l.setPauseOnExceptions(!0)},f=>{g.log(`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${f} seconds.`),l.setPauseOnExceptions(!1)})}o=!0},l=>{g.log("The `LocalVariables` integration failed to start.",l)})},processEvent(a){return o?i(a):a},_getCachedFramesCount(){return n.size},_getFirstCachedFrame(){return n.values()[0]}}}),rz=B1e;var oz=(t={})=>ya.major<19?rz(t):ez(t);var Gd=require("node:fs"),Hd=require("node:path");function mu(){try{return typeof module<"u"&&typeof module.exports<"u"}catch{return!1}}var GN,G1e="Modules",H1e=typeof __SENTRY_SERVER_MODULES__>"u"?{}:__SENTRY_SERVER_MODULES__,$1e=(()=>({name:G1e,processEvent(t){return t.modules={...t.modules,...sz()},t},getModules:sz})),iz=$1e;function F1e(){try{return require.cache?Object.keys(require.cache):[]}catch{return[]}}function j1e(){return{...H1e,...K1e(),...mu()?q1e():{}}}function q1e(){let t=require.main?.paths||[],e=F1e(),n={},r=new Set;return e.forEach(o=>{let s=o,i=()=>{let a=s;if(s=(0,Hd.dirname)(a),!s||a===s||r.has(a))return;if(t.indexOf(s)<0)return i();let c=(0,Hd.join)(a,"package.json");if(r.add(a),!(0,Gd.existsSync)(c))return i();try{let u=JSON.parse((0,Gd.readFileSync)(c,"utf8"));n[u.name]=u.version}catch{}};i()}),n}function sz(){return GN||(GN=j1e()),GN}function Y1e(){try{let t=(0,Hd.join)(process.cwd(),"package.json");return JSON.parse((0,Gd.readFileSync)(t,"utf8"))}catch{return{}}}function K1e(){let t=Y1e();return{...t.dependencies,...t.devDependencies}}var W1e=2e3;function $d(t){qe(()=>{console.error(t)});let e=K();if(e===void 0){_e&&g.warn("No NodeClient was defined, we are exiting the process now."),global.process.exit(1);return}let n=e.getOptions(),r=n?.shutdownTimeout&&n.shutdownTimeout>0?n.shutdownTimeout:W1e;e.close(r).then(o=>{o||_e&&g.warn("We reached the timeout for emptying the request buffer, still exiting now!"),global.process.exit(1)},o=>{_e&&g.error(o)})}var z1e="OnUncaughtException",az=(t={})=>{let e={exitEvenIfOtherHandlersAreRegistered:!1,...t};return{name:z1e,setup(n){global.process.on("uncaughtException",X1e(n,e))}}};function X1e(t,e){let r=!1,o=!1,s=!1,i,a=t.getOptions();return Object.assign(c=>{let u=$d;e.onFatalError?u=e.onFatalError:a.onFatalError&&(u=a.onFatalError);let d=global.process.listeners("uncaughtException").filter(_=>_.name!=="domainUncaughtExceptionClear"&&_.tag!=="sentry_tracingErrorCallback"&&_._errorHandler!==!0).length===0,p=e.exitEvenIfOtherHandlersAreRegistered||d;r?p&&(s?(_e&&g.warn("uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown"),$d(c)):o||(o=!0,setTimeout(()=>{s||(s=!0,u(i,c))},2e3))):(i=c,r=!0,K()===t&&un(c,{originalException:c,captureContext:{level:"fatal"},mechanism:{handled:!1,type:"onuncaughtexception"}}),!s&&p&&(s=!0,u(c)))},{_errorHandler:!0})}var J1e="OnUnhandledRejection",Z1e=((t={})=>{let e={mode:"warn",...t};return{name:J1e,setup(n){global.process.on("unhandledRejection",Q1e(n,e))}}}),cz=Z1e;function Q1e(t,e){return function(r,o){if(K()!==t)return;let s=e.mode==="strict"?"fatal":"error",i=r&&typeof r=="object"?r._sentry_active_span:void 0;(i?c=>hd(i,c):c=>c())(()=>{un(r,{originalException:o,captureContext:{extra:{unhandledPromiseRejection:!0},level:s},mechanism:{handled:!1,type:"onunhandledrejection"}})}),eke(r,e.mode)}}function eke(t,e){let n="This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:";e==="warn"?qe(()=>{console.warn(n),console.error(t&&typeof t=="object"&&"stack"in t?t.stack:t)}):e==="strict"&&(qe(()=>{console.warn(n)}),$d(t))}var uz=v(require("node:http"),1);var HN="Spotlight",tke=((t={})=>{let e={sidecarUrl:t.sidecarUrl||"http://localhost:8969/stream"};return{name:HN,setup(n){try{process.env.NODE_ENV&&process.env.NODE_ENV!=="development"&&g.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?")}catch{}nke(n,e)}}}),lz=tke;function nke(t,e){let n=rke(e.sidecarUrl);if(!n)return;let r=0;t.on("beforeEnvelope",o=>{if(r>3){g.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests");return}let s=fd(o);jc(()=>{let i=uz.request({method:"POST",path:n.pathname,hostname:n.hostname,port:n.port,headers:{"Content-Type":"application/x-sentry-envelope"}},a=>{a.statusCode&&a.statusCode>=200&&a.statusCode<400&&(r=0),a.on("data",()=>{}),a.on("end",()=>{}),a.setEncoding("utf8")});i.on("error",()=>{r++,g.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar")}),i.write(s),i.end()})})}function rke(t){try{return new URL(`${t}`)}catch{g.warn(`[Spotlight] Invalid sidecar URL: ${t}`);return}}var dz=v(require("node:util"),1);var oke="NodeSystemError";function ske(t){return!(t instanceof Error)||!("errno"in t)||typeof t.errno!="number"?!1:dz.getSystemErrorMap().has(t.errno)}var pz=(t={})=>({name:oke,processEvent:(e,n,r)=>{if(!ske(n.originalException))return e;let o=n.originalException,s={...o};!r.getOptions().sendDefaultPii&&t.includePaths!==!0&&(delete s.path,delete s.dest),e.contexts={...e.contexts,node_system_error:s};for(let i of e.exception?.values||[])i.value&&(o.path&&i.value.includes(o.path)&&(i.value=i.value.replace(`'${o.path}'`,"").trim()),o.dest&&i.value.includes(o.dest)&&(i.value=i.value.replace(`'${o.dest}'`,"").trim()));return e}});var $N=v(require("node:diagnostics_channel"),1);var ike="ChildProcess",_z=(t={})=>({name:ike,setup(){$N.channel("child_process").subscribe(e=>{e&&typeof e=="object"&&"process"in e&&ake(e.process,t)}),$N.channel("worker_threads").subscribe(e=>{e&&typeof e=="object"&&"worker"in e&&cke(e.worker,t)})}});function ake(t,e){let n=!1,r;t.on("spawn",()=>{if(t.spawnfile==="/usr/bin/sw_vers"){n=!0;return}r={spawnfile:t.spawnfile},e.includeChildProcessArgs&&(r.spawnargs=t.spawnargs)}).on("exit",o=>{n||(n=!0,o!==null&&o!==0&&Un({category:"child_process",message:`Child process exited with code '${o}'`,level:o===0?"info":"warning",data:r}))}).on("error",o=>{n||(n=!0,Un({category:"child_process",message:`Child process errored with '${o.message}'`,level:"error",data:r}))})}function cke(t,e){let n;t.on("online",()=>{n=t.threadId}).on("error",r=>{e.captureWorkerErrors!==!1?un(r,{mechanism:{type:"instrument",handled:!1,data:{threadId:String(n)}}}):Un({category:"worker_thread",message:`Worker thread errored with '${r.message}'`,level:"error",data:{threadId:n}})})}var Sz=v(Ez(),1);var KN=O3(Sz.AsyncLocalStorageContextManager);x();function WN(){Mn.disable(),Mn.setLogger({error:g.error,warn:g.warn,info:g.log,debug:g.log,verbose:g.log},mt.DEBUG)}var hke="ProcessSession",gz=()=>({name:hke,setupOnce(){oE(),process.on("beforeExit",()=>{Re().getSession()?.status!=="ok"&&Td()})}});var Ake=v(require("node:http"),1),Rke=v(require("node:https"),1),Az=require("node:stream"),Rz=require("node:zlib");var jo=v(require("node:net"),1),XN=v(require("node:tls"),1);var zN=v(require("node:http"),1);var lo=Symbol("AgentBaseInternalState"),NS=class extends zN.Agent{constructor(e){super(e),this[lo]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
172
- `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)};Promise.resolve().then(()=>this.connect(e,o)).then(s=>{if(s instanceof zN.Agent)return s.addRequest(e,o);this[lo].currentSocket=s,super.createSocket(e,n,r)},r)}createConnection(){let e=this[lo].currentSocket;if(this[lo].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[lo].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[lo]&&(this[lo].defaultPort=e)}get protocol(){return this[lo].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[lo]&&(this[lo].protocol=e)}};function CS(...t){g.log("[https-proxy-agent:parse-proxy-response]",...t)}function hz(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let l=t.read();l?u(l):t.once("readable",s)}function i(){t.removeListener("end",a),t.removeListener("error",c),t.removeListener("readable",s)}function a(){i(),CS("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function c(l){i(),CS("onerror %o",l),n(l)}function u(l){o.push(l),r+=l.length;let d=Buffer.concat(o,r),p=d.indexOf(`\r
173
- \r
174
- `);if(p===-1){CS("have not received end of HTTP headers yet..."),s();return}let _=d.subarray(0,p).toString("ascii").split(`\r
175
- `),f=_.shift();if(!f)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let E=f.split(" "),S=+(E[1]||0),h=E.slice(2).join(" "),R={};for(let A of _){if(!A)continue;let O=A.indexOf(":");if(O===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${A}"`));let y=A.slice(0,O).toLowerCase(),M=A.slice(O+1).trimStart(),I=R[y];typeof I=="string"?R[y]=[I,M]:Array.isArray(I)?I.push(M):R[y]=M}CS("got proxy server response: %o %o",f,R),i(),e({connect:{statusCode:S,statusText:h,headers:R},buffered:d})}t.on("error",c),t.on("end",a),s()})}function Fd(...t){g.log("[https-proxy-agent]",...t)}var jd=class extends NS{static __initStatic(){this.protocols=["http","https"]}constructor(e,n){super(n),this.options={},this.proxy=typeof e=="string"?new URL(e):e,this.proxyHeaders=n?.headers??{},Fd("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Tz(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;if(r.protocol==="https:"){Fd("Creating `tls.Socket`: %o",this.connectOpts);let p=this.connectOpts.servername||this.connectOpts.host;o=XN.connect({...this.connectOpts,servername:p&&jo.isIP(p)?void 0:p})}else Fd("Creating `net.Socket`: %o",this.connectOpts),o=jo.connect(this.connectOpts);let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=jo.isIPv6(n.host)?`[${n.host}]`:n.host,a=`CONNECT ${i}:${n.port} HTTP/1.1\r
176
- `;if(r.username||r.password){let p=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(p).toString("base64")}`}s.Host=`${i}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let p of Object.keys(s))a+=`${p}: ${s[p]}\r
177
- `;let c=hz(o);o.write(`${a}\r
178
- `);let{connect:u,buffered:l}=await c;if(e.emit("proxyConnect",u),this.emit("proxyConnect",u,e),u.statusCode===200){if(e.once("socket",Tke),n.secureEndpoint){Fd("Upgrading socket connection to TLS");let p=n.servername||n.host;return XN.connect({...Tz(n,"host","path","port"),socket:o,servername:jo.isIP(p)?void 0:p})}return o}o.destroy();let d=new jo.Socket({writable:!1});return d.readable=!0,e.once("socket",p=>{Fd("Replaying proxy buffer for failed request"),p.push(l),p.push(null)}),d}};jd.__initStatic();function Tke(t){t.resume()}function Tz(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}var yke=1024*32;function Oke(t){return new Az.Readable({read(){this.push(t),this.push(null)}})}function yz(t){let e;try{e=new URL(t.url)}catch{return qe(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),Rd(t,()=>Promise.resolve({}))}let n=e.protocol==="https:",r=Nke(e,t.proxy||(n?process.env.https_proxy:void 0)||process.env.http_proxy),o=n?Rke:Ake,s=t.keepAlive===void 0?!1:t.keepAlive,i=r?new jd(r):new o.Agent({keepAlive:s,maxSockets:30,timeout:2e3}),a=Cke(t,t.httpModule??o,i);return Rd(t,a)}function Nke(t,e){let{no_proxy:n}=process.env;if(!n?.split(",").some(o=>t.host.endsWith(o)||t.hostname.endsWith(o)))return e}function Cke(t,e,n){let{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(u){return new Promise((l,d)=>{jc(()=>{let p=Oke(u.body),_={...t.headers};u.body.length>yke&&(_["content-encoding"]="gzip",p=p.pipe((0,Rz.createGzip)()));let f=e.request({method:"POST",agent:n,headers:_,hostname:r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},E=>{E.on("data",()=>{}),E.on("end",()=>{}),E.setEncoding("utf8");let S=E.headers["retry-after"]??null,h=E.headers["x-sentry-rate-limits"]??null;l({statusCode:E.statusCode,headers:{"retry-after":S,"x-sentry-rate-limits":Array.isArray(h)?h[0]||null:h}})});f.on("error",d),p.pipe(f)})})}}var vke=new Set(["false","f","n","no","off","0"]),Ike=new Set(["true","t","y","yes","on","1"]);function vS(t,e){let n=String(t).toLowerCase();return vke.has(n)?!1:Ike.has(n)?!0:e?.strict?null:!!t}var IS=require("node:path");function Oz(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function Nz(t=process.argv[1]?Yy(process.argv[1]):process.cwd(),e=IS.sep==="\\"){let n=e?Oz(t):t;return r=>{if(!r)return;let o=e?Oz(r):r,{dir:s,base:i,ext:a}=IS.posix.parse(o);(a===".js"||a===".mjs"||a===".cjs")&&(i=i.slice(0,a.length*-1));let c=decodeURIComponent(i);s||(s=".");let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${c}`;if(s.startsWith(n)){let l=s.slice(n.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function Cz(t){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(te.SENTRY_RELEASE?.id)return te.SENTRY_RELEASE.id;let e=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,n=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,r=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return e||n||r||t}var vz=Pm(nO(Nz()));var Iz=v(require("node:os"),1);x();var Pz=v(fe(),1);var bS=require("worker_threads");var Pke=6e4,PS=class extends Ad{constructor(e){let n=e.includeServerName===!1?void 0:e.serverName||global.process.env.SENTRY_NAME||Iz.hostname(),r={...e,platform:"node",runtime:{name:"node",version:global.process.version},serverName:n};e.openTelemetryInstrumentations&&(0,Pz.registerInstrumentations)({instrumentations:e.openTelemetryInstrumentations}),fa(r,"node"),g.log(`Initializing Sentry: process: ${process.pid}, thread: ${bS.isMainThread?"main":`worker-${bS.threadId}`}.`),super(r);let{enableLogs:o,_experiments:s}=this.getOptions();(o??s?.enableLogs)&&(this._logOnExitFlushListener=()=>{_a(this)},n&&this.on("beforeCaptureLog",a=>{a.attributes={...a.attributes,"server.address":n}}),process.on("beforeExit",this._logOnExitFlushListener))}get tracer(){if(this._tracer)return this._tracer;let e="@sentry/node",n=Pe,r=oe.getTracer(e,n);return this._tracer=r,r}async flush(e){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(e)}close(e){return this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._logOnExitFlushListener&&process.off("beforeExit",this._logOnExitFlushListener),super.close(e)}startClientReportTracking(){let e=this.getOptions();e.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{_e&&g.log("Flushing client reports based on interval."),this._flushOutcomes()},e.clientReportFlushInterval??Pke).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_getTraceInfoFromScope(e){return e?A3(this,e):[void 0,void 0]}};var bz=v(hm(),1),Mz=v(require("module"),1),bke={};function Lz(){let[t=0,e=0]=process.versions.node.split(".").map(Number);if(t>=21||t===20&&e>=6||t===18&&e>=19){if(!te._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:n}=(0,bz.createAddHookMessageChannel)();Mz.default.register("import-in-the-middle/hook.mjs",bke.url,{data:{addHookMessagePort:n,include:[]},transferList:[n]})}catch(n){g.warn("Failed to register ESM hook",n)}}else qe(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function MS(){return[dE(),uE(),pE(),_E(),pz(),fE(),L3(),k3(),az(),cz(),z3(),oz(),H3(),_z(),gz(),iz()]}function JN(t={}){return Mke(t,MS)}function Mke(t={},e){let n=Lke(t,e);n.debug===!0&&(_e?g.enable():qe(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")})),!mu()&&n.registerEsmLoaderHooks!==!1&&Lz(),y3(),ue().update(n.initialScope),n.spotlight&&!n.integrations.some(({name:s})=>s===HN)&&n.integrations.push(lz({sidecarUrl:typeof n.spotlight=="string"?n.spotlight:void 0})),fa(n,"node-core");let o=new PS(n);return ue().setClient(o),o.init(),g.log(`Running in ${mu()?"CommonJS":"ESM"} mode.`),o.startClientReportTracking(),Uke(),p3(o),R3(o),o}function ZN(){if(!_e)return;let t=E3(),e=["SentryContextManager","SentryPropagator"];vt()&&e.push("SentrySpanProcessor");for(let n of e)t.includes(n)||g.error(`You have to set up the ${n}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);t.includes("SentrySampler")||g.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function Lke(t,e){let n=xke(t.release),r=t.spotlight??vS(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,o=Dke(t.tracesSampleRate),s={...t,dsn:t.dsn??process.env.SENTRY_DSN,environment:t.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:t.sendClientReports??!0,transport:t.transport??yz,stackParser:QR(t.stackParser||vz),release:n,tracesSampleRate:o,spotlight:r,debug:vS(t.debug??process.env.SENTRY_DEBUG)},i=t.integrations,a=t.defaultIntegrations??e(s);return{...s,integrations:Uy({defaultIntegrations:a,integrations:i})}}function xke(t){if(t!==void 0)return t;let e=Cz();if(e!==void 0)return e}function Dke(t){if(t!==void 0)return t;let e=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!e)return;let n=parseFloat(e);return isFinite(n)?n:void 0}function Uke(){if(vS(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let t=process.env.SENTRY_TRACE,e=process.env.SENTRY_BAGGAGE,n=dd(t,e);ue().setPropagationContext(n)}}function xe(t,e){t.setAttribute(ye,e)}var QN="Http",xz="@opentelemetry_sentry-patched/instrumentation-http",wke=q(`${QN}.sentry`,t=>new Ra(t)),kke=q(QN,t=>{let e=new Dz.HttpInstrumentation(t);try{e._diag=Mn.createComponentLogger({namespace:xz}),e.instrumentationName=xz}catch{}return e});function Vke(t,e={}){return typeof t.spans=="boolean"?t.spans:!(e.skipOpenTelemetrySetup||!vt(e)&&ya.major>=22)}var Uz=(t={})=>{let e=t.dropSpansForIncomingRequestStatusCodes??[[401,404],[300,399]];return{name:QN,setupOnce(){let n=Vke(t,K()?.getOptions());if(wke({...t,extractIncomingTraceFromHeader:!n,propagateTraceInOutgoingRequests:!n}),n){let r=Hke(t);kke(r)}},processEvent(n){if(n.type==="transaction"){let r=n.contexts?.trace?.data?.["http.response.status_code"];if(typeof r=="number"&&e.some(o=>{if(typeof o=="number")return o===r;let[s,i]=o;return r>=s&&r<=i}))return null}return n}}};function Bke(t){return"outputData"in t&&"outputSize"in t&&!("client"in t)&&!("statusCode"in t)}function Gke(t){return t.headers["next-router-prefetch"]==="1"}function Hke(t={}){return{...t.instrumentation?._experimentalConfig,disableIncomingRequestInstrumentation:t.disableIncomingRequestSpans,ignoreOutgoingRequestHook:n=>{let r=_u(n);if(!r)return!1;let o=t.ignoreOutgoingRequests;return!!o?.(r,n)},ignoreIncomingRequestHook:n=>{let r=n.url,o=n.method?.toUpperCase();if(o==="OPTIONS"||o==="HEAD")return!0;let s=t.ignoreIncomingRequests;return!!(r&&s?.(r,n))},requireParentforOutgoingSpans:!1,requireParentforIncomingSpans:!1,requestHook:(n,r)=>{xe(n,"auto.http.otel.http"),!Bke(r)&&Gke(r)&&n.setAttribute("sentry.http.prefetch",!0),t.instrumentation?.requestHook?.(n,r)},responseHook:(n,r)=>{t.instrumentation?.responseHook?.(n,r)},applyCustomAttributesOnSpan:(n,r,o)=>{t.instrumentation?.applyCustomAttributesOnSpan?.(n,r,o)}}}var jz=v(Fz(),1);var qz="NodeFetch",jke=q(qz,jz.UndiciInstrumentation,t=>zke(t)),qke=q(`${qz}.sentry`,Oa,t=>t),Yke=((t={})=>({name:"NodeFetch",setupOnce(){Wke(t,K()?.getOptions())&&jke(t),qke(t)}})),Yz=Yke;function Kke(t,e="/"){let n=`${t}`;return n.endsWith("/")&&e.startsWith("/")?`${n}${e.slice(1)}`:!n.endsWith("/")&&!e.startsWith("/")?`${n}/${e.slice(1)}`:`${n}${e}`}function Wke(t,e={}){return typeof t.spans=="boolean"?t.spans:!e.skipOpenTelemetrySetup&&vt(e)}function zke(t={}){return{requireParentforSpans:!1,ignoreRequestHook:n=>{let r=Kke(n.origin,n.path),o=t.ignoreOutgoingRequests;return!!(o&&r&&o(r))},startSpanHook:()=>({[ye]:"auto.http.otel.node_fetch"})}}var uX=v(rX(),1);var _o=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;x();var HS=v(Se(),1),fo=v(fe(),1);ve();var sr;(function(t){let e="express.type";t.EXPRESS_TYPE=e;let n="express.name";t.EXPRESS_NAME=n})(sr||(sr={}));var qo;(function(t){let e="router";t.ROUTER=e;let n="middleware";t.MIDDLEWARE=n;let r="request_handler";t.REQUEST_HANDLER=r})(qo||(qo={}));var sC=Symbol("express-layer-patched"),Js="__ot_middlewares";var sX=(t,e)=>{Array.isArray(t[Js])===!1&&Object.defineProperty(t,Js,{enumerable:!1,value:[]}),e!==void 0&&t[Js].push(e)},iX=(t,e)=>{let n=e.handle?.stack?.[0];return n?.route?.path?`${t}${n.route.path}`:n?.handle?.stack?iX(t,n):t},aX=(t,e,n)=>{if(e.name==="router"){let r=iX("",e),o=r||n||t||"/";return{attributes:{[sr.EXPRESS_NAME]:o,[sr.EXPRESS_TYPE]:qo.ROUTER},name:`router - ${o}`}}else return e.name==="bound dispatch"||e.name==="handle"?{attributes:{[sr.EXPRESS_NAME]:(t||n)??"request handler",[sr.EXPRESS_TYPE]:qo.REQUEST_HANDLER},name:`request handler${e.path?` - ${t||n}`:""}`}:{attributes:{[sr.EXPRESS_NAME]:e.name,[sr.EXPRESS_TYPE]:qo.MIDDLEWARE},name:`middleware - ${e.name}`}},aVe=(t,e)=>{if(typeof e=="string")return e===t;if(e instanceof RegExp)return e.test(t);if(typeof e=="function")return e(t);throw new TypeError("Pattern is in unsupported datatype")},cX=(t,e,n)=>{if(Array.isArray(n?.ignoreLayersType)&&n?.ignoreLayersType?.includes(e))return!0;if(Array.isArray(n?.ignoreLayers)===!1)return!1;try{for(let r of n.ignoreLayers)if(aVe(t,r))return!0}catch{}return!1},iC=t=>t instanceof Error?[t,t.message]:[String(t),String(t)],BS=t=>{let e=t[0];return Array.isArray(e)?e.map(n=>oX(n)||"").join(","):oX(e)},oX=t=>{if(typeof t=="string")return t;if(t instanceof RegExp||typeof t=="number")return t.toString()};var cVe="0.1.0",uVe="@sentry/instrumentation-express-v5",GS=class extends fo.InstrumentationBase{constructor(e={}){super(uVe,cVe,e)}init(){return[new fo.InstrumentationNodeModuleDefinition("express",[">=5.0.0"],e=>this._setup(e),e=>this._tearDown(e))]}_setup(e){let n=e.Router.prototype;return(0,fo.isWrapped)(n.route)&&this._unwrap(n,"route"),this._wrap(n,"route",this._getRoutePatch()),(0,fo.isWrapped)(n.use)&&this._unwrap(n,"use"),this._wrap(n,"use",this._getRouterUsePatch()),(0,fo.isWrapped)(e.application.use)&&this._unwrap(e.application,"use"),this._wrap(e.application,"use",this._getAppUsePatch()),e}_tearDown(e){if(e===void 0)return;let n=e.Router.prototype;this._unwrap(n,"route"),this._unwrap(n,"use"),this._unwrap(e.application,"use")}_getRoutePatch(){let e=this;return function(n){return function(...o){let s=n.apply(this,o),i=this.stack[this.stack.length-1];return e._applyPatch(i,BS(o)),s}}}_getRouterUsePatch(){let e=this;return function(n){return function(...o){let s=n.apply(this,o),i=this.stack[this.stack.length-1];return e._applyPatch(i,BS(o)),s}}}_getAppUsePatch(){let e=this;return function(n){return function(...o){let s=this.router,i=n.apply(this,o);if(s){let a=s.stack[s.stack.length-1];e._applyPatch(a,BS(o))}return i}}}_applyPatch(e,n){let r=this;e[sC]!==!0&&(e[sC]=!0,this._wrap(e,"handle",o=>{if(o.length===4)return o;let s=function(i,a){sX(i,n);let c=i[Js].filter(y=>y!=="/"&&y!=="/*").join("").replace(/\/{2,}/g,"/"),u=c.length>0?c:void 0,l={[vd]:u},d=aX(c,e,n),p=d.attributes[sr.EXPRESS_TYPE],_=(0,HS.getRPCMetadata)(X.active());if(_?.type===HS.RPCType.HTTP&&(_.route=u),cX(d.name,p,r.getConfig()))return p===qo.MIDDLEWARE&&i[Js].pop(),o.apply(this,arguments);if(oe.getSpan(X.active())===void 0)return o.apply(this,arguments);let f=r._getSpanName({request:i,layerType:p,route:c},d.name),E=r.tracer.startSpan(f,{attributes:Object.assign(l,d.attributes)}),{requestHook:S}=r.getConfig();S&&(0,fo.safeExecuteInTheMiddle)(()=>S(E,{request:i,layerType:p,route:c}),y=>{y&&Mn.error("express instrumentation: request hook failed",y)},!0);let h=!1;d.attributes[sr.EXPRESS_TYPE]!==qo.MIDDLEWARE&&(E.end(),h=!0);let R=()=>{h===!1&&(h=!0,E.end())},A=Array.from(arguments),O=A.findIndex(y=>typeof y=="function");O>=0&&(arguments[O]=function(){let y=arguments[0],M=![void 0,null,"route","router"].includes(y);if(!h&&M){let[J,H]=iC(y);E.recordException(J),E.setStatus({code:Me.ERROR,message:H})}return h===!1&&(h=!0,i.res?.removeListener("finish",R),E.end()),i.route&&M||i[Js].pop(),A[O].apply(this,arguments)});try{return o.apply(this,arguments)}catch(y){let[M,I]=iC(y);throw E.recordException(M),E.setStatus({code:Me.ERROR,message:I}),y}finally{h||a.once("finish",R)}};for(let i in o)Object.defineProperty(s,i,{get(){return o[i]},set(a){o[i]=a}});return s}))}_getSpanName(e,n){let{spanNameHook:r}=this.getConfig();if(!(r instanceof Function))return n;try{return r(e,n)??n}catch(o){return Mn.error("express instrumentation: error calling span name rewrite hook",o),n}}};var lX="Express",lVe="Express-V5";function dX(t){xe(t,"auto.http.otel.express");let e=W(t).data,n=e["express.type"];n&&t.setAttribute(se,`${n}.express`);let r=e["express.name"];typeof r=="string"&&t.updateName(r)}function pX(t,e){if(Re()===Qr())return _o&&g.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),e;if(t.layerType==="request_handler"){let n=t.request,r=n.method?n.method.toUpperCase():"GET";Re().setTransactionName(`${r} ${t.route}`)}return e}var _X=q(lX,()=>new uX.ExpressInstrumentation({requestHook:t=>dX(t),spanNameHook:(t,e)=>pX(t,e)})),fX=q(lVe,()=>new GS({requestHook:t=>dX(t),spanNameHook:(t,e)=>pX(t,e)})),dVe=(()=>({name:lX,setupOnce(){_X(),fX()}})),cC=dVe;var EC=v(require("node:diagnostics_channel"),1);var fC=v(require("node:diagnostics_channel"),1);x();var qS=v(Se(),1),qX=v(fe(),1);ve();var wX=v(vX(),1);var Jd=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var hVe={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Zd=t=>t.replace(/[[\]\\-]/g,"\\$&"),TVe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),IX=t=>t.join(""),PX=(t,e)=>{let n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],o=[],s=n+1,i=!1,a=!1,c=!1,u=!1,l=n,d="";e:for(;s<t.length;){let E=t.charAt(s);if((E==="!"||E==="^")&&s===n+1){u=!0,s++;continue}if(E==="]"&&i&&!c){l=s+1;break}if(i=!0,E==="\\"&&!c){c=!0,s++;continue}if(E==="["&&!c){for(let[S,[h,R,A]]of Object.entries(hVe))if(t.startsWith(S,s)){if(d)return["$.",!1,t.length-n,!0];s+=S.length,A?o.push(h):r.push(h),a=a||R;continue e}}if(c=!1,d){E>d?r.push(Zd(d)+"-"+Zd(E)):E===d&&r.push(Zd(E)),d="",s++;continue}if(t.startsWith("-]",s+1)){r.push(Zd(E+"-")),s+=2;continue}if(t.startsWith("-",s+1)){d=E,s+=2;continue}r.push(Zd(E)),s++}if(l<s)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,t.length-n,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!u){let E=r[0].length===2?r[0].slice(-1):r[0];return[TVe(E),!1,l-n,!1]}let p="["+(u?"^":"")+IX(r)+"]",_="["+(u?"":"^")+IX(o)+"]";return[r.length&&o.length?"("+p+"|"+_+")":r.length?p:_,a,l-n,!0]};var Zs=(t,{windowsPathsNoEscape:e=!1}={})=>e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Nn,AVe=new Set(["!","?","+","*","@"]),dC=t=>AVe.has(t),bX=t=>dC(t.type),RVe=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),yVe=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),OVe=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),MX=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),NVe="(?!(?:^|/)\\.\\.?(?:$|/))",$S="(?!\\.)",CVe=new Set(["[","."]),vVe=new Set(["..","."]),IVe=new Set("().*{}+?[]^$\\!"),PVe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pC="[^/]",LX=pC+"*?",xX=pC+"+?",Ca=class{type;#n;#r;#o=!1;#e=[];#t;#a;#u;#c=!1;#s;#i;#l=!1;constructor(e,n,r={}){this.type=e,e&&(this.#r=!0),this.#t=n,this.#n=this.#t?this.#t.#n:this,this.#s=this.#n===this?r:this.#n.#s,this.#u=this.#n===this?[]:this.#n.#u,e==="!"&&!this.#n.#c&&this.#u.push(this),this.#a=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#e)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#i!==void 0?this.#i:this.type?this.#i=this.type+"("+this.#e.map(e=>String(e)).join("|")+")":this.#i=this.#e.map(e=>String(e)).join("")}#S(){if(this!==this.#n)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let e;for(;e=this.#u.pop();){if(e.type!=="!")continue;let n=e,r=n.#t;for(;r;){for(let o=n.#a+1;!r.type&&o<r.#e.length;o++)for(let s of e.#e){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(r.#e[o])}n=r,r=n.#t}}return this}push(...e){for(let n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof Nn&&n.#t===this))throw new Error("invalid part: "+n);this.#e.push(n)}}toJSON(){let e=this.type===null?this.#e.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#e.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#c&&this.#t?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#t?.isStart())return!1;if(this.#a===0)return!0;let e=this.#t;for(let n=0;n<this.#a;n++){let r=e.#e[n];if(!(r instanceof Nn&&r.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#t?.type==="!")return!0;if(!this.#t?.isEnd())return!1;if(!this.type)return this.#t?.isEnd();let e=this.#t?this.#t.#e.length:0;return this.#a===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let n=new Nn(this.type,e);for(let r of this.#e)n.copyIn(r);return n}static#d(e,n,r,o,s){let i=o.maxExtglobRecursion??2,a=!1,c=!1,u=-1,l=!1;if(n.type===null){let E=r,S="";for(;E<e.length;){let h=e.charAt(E++);if(a||h==="\\"){a=!a,S+=h;continue}if(c){E===u+1?(h==="^"||h==="!")&&(l=!0):h==="]"&&!(E===u+2&&l)&&(c=!1),S+=h;continue}else if(h==="["){c=!0,u=E,l=!1,S+=h;continue}if(!o.noext&&dC(h)&&e.charAt(E)==="("&&s<=i){n.push(S),S="";let A=new Nn(h,n);E=Nn.#d(e,A,E,o,s+1),n.push(A);continue}S+=h}return n.push(S),E}let d=r+1,p=new Nn(null,n),_=[],f="";for(;d<e.length;){let E=e.charAt(d++);if(a||E==="\\"){a=!a,f+=E;continue}if(c){d===u+1?(E==="^"||E==="!")&&(l=!0):E==="]"&&!(d===u+2&&l)&&(c=!1),f+=E;continue}else if(E==="["){c=!0,u=d,l=!1,f+=E;continue}if(dC(E)&&e.charAt(d)==="("&&(s<=i||n&&n.#p(E))){let h=n&&n.#p(E)?0:1;p.push(f),f="";let R=new Nn(E,p);p.push(R),d=Nn.#d(e,R,d,o,s+h);continue}if(E==="|"){p.push(f),f="",_.push(p),p=new Nn(null,n);continue}if(E===")")return f===""&&n.#e.length===0&&(n.#l=!0),p.push(f),f="",n.push(..._,p),d;f+=E}return n.type=null,n.#r=void 0,n.#e=[e.substring(r-1)],d}#g(e){return this.#f(e,yVe)}#f(e,n=RVe){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null)return!1;let r=e.#e[0];return!r||typeof r!="object"||r.type===null?!1:this.#p(r.type,n)}#p(e,n=OVe){return!!n.get(this.type)?.includes(e)}#h(e,n){let r=e.#e[0],o=new Nn(null,r,this.options);o.#e.push(""),r.push(o),this.#m(e,n)}#m(e,n){let r=e.#e[0];this.#e.splice(n,1,...r.#e);for(let o of r.#e)typeof o=="object"&&(o.#t=this);this.#i=void 0}#T(e){return!!MX.get(this.type)?.has(e)}#A(e){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null||this.#e.length!==1)return!1;let n=e.#e[0];return!n||typeof n!="object"||n.type===null?!1:this.#T(n.type)}#R(e){let n=MX.get(this.type),r=e.#e[0],o=n?.get(r.type);if(!o)return!1;this.#e=r.#e;for(let s of this.#e)typeof s=="object"&&(s.#t=this);this.type=o,this.#i=void 0,this.#l=!1}#_(){if(bX(this)){let e=0,n=!1;do{n=!0;for(let r=0;r<this.#e.length;r++){let o=this.#e[r];typeof o=="object"&&(o.#_(),this.#f(o)?(n=!1,this.#m(o,r)):this.#g(o)?(n=!1,this.#h(o,r)):this.#A(o)&&(n=!1,this.#R(o)))}}while(!n&&++e<10)}else for(let e of this.#e)typeof e=="object"&&e.#_();this.#i=void 0}static fromGlob(e,n={}){let r=new Nn(null,void 0,n);return Nn.#d(e,r,0,n,0),r}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[n,r,o,s]=this.toRegExpSource();if(!(o||this.#r||this.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let a=(this.#s.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${n}$`,a),{_src:n,_glob:e})}get options(){return this.#s}toRegExpSource(e){let n=e??!!this.#s.dot;if(this.#n===this&&(this.#_(),this.#S()),!bX(this)){let c=this.isStart()&&this.isEnd(),u=this.#e.map(_=>{let[f,E,S,h]=typeof _=="string"?Nn.#y(_,this.#r,c):_.toRegExpSource(e);return this.#r=this.#r||S,this.#o=this.#o||h,f}).join(""),l="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&vVe.has(this.#e[0]))){let f=CVe,E=n&&f.has(u.charAt(0))||u.startsWith("\\.")&&f.has(u.charAt(2))||u.startsWith("\\.\\.")&&f.has(u.charAt(4)),S=!n&&!e&&f.has(u.charAt(0));l=E?NVe:S?$S:""}let d="";return this.isEnd()&&this.#n.#c&&this.#t?.type==="!"&&(d="(?:$|\\/)"),[l+u+d,Zs(u),this.#r=!!this.#r,this.#o]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#E(n);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let c=this.toString(),u=this;return u.#e=[c],u.type=null,u.#r=void 0,[c,Zs(this.toString()),!1,!1]}let i=!r||e||n||!$S?"":this.#E(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let a="";if(this.type==="!"&&this.#l)a=(this.isStart()&&!n?$S:"")+xX;else{let c=this.type==="!"?"))"+(this.isStart()&&!n&&!e?$S:"")+LX+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;a=o+s+c}return[a,Zs(s),this.#r=!!this.#r,this.#o]}#E(e){return this.#e.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,o,s,i]=n.toRegExpSource(e);return this.#o=this.#o||i,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#y(e,n,r=!1){let o=!1,s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e.charAt(c);if(o){o=!1,s+=(IVe.has(u)?"\\":"")+u,a=!1;continue}if(u==="\\"){c===e.length-1?s+="\\\\":o=!0;continue}if(u==="["){let[l,d,p,_]=PX(e,c);if(p){s+=l,i=i||d,c+=p-1,n=n||_,a=!1;continue}}if(u==="*"){if(a)continue;a=!0,s+=r&&/^[*]+$/.test(e)?xX:LX,n=!0;continue}else a=!1;if(u==="?"){s+=pC,n=!0;continue}s+=PVe(u)}return[s,Zs(e),!!n,i]}};Nn=Ca;var _C=(t,{windowsPathsNoEscape:e=!1}={})=>e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var wt=(t,e,n={})=>(Jd(e),!n.nocomment&&e.charAt(0)==="#"?!1:new Ru(e,n).match(t)),bVe=/^\*+([^+@!?\*\[\(]*)$/,MVe=t=>e=>!e.startsWith(".")&&e.endsWith(t),LVe=t=>e=>e.endsWith(t),xVe=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),DVe=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),UVe=/^\*+\.\*+$/,wVe=t=>!t.startsWith(".")&&t.includes("."),kVe=t=>t!=="."&&t!==".."&&t.includes("."),VVe=/^\.\*+$/,BVe=t=>t!=="."&&t!==".."&&t.startsWith("."),GVe=/^\*+$/,HVe=t=>t.length!==0&&!t.startsWith("."),$Ve=t=>t.length!==0&&t!=="."&&t!=="..",FVe=/^\?+([^+@!?\*\[\(]*)?$/,jVe=([t,e=""])=>{let n=kX([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},qVe=([t,e=""])=>{let n=VX([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},YVe=([t,e=""])=>{let n=VX([t]);return e?r=>n(r)&&r.endsWith(e):n},KVe=([t,e=""])=>{let n=kX([t]);return e?r=>n(r)&&r.endsWith(e):n},kX=([t])=>{let e=t.length;return n=>n.length===e&&!n.startsWith(".")},VX=([t])=>{let e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},BX=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",DX={win32:{sep:"\\"},posix:{sep:"/"}},WVe=BX==="win32"?DX.win32.sep:DX.posix.sep;wt.sep=WVe;var Qt=Symbol("globstar **");wt.GLOBSTAR=Qt;var zVe="[^/]",XVe=zVe+"*?",JVe="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",ZVe="(?:(?!(?:\\/|^)\\.).)*?",QVe=(t,e={})=>n=>wt(n,t,e);wt.filter=QVe;var ir=(t,e={})=>Object.assign({},t,e),eBe=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return wt;let e=wt;return Object.assign((r,o,s={})=>e(r,o,ir(t,s)),{Minimatch:class extends e.Minimatch{constructor(o,s={}){super(o,ir(t,s))}static defaults(o){return e.defaults(ir(t,o)).Minimatch}},AST:class extends e.AST{constructor(o,s,i={}){super(o,s,ir(t,i))}static fromGlob(o,s={}){return e.AST.fromGlob(o,ir(t,s))}},unescape:(r,o={})=>e.unescape(r,ir(t,o)),escape:(r,o={})=>e.escape(r,ir(t,o)),filter:(r,o={})=>e.filter(r,ir(t,o)),defaults:r=>e.defaults(ir(t,r)),makeRe:(r,o={})=>e.makeRe(r,ir(t,o)),braceExpand:(r,o={})=>e.braceExpand(r,ir(t,o)),match:(r,o,s={})=>e.match(r,o,ir(t,s)),sep:e.sep,GLOBSTAR:Qt})};wt.defaults=eBe;var GX=(t,e={})=>(Jd(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:(0,wX.default)(t));wt.braceExpand=GX;var tBe=(t,e={})=>new Ru(t,e).makeRe();wt.makeRe=tBe;var nBe=(t,e,n={})=>{let r=new Ru(e,n);return t=t.filter(o=>r.match(o)),r.options.nonull&&!t.length&&t.push(e),t};wt.match=nBe;var UX=/[?*]|[+@!]\(.*?\)|\[|\]/,rBe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ru=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,n={}){Jd(e),n=n||{},this.options=n,this.maxGlobstarRecursion=n.maxGlobstarRecursion??200,this.pattern=e,this.platform=n.platform||BX,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,i,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=s[0]===""&&s[1]===""&&(s[2]==="?"||!UX.test(s[2]))&&!UX.test(s[3]),u=/^[a-z]:/i.test(s[0]);if(c)return[...s.slice(0,4),...s.slice(4).map(l=>this.parse(l))];if(u)return[s[0],...s.slice(1).map(l=>this.parse(l))]}return s.map(c=>this.parse(c))});if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let i=this.set[s];i[0]===""&&i[1]===""&&this.globParts[s][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let o=r;for(;n[o+1]==="**";)o++;o!==r&&n.splice(r,o-r)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((r,o)=>{let s=r[r.length-1];return o==="**"&&s==="**"?r:o===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(o),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let s=e[o];o===1&&s===""&&e[0]===""||(s==="."||s==="")&&(n=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(n=!0,e.splice(r-1,2),r-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let i=o;for(;r[i+1]==="**";)i++;i>o&&r.splice(o+1,i-o);let a=r[o+1],c=r[o+2],u=r[o+3];if(a!==".."||!c||c==="."||c===".."||!u||u==="."||u==="..")continue;n=!0,r.splice(o,1);let l=r.slice(0);l[o]="**",e.push(l),o--}if(!this.preserveMultipleSlashes){for(let i=1;i<r.length-1;i++){let a=r[i];i===1&&a===""&&r[0]===""||(a==="."||a==="")&&(n=!0,r.splice(i,1),i--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let i=r[s-1];if(i&&i!=="."&&i!==".."&&i!=="**"){n=!0;let c=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...c),r.length===0&&r.push(""),s-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let r=n+1;r<e.length;r++){let o=this.partsMatch(e[n],e[r],!this.preserveMultipleSlashes);if(o){e[n]=[],e[r]=o;break}}return e.filter(n=>n.length)}partsMatch(e,n,r=!1){let o=0,s=0,i=[],a="";for(;o<e.length&&s<n.length;)if(e[o]===n[s])i.push(a==="b"?n[s]:e[o]),o++,s++;else if(r&&e[o]==="**"&&n[s]===e[o+1])i.push(e[o]),o++;else if(r&&n[s]==="**"&&e[o]===n[s+1])i.push(n[s]),s++;else if(e[o]==="*"&&n[s]&&(this.options.dot||!n[s].startsWith("."))&&n[s]!=="**"){if(a==="b")return!1;a="a",i.push(e[o]),o++,s++}else if(n[s]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(a==="a")return!1;a="b",i.push(n[s]),o++,s++}else return!1;return e.length===n.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,n=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)n=!n,r++;r&&(this.pattern=e.slice(r)),this.negate=n}matchOne(e,n,r=!1){let o=0,s=0;if(this.isWindows){let a=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),c=!a&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),u=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),l=!u&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),d=c?3:a?0:void 0,p=l?3:u?0:void 0;if(typeof d=="number"&&typeof p=="number"){let[_,f]=[e[d],n[p]];_.toLowerCase()===f.toLowerCase()&&(n[p]=_,s=p,o=d)}}let{optimizationLevel:i=1}=this.options;return i>=2&&(e=this.levelTwoFileOptimize(e)),n.includes(Qt)?this.#n(e,n,r,o,s):this.#o(e,n,r,o,s)}#n(e,n,r,o,s){let i=n.indexOf(Qt,s),a=n.lastIndexOf(Qt),[c,u,l]=r?[n.slice(s,i),n.slice(i+1),[]]:[n.slice(s,i),n.slice(i+1,a),n.slice(a+1)];if(c.length){let R=e.slice(o,o+c.length);if(!this.#o(R,c,r,0,0))return!1;o+=c.length}let d=0;if(l.length){if(l.length+o>e.length)return!1;let R=e.length-l.length;if(this.#o(e,l,r,R,0))d=l.length;else{if(e[e.length-1]!==""||o+l.length===e.length||(R--,!this.#o(e,l,r,R,0)))return!1;d=l.length+1}}if(!u.length){let R=!!d;for(let A=o;A<e.length-d;A++){let O=String(e[A]);if(R=!0,O==="."||O===".."||!this.options.dot&&O.startsWith("."))return!1}return r||R}let p=[[[],0]],_=p[0],f=0,E=[0];for(let R of u)R===Qt?(E.push(f),_=[[],0],p.push(_)):(_[0].push(R),f++);let S=p.length-1,h=e.length-d;for(let R of p)R[1]=h-(E[S--]+R[0].length);return!!this.#r(e,p,o,0,r,0,!!d)}#r(e,n,r,o,s,i,a){let c=n[o];if(!c){for(let d=r;d<e.length;d++){a=!0;let p=e[d];if(p==="."||p===".."||!this.options.dot&&p.startsWith("."))return!1}return a}let[u,l]=c;for(;r<=l;){if(this.#o(e.slice(0,r+u.length),u,s,r,0)&&i<this.maxGlobstarRecursion){let _=this.#r(e,n,r+u.length,o+1,s,i+1,a);if(_!==!1)return _}let p=e[r];if(p==="."||p===".."||!this.options.dot&&p.startsWith("."))return!1;r++}return s||null}#o(e,n,r,o,s){let i,a,c,u;for(i=o,a=s,u=e.length,c=n.length;i<u&&a<c;i++,a++){this.debug("matchOne loop");let l=n[a],d=e[i];if(this.debug(n,l,d),l===!1||l===Qt)return!1;let p;if(typeof l=="string"?(p=d===l,this.debug("string match",l,d,p)):(p=l.test(d),this.debug("pattern match",l,d,p)),!p)return!1}if(i===u&&a===c)return!0;if(i===u)return r;if(a===c)return i===u-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return GX(this.pattern,this.options)}parse(e){Jd(e);let n=this.options;if(e==="**")return Qt;if(e==="")return"";let r,o=null;(r=e.match(GVe))?o=n.dot?$Ve:HVe:(r=e.match(bVe))?o=(n.nocase?n.dot?DVe:xVe:n.dot?LVe:MVe)(r[1]):(r=e.match(FVe))?o=(n.nocase?n.dot?qVe:jVe:n.dot?YVe:KVe)(r):(r=e.match(UVe))?o=n.dot?kVe:wVe:(r=e.match(VVe))&&(o=BVe);let s=Ca.fromGlob(e,this.options).toMMPattern();return o&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:o}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?XVe:n.dot?JVe:ZVe,o=new Set(n.nocase?["i"]:[]),s=e.map(c=>{let u=c.map(l=>{if(l instanceof RegExp)for(let d of l.flags.split(""))o.add(d);return typeof l=="string"?rBe(l):l===Qt?Qt:l._src});return u.forEach((l,d)=>{let p=u[d+1],_=u[d-1];l!==Qt||_===Qt||(_===void 0?p!==void 0&&p!==Qt?u[d+1]="(?:\\/|"+r+"\\/)?"+p:u[d]=r:p===void 0?u[d-1]=_+"(?:\\/|"+r+")?":p!==Qt&&(u[d-1]=_+"(?:\\/|\\/"+r+"\\/)"+p,u[d+1]=Qt))}),u.filter(l=>l!==Qt).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];s="^"+i+s+a+"$",this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let i=o[o.length-1];if(!i)for(let a=o.length-2;!i&&a>=0;a--)i=o[a];for(let a=0;a<s.length;a++){let c=s[a],u=o;if(r.matchBase&&c.length===1&&(u=[i]),this.matchOne(u,c,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return wt.defaults(e).Minimatch}};wt.AST=Ca;wt.Minimatch=Ru;wt.escape=_C;wt.unescape=Zs;var HX="@fastify/otel",sBe="0.8.0",iBe=">=4.0.0 <6",$X=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],De={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},Qs={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},Yo="anonymous",ln=Symbol("fastify otel instance"),ei=Symbol("fastify otel request spans"),Qd=Symbol("fastify otel request context"),FX=Symbol("fastify otel addhook original"),jX=Symbol("fastify otel setnotfound original"),FS=Symbol("fastify otel ignore path"),jS=class extends qX.InstrumentationBase{constructor(e){if(super(HX,sBe,e),this.servername=e?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[FS]=null,this._logger=Mn.createComponentLogger({namespace:HX}),e?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let n=e?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof n!="string"||n.length===0)&&typeof n!="function")throw new TypeError("ignorePaths must be a string or a function");let r=wt;this[FS]=o=>typeof n=="function"?n(o):r(o.url,n)}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let e=this.plugin();this._handleInitialization=n=>{n.fastify.register(e)},fC.default.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){return this._handleInitialization&&(fC.default.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0),super.disable()}init(){return[]}plugin(){let e=this;return n[Symbol.for("skip-override")]=!0,n[Symbol.for("fastify.display-name")]="@fastify/otel",n[Symbol.for("plugin-meta")]={fastify:iBe,name:"@fastify/otel"},n;function n(r,o,s){r.decorate(ln,e),r.decorate(FX,r.addHook),r.decorate(jX,r.setNotFoundHandler),r.decorateRequest("opentelemetry",function(){let p=this[Qd];return{span:this[ei],tracer:e.tracer,context:p,inject:(f,E)=>rn.inject(p,f,E),extract:(f,E)=>rn.extract(p,f,E)}}),r.decorateRequest(ei,null),r.decorateRequest(Qd,null),r.addHook("onRoute",function(d){if(e[FS]?.(d)===!0){e._logger.debug(`Ignoring route instrumentation ${d.method} ${d.url} because it matches the ignore path`);return}for(let p of $X)if(d[p]!=null){let _=d[p];if(typeof _=="function")d[p]=l(_,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - route -> ${p}`,[De.FASTIFY_TYPE]:Qs.ROUTE,[io]:d.url,[De.HOOK_CALLBACK_NAME]:_.name?.length>0?_.name:Yo});else if(Array.isArray(_)){let f=[];for(let E of _)f.push(l(E,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - route -> ${p}`,[De.FASTIFY_TYPE]:Qs.ROUTE,[io]:d.url,[De.HOOK_CALLBACK_NAME]:E.name?.length>0?E.name:Yo}));d[p]=f}}d.onSend!=null?d.onSend=Array.isArray(d.onSend)?[...d.onSend,i]:[d.onSend,i]:d.onSend=i,d.onError!=null?d.onError=Array.isArray(d.onError)?[...d.onError,a]:[d.onError,a]:d.onError=a,d.handler=l(d.handler,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - route-handler`,[De.FASTIFY_TYPE]:Qs.HANDLER,[io]:d.url,[De.HOOK_CALLBACK_NAME]:d.handler.name.length>0?d.handler.name:Yo})}),r.addHook("onRequest",function(d,p,_){if(this[ln].isEnabled()===!1)return _();if(this[ln][FS]?.({url:d.url,method:d.method})===!0)return this[ln]._logger.debug(`Ignoring request ${d.method} ${d.url} because it matches the ignore path`),_();let f=X.active();oe.getSpan(f)==null&&(f=rn.extract(f,d.headers));let E=(0,qS.getRPCMetadata)(f);d.routeOptions.url!=null&&E?.type===qS.RPCType.HTTP&&(E.route=d.routeOptions.url);let S=this[ln].tracer.startSpan("request",{attributes:{[wn]:r[ln].servername,[De.ROOT]:"@fastify/otel",[io]:d.url,[ma]:d.method}},f);d[Qd]=oe.setSpan(f,S),d[ei]=S,X.with(d[Qd],()=>{_()})}),r.addHook("onResponse",function(d,p,_){let f=d[ei];f!=null&&(f.setStatus({code:Me.OK,message:"OK"}),f.setAttributes({[Ks]:404}),f.end()),d[ei]=null,_()}),r.addHook=c,r.setNotFoundHandler=u,s();function i(d,p,_,f){let E=d[ei];E!=null&&(p.statusCode<500&&E.setStatus({code:Me.OK,message:"OK"}),E.setAttributes({[Ks]:p.statusCode}),E.end()),d[ei]=null,f(null,_)}function a(d,p,_,f){let E=d[ei];E!=null&&(E.setStatus({code:Me.ERROR,message:_.message}),E.recordException(_)),f()}function c(d,p){let _=this[FX];return $X.includes(d)?_.call(this,d,l(p,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - ${d}`,[De.FASTIFY_TYPE]:Qs.INSTANCE,[De.HOOK_CALLBACK_NAME]:p.name?.length>0?p.name:Yo})):_.call(this,d,p)}function u(d,p){let _=this[jX];typeof d=="function"?(p=l(d,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[De.FASTIFY_TYPE]:Qs.INSTANCE,[De.HOOK_CALLBACK_NAME]:d.name?.length>0?d.name:Yo}),_.call(this,p)):(d.preValidation!=null&&(d.preValidation=l(d.preValidation,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[De.FASTIFY_TYPE]:Qs.INSTANCE,[De.HOOK_CALLBACK_NAME]:d.preValidation.name?.length>0?d.preValidation.name:Yo})),d.preHandler!=null&&(d.preHandler=l(d.preHandler,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[De.FASTIFY_TYPE]:Qs.INSTANCE,[De.HOOK_CALLBACK_NAME]:d.preHandler.name?.length>0?d.preHandler.name:Yo})),p=l(p,{[wn]:r[ln].servername,[De.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[De.FASTIFY_TYPE]:Qs.INSTANCE,[De.HOOK_CALLBACK_NAME]:p.name?.length>0?p.name:Yo}),_.call(this,d,p))}function l(d,p={}){return function(...f){let E=this[ln],[S]=f;if(E.isEnabled()===!1)return d.call(this,...f);let h=S[Qd]??X.active(),R=E.tracer.startSpan(`handler - ${d.name?.length>0?d.name:this.pluginName??Yo}`,{attributes:p},h);return X.with(oe.setSpan(h,R),function(){try{let A=d.call(this,...f);return typeof A?.then=="function"?A.then(O=>(R.end(),O),O=>(R.setStatus({code:Me.ERROR,message:O.message}),R.recordException(O),R.end(),Promise.reject(O))):(R.end(),A)}catch(A){throw R.setStatus({code:Me.ERROR,message:A.message}),R.recordException(A),R.end(),A}},this)}}}}};x();var WS=v(Se(),1),va=v(fe(),1);ve();var Ko;(function(t){let e="fastify.name";t.FASTIFY_NAME=e;let n="fastify.type";t.FASTIFY_TYPE=n;let r="hook.name";t.HOOK_NAME=r;let o="plugin.name";t.PLUGIN_NAME=o})(Ko||(Ko={}));var ep;(function(t){let e="middleware";t.MIDDLEWARE=e;let n="request_handler";t.REQUEST_HANDLER=n})(ep||(ep={}));var tp;(function(t){let e="middleware";t.MIDDLEWARE=e;let n="request handler";t.REQUEST_HANDLER=n})(tp||(tp={}));x();var np=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function mC(t,e,n,r={}){let o=e.startSpan(n,{attributes:r}),s=t[np]||[];return s.push(o),Object.defineProperty(t,np,{enumerable:!1,configurable:!0,value:s}),o}function YS(t,e){let n=t[np]||[];n.length&&(n.forEach(r=>{e&&(r.setStatus({code:Me.ERROR,message:e.message}),r.recordException(e)),r.end()}),delete t[np])}function KX(t,e,n){let r,o;try{o=t(),YX(o)&&o.then(s=>e(void 0,s),s=>e(s))}catch(s){r=s}finally{if(!YX(o)&&(e(r,o),r))throw r;return o}}function YX(t){return typeof t=="object"&&t&&typeof Object.getOwnPropertyDescriptor(t,"then")?.value=="function"||!1}var aBe="0.1.0",cBe="@sentry/instrumentation-fastify-v3",WX="anonymous",uBe=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]),KS=class extends va.InstrumentationBase{constructor(e={}){super(cBe,aBe,e)}init(){return[new va.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],e=>this._patchConstructor(e))]}_hookOnRequest(){let e=this;return function(r,o,s){if(!e.isEnabled())return s();e._wrap(o,"send",e._patchSend());let i=r,a=(0,WS.getRPCMetadata)(X.active()),c=i.routeOptions?i.routeOptions.url:r.routerPath;c&&a?.type===WS.RPCType.HTTP&&(a.route=c);let u=r.method||"GET";Re().setTransactionName(`${u} ${c}`),s()}}_wrapHandler(e,n,r,o){let s=this;return this._diag.debug("Patching fastify route.handler function"),function(...i){if(!s.isEnabled())return r.apply(this,i);let a=r.name||e||WX,c=`${tp.MIDDLEWARE} - ${a}`,u=i[1],l=mC(u,s.tracer,c,{[Ko.FASTIFY_TYPE]:ep.MIDDLEWARE,[Ko.PLUGIN_NAME]:e,[Ko.HOOK_NAME]:n}),d=o&&i[i.length-1];return d&&(i[i.length-1]=function(...p){YS(u),d.apply(this,p)}),X.with(oe.setSpan(X.active(),l),()=>KX(()=>r.apply(this,i),p=>{p instanceof Error&&(l.setStatus({code:Me.ERROR,message:p.message}),l.recordException(p)),o||YS(u)}))}}_wrapAddHook(){let e=this;return this._diag.debug("Patching fastify server.addHook function"),function(n){return function(...o){let s=o[0],i=o[1],a=this.pluginName;if(!uBe.has(s))return n.apply(this,o);let c=typeof o[o.length-1]=="function"&&i.constructor.name!=="AsyncFunction";return n.apply(this,[s,e._wrapHandler(a,s,i,c)])}}}_patchConstructor(e){let n=this;function r(...o){let s=e.fastify.apply(this,o);return s.addHook("onRequest",n._hookOnRequest()),s.addHook("preHandler",n._hookPreHandler()),lBe(),n._wrap(s,"addHook",n._wrapAddHook()),s}return e.errorCodes!==void 0&&(r.errorCodes=e.errorCodes),r.fastify=r,r.default=r,r}_patchSend(){let e=this;return this._diag.debug("Patching fastify reply.send function"),function(r){return function(...s){let i=s[0];return e.isEnabled()?(0,va.safeExecuteInTheMiddle)(()=>r.apply(this,s),a=>{!a&&i instanceof Error&&(a=i),YS(this,a)}):r.apply(this,s)}}}_hookPreHandler(){let e=this;return this._diag.debug("Patching fastify preHandler function"),function(r,o,s){if(!e.isEnabled())return s();let i=r,a=i.routeOptions?.handler||i.context?.handler,c=a?.name.startsWith("bound ")?a.name.substring(6):a?.name,u=`${tp.REQUEST_HANDLER} - ${c||this.pluginName||WX}`,l={[Ko.PLUGIN_NAME]:this.pluginName,[Ko.FASTIFY_TYPE]:ep.REQUEST_HANDLER,[vd]:i.routeOptions?i.routeOptions.url:r.routerPath};c&&(l[Ko.FASTIFY_NAME]=c);let d=mC(o,e.tracer,u,l);zX(d);let{requestHook:p}=e.getConfig();return p&&(0,va.safeExecuteInTheMiddle)(()=>p(d,{request:r}),_=>{_&&e._diag.error("request hook failed",_)},!0),X.with(oe.setSpan(X.active(),d),()=>{s()})}}};function lBe(){let t=K();t&&t.on("spanStart",e=>{zX(e)})}function zX(t){let e=W(t).data,n=e["fastify.type"];if(e[se]||!n)return;t.setAttributes({[ye]:"auto.http.otel.fastify",[se]:`${n}.fastify`});let r=e["fastify.name"]||e["plugin.name"]||e["hook.name"];if(typeof r=="string"){let o=r.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");t.updateName(o)}}var JX="Fastify",dBe="Fastify-V5",pBe="Fastify-V3",ZX=q(pBe,()=>new KS);function _Be(){let t=K();if(t)return t.getIntegrationByName(JX)}function XX(t,e,n,r){let o=_Be()?.getShouldHandleError()||t9;if(r==="diagnostics-channel"&&(this.diagnosticsChannelExists=!0),this.diagnosticsChannelExists&&r==="onError-hook"){_o&&g.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}o(t,e,n)&&un(t,{mechanism:{handled:!1,type:"fastify"}})}var QX=q(dBe,()=>{let t=new jS,e=t.plugin();return EC.subscribe("fastify.initialization",n=>{let r=n.fastify;r?.register(e).after(o=>{o?_o&&g.error("Failed to setup Fastify instrumentation",o):(mBe(),r&&EBe(r))})}),EC.subscribe("tracing:fastify.request.handler:error",n=>{let{error:r,request:o,reply:s}=n;XX.call(XX,r,o,s,"diagnostics-channel")}),t}),fBe=(({shouldHandleError:t})=>{let e;return{name:JX,setupOnce(){e=t||t9,ZX(),QX()},getShouldHandleError(){return e},setShouldHandleError(n){e=n}}}),e9=(t={})=>fBe(t);function t9(t,e,n){let r=n.statusCode;return r>=500||r<=299}function n9(t){let e=W(t),n=e.description,r=e.data,o=r["fastify.type"],s=o==="hook",i=o===n?.startsWith("handler -"),a=n==="request"||o==="request-handler";if(r[se]||!i&&!a&&!s)return;let c=s?"hook":i?"middleware":a?"request-handler":"<unknown>";t.setAttributes({[ye]:"auto.http.otel.fastify",[se]:`${c}.fastify`});let u=r["fastify.name"]||r["plugin.name"]||r["hook.name"];if(typeof u=="string"){let l=u.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");t.updateName(l)}}function mBe(){let t=K();t&&t.on("spanStart",e=>{n9(e)})}function EBe(t){t.addHook("onRequest",async(e,n)=>{if(e.opentelemetry){let{span:s}=e.opentelemetry();s&&n9(s)}let r=e.routeOptions?.url,o=e.method||"GET";Re().setTransactionName(`${o} ${r}`)})}x();var O9=v(y9(),1);var N9="Graphql",C9=q(N9,O9.GraphQLInstrumentation,t=>{let e=I9(t);return{...e,responseHook(n,r){xe(n,"auto.graphql.otel.graphql"),r.errors?.length&&!W(n).status&&n.setStatus({code:Me.ERROR});let s=W(n).data,i=s["graphql.operation.type"],a=s["graphql.operation.name"];if(e.useOperationNameForRootSpan&&i){let c=Ye(n),l=W(c).data[du]||[],d=a?`${i} ${a}`:`${i}`;Array.isArray(l)?(l.push(d),c.setAttribute(du,l)):typeof l=="string"?c.setAttribute(du,[l,d]):c.setAttribute(du,d),W(c).data["original-description"]||c.setAttribute("original-description",W(c).description),c.updateName(`${W(c).data["original-description"]} (${UBe(l)})`)}}}}),DBe=((t={})=>({name:N9,setupOnce(){C9(I9(t))}})),v9=DBe;function I9(t){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...t}}function UBe(t){if(Array.isArray(t)){let e=t.slice().sort();return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")}, +${e.length-5}`}return`${t}`}var V9=v(k9(),1);var B9="Kafka",G9=q(B9,()=>new V9.KafkaJsInstrumentation({consumerHook(t){xe(t,"auto.kafkajs.otel.consumer")},producerHook(t){xe(t,"auto.kafkajs.otel.producer")}})),kBe=(()=>({name:B9,setupOnce(){G9()}})),H9=kBe;var W9=v(K9(),1);var z9="LruMemoizer",X9=q(z9,()=>new W9.LruMemoizerInstrumentation),GBe=(()=>({name:z9,setupOnce(){X9()}})),J9=GBe;var i8=v(s8(),1);var a8="Mongo",c8=q(a8,()=>new i8.MongoDBInstrumentation({dbStatementSerializer:jBe,responseHook(t){xe(t,"auto.db.otel.mongo")}}));function jBe(t){let e=NC(t);return JSON.stringify(e)}function NC(t){if(Array.isArray(t))return t.map(e=>NC(e));if(qBe(t)){let e={};return Object.entries(t).map(([n,r])=>[n,NC(r)]).reduce((n,r)=>(KBe(r)&&(n[r[0]]=r[1]),n),e)}return"?"}function qBe(t){return typeof t=="object"&&t!==null&&!YBe(t)}function YBe(t){let e=!1;return typeof Buffer<"u"&&(e=Buffer.isBuffer(t)),e}function KBe(t){return Array.isArray(t)}var WBe=(()=>({name:a8,setupOnce(){c8()}})),u8=WBe;var y8=v(R8(),1);var O8="Mongoose",N8=q(O8,()=>new y8.MongooseInstrumentation({responseHook(t){xe(t,"auto.db.otel.mongoose")}})),oGe=(()=>({name:O8,setupOnce(){N8()}})),C8=oGe;var k8=v(w8(),1);var V8="Mysql",B8=q(V8,()=>new k8.MySQLInstrumentation({})),fGe=(()=>({name:V8,setupOnce(){B8()}})),G8=fGe;var Z8=v(J8(),1);var Q8="Mysql2",e6=q(Q8,()=>new Z8.MySQL2Instrumentation({responseHook(t){xe(t,"auto.db.otel.mysql2")}})),CGe=(()=>({name:Q8,setupOnce(){e6()}})),t6=CGe;var v6=v(d6(),1),I6=v(R6(),1);var VGe=["get","set","setex"],kC=["get","mget"],BGe=["set","setex"];function _p(t,e){return t.includes(e.toLowerCase())}function VC(t){return _p(kC,t)?"cache.get":_p(BGe,t)?"cache.put":void 0}function GGe(t,e){return e.some(n=>t.startsWith(n))}function O6(t,e){try{if(e.length===0)return;let n=o=>typeof o=="string"||typeof o=="number"||Buffer.isBuffer(o)?[o.toString()]:Array.isArray(o)?y6(o.map(s=>n(s))):["<unknown>"],r=e[0];return _p(VGe,t)&&r!=null?n(r):y6(e.map(o=>n(o)))}catch{return}}function N6(t,e,n){if(!VC(t))return!1;for(let r of e)if(GGe(r,n))return!0;return!1}function C6(t){let e=n=>{try{return Buffer.isBuffer(n)?n.byteLength:typeof n=="string"?n.length:typeof n=="number"?n.toString().length:n==null?0:JSON.stringify(n).length}catch{return}};return Array.isArray(t)?t.reduce((n,r)=>{let o=e(r);return typeof o=="number"?n!==void 0?n+o:o:n},0):e(t)}function y6(t){let e=[],n=r=>{r.forEach(o=>{Array.isArray(o)?n(o):e.push(o)})};return n(t),e}var P6="Redis",BC={},b6=(t,e,n,r)=>{t.setAttribute(ye,"auto.db.otel.redis");let o=O6(e,n),s=VC(e);if(!o||!s||!BC.cachePrefixes||!N6(e,o,BC.cachePrefixes))return;let i=W(t).data["net.peer.name"],a=W(t).data["net.peer.port"];a&&i&&t.setAttributes({"network.peer.address":i,"network.peer.port":a});let c=C6(r);c&&t.setAttribute(yy,c),_p(kC,e)&&c!==void 0&&t.setAttribute(Ay,c>0),t.setAttributes({[se]:s,[Ry]:o});let u=o.join(", ");t.updateName(Zr(u,1024))},HGe=q("IORedis",()=>new v6.IORedisInstrumentation({responseHook:b6})),$Ge=q("Redis-4",()=>new I6.RedisInstrumentation({responseHook:b6})),M6=Object.assign(()=>{HGe(),$Ge()},{id:P6}),FGe=((t={})=>({name:P6,setupOnce(){BC=t,M6()}})),L6=FGe;var J6=v(X6(),1);var Z6="Postgres",Q6=q(Z6,()=>new J6.PgInstrumentation({requireParentSpan:!0,requestHook(t){xe(t,"auto.db.otel.postgres")}})),oHe=(()=>({name:Z6,setupOnce(){Q6()}})),eJ=oHe;x();var es=v(fe(),1);ve();var KC="PostgresJs",tJ=[">=3.0.0 <4"],nJ=q(KC,t=>new YC({requireParentSpan:t?.requireParentSpan??!0,requestHook:t?.requestHook})),YC=class extends es.InstrumentationBase{constructor(e){super("sentry-postgres-js",Pe,e)}init(){let e=new es.InstrumentationNodeModuleDefinition("postgres",tJ);return["src","cf/src","cjs/src"].forEach(n=>{e.files.push(new es.InstrumentationNodeModuleFile(`postgres/${n}/connection.js`,["*"],this._patchConnection.bind(this),this._unwrap.bind(this))),e.files.push(new es.InstrumentationNodeModuleFile(`postgres/${n}/query.js`,tJ,this._patchQuery.bind(this),this._unwrap.bind(this)))}),[e]}_shouldCreateSpans(){let e=this.getConfig();return oe.getSpan(X.active())!==void 0||!e.requireParentSpan}_patchReject(e,n){return new Proxy(e,{apply:(r,o,s)=>{n.setStatus({code:2,message:s?.[0]?.message||"unknown_error"});let i=Reflect.apply(r,o,s);return n.setAttribute(EO,s?.[0]?.code||"Unknown error"),n.setAttribute(gO,s?.[0]?.name||"Unknown error"),n.end(),i}})}_patchResolve(e,n){return new Proxy(e,{apply:(r,o,s)=>{let i=Reflect.apply(r,o,s),a=s?.[0]?.command;return a&&n.setAttribute(fO,a),n.end(),i}})}_patchQuery(e){return e.Query.prototype.handle=new Proxy(e.Query.prototype.handle,{apply:async(n,r,o)=>{if(!this._shouldCreateSpans())return Reflect.apply(n,r,o);let s=this._sanitizeSqlQuery(r.strings?.[0]);return Wm({name:s||"postgresjs.query",op:"db"},i=>{let c=ue().getScopeData().contexts.postgresjsConnection;xe(i,"auto.db.otel.postgres");let{requestHook:u}=this.getConfig();u&&(0,es.safeExecuteInTheMiddle)(()=>u(i,s,c),_=>{_&&g.error(`Error in requestHook for ${KC} integration:`,_)});let l=c?.ATTR_DB_NAMESPACE||"<unknown database>",d=c?.ATTR_SERVER_ADDRESS||"<unknown host>",p=c?.ATTR_SERVER_PORT||"<unknown port>";i.setAttribute(SO,"postgres"),i.setAttribute(_O,l),i.setAttribute(hO,d),i.setAttribute(TO,p),i.setAttribute(mO,s),r.resolve=this._patchResolve(r.resolve,i),r.reject=this._patchReject(r.reject,i);try{return Reflect.apply(n,r,o)}catch(_){throw i.setStatus({code:2}),i.end(),_}})}}),e}_patchConnection(e){return new Proxy(e,{apply:(n,r,o)=>{let s=o[0]?.database||"<unknown database>",i=o[0]?.host?.[0]||"<unknown host>",a=o[0]?.port?.[0]||"<unknown port>";return ue().setContext("postgresjsConnection",{ATTR_DB_NAMESPACE:s,ATTR_SERVER_ADDRESS:i,ATTR_SERVER_PORT:a}),Reflect.apply(n,r,o)}})}_sanitizeSqlQuery(e){return e?e.replace(/\s+/g," ").trim().substring(0,1024).replace(/--.*?(\r?\n|$)/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\b\d+\b/g,"?").replace(/\s+/g," ").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/g,"IN (?)"):"Unknown SQL Query"}},sHe=(()=>({name:KC,setupOnce(){nJ()}})),rJ=sHe;x();var Rg=v(fe(),1);x();var iHe=process.env.PRISMA_SHOW_ALL_TRACES==="true",aHe="00-10-10-00";function cHe(t){return t==="client"?Dt.CLIENT:Dt.INTERNAL}var uHe=class{traceMiddleware;tracerProvider;ignoreSpanTypes;constructor({traceMiddleware:t,tracerProvider:e,ignoreSpanTypes:n}){this.traceMiddleware=t,this.tracerProvider=e,this.ignoreSpanTypes=n}isEnabled(){return!0}getTraceParent(t){let e=oe.getSpanContext(t??X.active());return e?`00-${e.traceId}-${e.spanId}-0${e.traceFlags}`:aHe}dispatchEngineSpans(t){let e=this.tracerProvider.getTracer("prisma"),n=new Map,r=t.filter(o=>o.parentId===null);for(let o of r)iJ(e,o,t,n,this.ignoreSpanTypes)}getActiveContext(){return X.active()}runInChildSpan(t,e){if(typeof t=="string"&&(t={name:t}),t.internal&&!iHe||t.middleware&&!this.traceMiddleware)return e();let n=this.tracerProvider.getTracer("prisma"),r=t.context??this.getActiveContext(),o=`prisma:client:${t.name}`;if(aJ(o,this.ignoreSpanTypes))return e();if(t.active===!1){let s=n.startSpan(o,t,r);return oJ(s,e(s,r))}return n.startActiveSpan(o,t,s=>oJ(s,e(s,r)))}};function iJ(t,e,n,r,o){if(aJ(e.name,o))return;let s={attributes:e.attributes,kind:cHe(e.kind),startTime:e.startTime};t.startActiveSpan(e.name,s,i=>{r.set(e.id,i.spanContext().spanId),e.links&&i.addLinks(e.links.flatMap(c=>{let u=r.get(c);return u?{context:{spanId:u,traceId:i.spanContext().traceId,traceFlags:i.spanContext().traceFlags}}:[]}));let a=n.filter(c=>c.parentId===e.id);for(let c of a)iJ(t,c,n,r,o);i.end(e.endTime)})}function oJ(t,e){return lHe(e)?e.then(n=>(t.end(),n),n=>{throw t.end(),n}):(t.end(),e)}function lHe(t){return t!=null&&typeof t.then=="function"}function aJ(t,e){return e.some(n=>typeof n=="string"?n===t:n.test(t))}var cJ={name:"@prisma/instrumentation",version:"6.11.1",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@swc/core":"1.11.5","@types/jest":"29.5.14","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",jest:"29.7.0","jest-junit":"16.0.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":"^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"jest"},sideEffects:!1},zC=cJ.version,dHe=zC.split(".")[0],sJ="PRISMA_INSTRUMENTATION",WC=`V${dHe}_PRISMA_INSTRUMENTATION`,pHe=cJ.name,_He="@prisma/client",uJ=class extends Rg.InstrumentationBase{tracerProvider;constructor(t={}){super(pHe,zC,t)}setTracerProvider(t){this.tracerProvider=t}init(){return[new Rg.InstrumentationNodeModuleDefinition(_He,[zC])]}enable(){let t=this._config,e={helper:new uHe({traceMiddleware:t.middleware??!1,tracerProvider:this.tracerProvider??oe.getTracerProvider(),ignoreSpanTypes:t.ignoreSpanTypes??[]})};global[sJ]=e,global[WC]=e}disable(){delete global[sJ],delete global[WC]}isEnabled(){return!!global[WC]}};var lJ="Prisma";function fHe(t){return!!t&&typeof t=="object"&&"dispatchEngineSpans"in t}function dJ(){let t=globalThis.PRISMA_INSTRUMENTATION;return t&&typeof t=="object"&&"helper"in t?t.helper:void 0}var XC=class extends uJ{constructor(){super()}enable(){super.enable();let e=dJ(),n=!1;fHe(e)&&(e.createEngineSpan=()=>{qe(()=>{n||(n=!0,console.warn("[Sentry] The Sentry SDK supports tracing with Prisma version 5 only with limited capabilities. For full tracing capabilities pass `prismaInstrumentation` for version 5 to the Sentry `prismaIntegration`. Read more: https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/"))})})}},mHe=q(lJ,t=>t?.prismaInstrumentation?t.prismaInstrumentation:new XC),pJ=({prismaInstrumentation:t}={})=>({name:lJ,setupOnce(){mHe({prismaInstrumentation:t})},setup(e){dJ()&&e.on("spanStart",n=>{let r=W(n);r.description?.startsWith("prisma:")&&n.setAttribute(ye,"auto.db.otel.prisma"),r.description==="prisma:engine:db_query"&&r.data["db.query.text"]&&n.updateName(r.data["db.query.text"]),r.description==="prisma:engine:db_query"&&!r.data["db.system"]&&n.setAttribute("db.system","prisma")})}});var TJ=v(hJ(),1);var AJ="Hapi",RJ=q(AJ,()=>new TJ.HapiInstrumentation),CHe=(()=>({name:AJ,setupOnce(){RJ()}})),yJ=CHe;var UJ=v(DJ(),1);ve();var wJ="Koa",kJ=q(wJ,UJ.KoaInstrumentation,(t={})=>({ignoreLayersType:t.ignoreLayersType,requestHook(e,n){xe(e,"auto.http.otel.koa");let r=W(e).data,o=r["koa.type"];o&&e.setAttribute(se,`${o}.koa`);let s=r["koa.name"];if(typeof s=="string"&&e.updateName(s||"< unknown >"),Re()===Qr()){_o&&g.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let i=r[io],a=n.context?.request?.method?.toUpperCase()||"GET";i&&Re().setTransactionName(`${a} ${i}`)}})),xHe=((t={})=>({name:wJ,setupOnce(){kJ(t)}})),VJ=xHe;var KJ=v(YJ(),1);var WJ="Connect",zJ=q(WJ,()=>new KJ.ConnectInstrumentation),jHe=(()=>({name:WJ,setupOnce(){zJ()}})),XJ=jHe;var cZ=v(aZ(),1);var zHe=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),uZ="Tedious",lZ=q(uZ,()=>new cZ.TediousInstrumentation({})),XHe=(()=>{let t;return{name:uZ,setupOnce(){let e=lZ();t=Nd(e)},setup(e){t?.(()=>e.on("spanStart",n=>{let{description:r,data:o}=W(n);if(!r||o["db.system"]!=="mssql")return;let s=r.split(" ")[0]||"";zHe.has(s)&&n.setAttribute(ye,"auto.db.otel.tedious")}))}}}),dZ=XHe;var EZ=v(mZ(),1);var SZ="GenericPool",gZ=q(SZ,()=>new EZ.GenericPoolInstrumentation({})),QHe=(()=>{let t;return{name:SZ,setupOnce(){let e=gZ();t=Nd(e)},setup(e){t?.(()=>e.on("spanStart",n=>{let o=W(n).description;(o==="generic-pool.aquire"||o==="generic-pool.acquire")&&n.setAttribute(ye,"auto.db.otel.generic_pool")}))}}}),hZ=QHe;var PZ=v(IZ(),1);var bZ="Amqplib",u$e={consumeEndHook:t=>{xe(t,"auto.amqplib.otel.consumer")},publishHook:t=>{xe(t,"auto.amqplib.otel.publisher")}},MZ=q(bZ,()=>new PZ.AmqplibInstrumentation(u$e)),l$e=(()=>({name:bZ,setupOnce(){MZ()}})),LZ=l$e;var yp="VercelAI";var Hg=v(fe(),1);var xZ=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function d$e(t,e,n,r){let o=t?.recordInputs!==void 0?t.recordInputs:e.recordInputs!==void 0?e.recordInputs:n===!0?!0:r,s=t?.recordOutputs!==void 0?t.recordOutputs:e.recordOutputs!==void 0?e.recordOutputs:n===!0?!0:r;return{recordInputs:o,recordOutputs:s}}var Gg=class t extends Hg.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(e={}){super("@sentry/instrumentation-vercel-ai",Pe,e),t.prototype.__init.call(this),t.prototype.__init2.call(this)}init(){return new Hg.InstrumentationNodeModuleDefinition("ai",[">=3.0.0 <5"],this._patch.bind(this))}callWhenPatched(e){this._isPatched?e():this._callbacks.push(e)}_patch(e){this._isPatched=!0,this._callbacks.forEach(r=>r()),this._callbacks=[];function n(r){return(...o)=>{let s=o[0].experimental_telemetry||{},i=s.isEnabled,a=ue().getClient(),c=a?.getIntegrationByName(yp),u=c?.options,l=c?!!a?.getOptions().sendDefaultPii:!1,{recordInputs:d,recordOutputs:p}=d$e(u,s,i,l);return o[0].experimental_telemetry={...s,isEnabled:i!==void 0?i:!0,recordInputs:d,recordOutputs:p},Bo(()=>r.apply(this,o),_=>{_&&typeof _=="object"&&ct(_,"_sentry_active_span",ro())})}}if(Object.prototype.toString.call(e)==="[object Module]"){for(let r of xZ)e[r]=n(e[r]);return e}else{let r=xZ.reduce((o,s)=>(o[s]=n(e[s]),o),{});return{...e,...r}}}};var DZ=q(yp,()=>new Gg({}));function p$e(t){return!!t.getIntegrationByName("Modules")?.getModules?.()?.ai}var _$e=((t={})=>{let e;return{name:yp,options:t,setupOnce(){e=DZ()},afterAllSetup(n){t.force??p$e(n)?SE(n):e?.callWhenPatched(()=>SE(n))}}}),UZ=_$e;var Fg=v(fe(),1);var f$e=[">=4.0.0 <6"];function m$e(t,e){let n=t?.recordInputs??e,r=t?.recordOutputs??e;return{recordInputs:n,recordOutputs:r}}var $g=class extends Fg.InstrumentationBase{constructor(e={}){super("@sentry/instrumentation-openai",Pe,e)}init(){return new Fg.InstrumentationNodeModuleDefinition("openai",f$e,this._patch.bind(this))}_patch(e){let n=e.OpenAI,r=function(...o){let s=Reflect.construct(n,o),i=ue().getClient(),c=i?.getIntegrationByName(Ys)?.options,u=!!i?.getOptions().sendDefaultPii,{recordInputs:l,recordOutputs:d}=m$e(c,u);return tO(s,{recordInputs:l,recordOutputs:d})};Object.setPrototypeOf(r,n),Object.setPrototypeOf(r.prototype,n.prototype);for(let o of Object.getOwnPropertyNames(n))if(!["length","name","prototype"].includes(o)){let s=Object.getOwnPropertyDescriptor(n,o);s&&Object.defineProperty(r,o,s)}try{e.OpenAI=r}catch{Object.defineProperty(e,"OpenAI",{value:r,writable:!0,configurable:!0,enumerable:!0})}if(e.default===n)try{e.default=r}catch{Object.defineProperty(e,"default",{value:r,writable:!0,configurable:!0,enumerable:!0})}return e}};var wZ=q(Ys,()=>new $g({})),E$e=((t={})=>({name:Ys,options:t,setupOnce(){wZ()}})),kZ=E$e;function VZ(){return[cC(),e9(),v9(),u8(),C8(),G8(),t6(),L6(),eJ(),pJ(),yJ(),VJ(),XJ(),dZ(),hZ(),H9(),LZ(),J9(),UZ(),kZ(),rJ()]}x();var BZ=v(cN(),1),GZ=v(EN(),1);ve();var S$e=v(hm(),1);var pv=1e6;function HZ(t,e={}){t.getOptions().debug&&WN();let n=g$e(t,e);t.traceProvider=n}function g$e(t,e={}){let n=new GZ.BasicTracerProvider({sampler:new mS(t),resource:new BZ.Resource({[wn]:"node",[pO]:"sentry",[AO]:Pe}),forceFlushTimeoutMillis:500,spanProcessors:[new fS({timeout:h$e(t.getOptions().maxSpanWaitDuration)}),...e.spanProcessors||[]]});return oe.setGlobalTracerProvider(n),rn.setGlobalPropagator(new _S),X.setGlobalContextManager(new KN),n}function h$e(t){if(t!=null){if(t>pv)return _o&&g.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${pv}`),pv;if(t<=0||Number.isNaN(t)){_o&&g.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return t}}function $Z(){return MS().filter(e=>e.name!=="Http"&&e.name!=="NodeFetch").concat(Uz(),Yz())}function FZ(t){return[...$Z(),...vt(t)?VZ():[]]}function _v(t={}){return T$e(t,FZ)}function T$e(t={},e){fa(t,"node");let n=JN({...t,defaultIntegrations:t.defaultIntegrations??e(t)});return n&&!t.skipOpenTelemetrySetup&&(HZ(n,{spanProcessors:t.openTelemetrySpanProcessors}),ZN()),n}function R$e(){let t=process.env.SENTRY_RELEASE?.trim();if(t)return t;let n=(process.env.RAILWAY_GIT_COMMIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.GITHUB_SHA||process.env.GIT_COMMIT||"").slice(0,7),r=typeof process.env.npm_package_version=="string"?process.env.npm_package_version:"";if(r&&n)return`${r}+${n}`;if(n)return n;if(r)return r}function qZ(){let t=process.env.SENTRY_ENVIRONMENT?.trim();return t||(process.env.NODE_ENV==="production"?"production":"development")}function y$e(){let t=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(t===""||t===void 0)return qZ()==="production"?.15:1;let e=Number(t);return!Number.isFinite(e)||e<0?0:Math.min(e,1)}var O$e=new Set(["authorization","cookie","x-admin-key","x-api-key","x-platform-web-secret","proxy-authorization"]);function N$e(t){if(!t||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();e[n]=O$e.has(o)?"[Filtered]":r}return e}function C$e(t){let e=t.request;if(!e)return;e.headers&&typeof e.headers=="object"&&(e.headers=N$e(e.headers));let n=e.url;typeof n=="string"&&n.includes("token=")&&(e.url=n.replace(/([?&]token=)[^&]+/gi,"$1[Filtered]"))}function v$e(t){try{C$e(t);let n=t.exception?.values?.[0];return n?.value&&typeof n.value=="string"&&(/Bearer\s+\S+/i.test(n.value)&&(n.value=n.value.replace(/Bearer\s+\S+/gi,"Bearer [Filtered]")),/password[=:]\s*\S+/i.test(n.value)&&(n.value="[Filtered]")),t}catch{return t}}function I$e(t){return t.replace(/:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,":?").replace(/:[a-f0-9]{16,}/gi,":?")}var jZ=!1;function P$e(t){let e=R$e();return{environment:qZ(),...e?{release:e}:{},tracesSampleRate:y$e(),enableLogs:!0,beforeSend(n){if(n.type==="transaction")return n;let r=v$e(n);return r===null?null:r},beforeSendTransaction(n){try{for(let r of n.spans??[])r.description&&(r.description=I$e(r.description))}catch{}return n},initialScope:n=>(n.setTag("service",t),n)}}function YZ(t){if(jZ)return;let e=process.env.SENTRY_DSN?.trim();if(!e){t.dsnProvided=!1;return}t.dsnProvided=!0;try{_v({dsn:e,...P$e(t.serviceName)}),jZ=!0,console.log(`[visa/observability] Sentry initialized service=${t.serviceName} env=${process.env.SENTRY_ENVIRONMENT??process.env.NODE_ENV??"unknown"}`),tE(`Sentry initialized: ${t.serviceName}`,"info")}catch(n){console.error("[visa/observability] Sentry.init failed:",n),t.dsnProvided=!1}}process.env.SENTRY_DSN;YZ({serviceName:"visa-cli"});var mv=(0,XZ.promisify)(zZ.execFile);function b$e(t){let e=pt.homedir(),n=o=>o.replace(e,"~"),r=t.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${t.client.displayName} (${n(t.configPath)})
179
- ${r}: ${n(t.currentPath)}`}function JZ(t,e){if(t.length===0){console.log(`${e} \u2713 All MCP client configs are up to date.`);return}console.log(`${e} Found ${t.length} stale MCP config ${t.length===1?"entry":"entries"}:`);for(let n of t)console.log(b$e(n))}function KZ(t){console.log(` ! ${t.client.displayName} skipped: ${t.message}`)}var ze=new WZ.Command,M$e=new Set(["pay",...cT]),jg=null,Op=!1;function Vt(){return jg=new $n(()=>Ae.getSessionToken()),jg}function L$e(t){return t?typeof t.hasAnyAttestationKey=="boolean"?t.hasAnyAttestationKey:typeof t.hasAttestationKey=="boolean"?t.hasAttestationKey:!0:!1}function x$e(t){return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}async function D$e(t){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${Hn()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:t,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await us(o,i=>{T.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await us(void 0,s=>{T.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function U$e(t){let e;try{e=await t.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!L$e(e))return!1;let n=Np.randomUUID(),r=await t.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await rh(r.recoveryUrl),await D$e(n),console.log(" Server biometric state cleared."),!0}function Sv(t){return`$${(t/100).toFixed(2)}`}function Ev(t,e,n=!1){if(!t){let i=Sv(e);return n&&e>=0?`+${i}`:i}let r=(0,qg.fromWire)(t),o=r%10000n===0n?2:6,s=(0,qg.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function w$e(t){return Ev(t,0)}function k$e(t){let e=`visa-cli-${pt.hostname()||"local"}`,n=(t?.trim()||e).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function V$e(t){if(!t)return;let e=t.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(e)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>M$e.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function B$e(t){if(!t)return;let e=Number(t);if(!Number.isFinite(e)||e<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(e*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function ZZ(t){return t&&t.length>0?t.join(", "):"all tools"}function gv(t,e){return e||(typeof t!="number"||!Number.isFinite(t)?"price unknown":`$${(t/100).toFixed(2)}`)}function G$e(t,e){if(!t)return{};try{let n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must be a JSON object.`);return n}catch(n){throw new Error(`${e} must be valid JSON: ${n.message}`)}}function QZ(t){let e=t.inputSchema?.properties;return e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).join(", ")||"none":Object.keys(t.inputSchema||{}).join(", ")||"none"}function fv(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}function H$e(t){let e=new Map;for(let n of t){let r=n.category||"other",o=e.get(r)??[];o.push(n),e.set(r,o)}return new Map([...e.entries()].sort(([n],[r])=>n.localeCompare(r)))}function $$e(t){let e=Math.max(4,Math.min(28,t.reduce((o,s)=>Math.max(o,s.id.length),0))),n=7,r=Math.max(8,Math.min(12,t.reduce((o,s)=>Math.max(o,(s.category||"").length),0)));console.log(`
140
+ `)):e}function Nn(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);try{let r=R.dirname(n);N.existsSync(r)||N.mkdirSync(r,{recursive:!0});let s=fo(e,t),o=mc();if(s==="toml"){let i=N.existsSync(n)?N.readFileSync(n,"utf-8"):"",a=Lp(i,"visa-cli",o);N.writeFileSync(n,a)}else{let i={};if(N.existsSync(n))try{i=JSON.parse(N.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,N.writeFileSync(n,JSON.stringify(i,null,2)+`
141
+ `)}}catch(r){throw Mp(r)?new cn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function yo(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return{removed:!1,configPath:n};if(fo(e,t)==="toml"){let i=N.readFileSync(n,"utf-8");return ho(i,"visa-cli")?(N.writeFileSync(n,jp(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(N.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],N.writeFileSync(n,JSON.stringify(s,null,2)+`
142
+ `),{removed:!0,configPath:n})}function pc(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return!1;if(fo(e,t)==="toml")try{let s=N.readFileSync(n,"utf-8");return!!ho(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(N.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Vp(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function qp(e,t){if(e===t)return!0;let n=R.resolve(e),r=R.resolve(t);if(n===r)return!0;try{let s=N.realpathSync(n),o=N.realpathSync(r);return s===o}catch{return!1}}function Un(){let e=mc(),t=e.args[e.args.length-1],n=[];for(let r of Re){let s=Fr(r);if(!N.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let c=N.readFileSync(s,"utf-8");i=ho(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(N.readFileSync(s,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Vp(i);if(!a||qp(a,t))continue;let l=N.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:l})}return n}function _o(e){return{configPath:Nn(e.client,"global").configPath}}var bo=(0,yc.promisify)(hc.execFile);function Kp(e){let t=W.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
143
+ ${r}: ${n(e.currentPath)}`}function _c(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(Kp(n))}function fc(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var q=new gc.Command,Gp=new Set(["pay",...uo]),Kr=null,Dn=!1;function oe(){return Kr=new ve(()=>D.getSessionToken()),Kr}function zp(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Wp(e){return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(e)}async function Jp(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await tt(s,i=>{d.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await tt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Yp(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!zp(t))return!1;let n=Ln.randomUUID(),r=await e.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await os(r.recoveryUrl),await Jp(n),console.log(" Server biometric state cleared."),!0}function wo(e){return`$${(e/100).toFixed(2)}`}function So(e,t,n=!1){if(!e){let i=wo(t);return n&&t>=0?`+${i}`:i}let r=(0,Gr.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Gr.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function Zp(e){return So(e,0)}function Xp(e){let t=`visa-cli-${W.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function Qp(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>Gp.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function ef(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function vc(e){return e&&e.length>0?e.join(", "):"all tools"}function xo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function tf(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function bc(e){let t=e.inputSchema?.properties;return t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).join(", ")||"none":Object.keys(e.inputSchema||{}).join(", ")||"none"}function vo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function nf(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function rf(e){let t=Math.max(4,Math.min(28,e.reduce((s,o)=>Math.max(s,o.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((s,o)=>Math.max(s,(o.category||"").length),0)));console.log(`
180
144
  Merchant tools
181
- `),console.log(` ${"Tool".padEnd(e)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(e)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(28)}`);for(let o of t)console.log(` ${fv(o.id,e).padEnd(e)} ${gv(o.priceCents,o.priceDisplay).padEnd(n)} ${fv(o.category||"other",r).padEnd(r)} ${fv(QZ(o),42)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function F$e(t){console.log(`
145
+ `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(28)}`);for(let s of e)console.log(` ${vo(s.id,t).padEnd(t)} ${xo(s.priceCents,s.priceDisplay).padEnd(n)} ${vo(s.category||"other",r).padEnd(r)} ${vo(bc(s),42)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function sf(e){console.log(`
182
146
  Merchant tools
183
- `);for(let[e,n]of H$e(t)){console.log(e[0]?.toUpperCase()+e.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${gv(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${QZ(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log(`Shortcut: visa-cli generate image "a lobster"
184
- `)}function eQ(t){if(t?.content?.[0]?.text&&typeof t.content[0].text=="string"){console.log(t.content[0].text);return}let e=Array.isArray(t?.urls)?t.urls:Array.isArray(t?.receipt?.urls)?t.receipt.urls:[];if(console.log("Done"),typeof t?.merchantName=="string"&&console.log(`Merchant: ${t.merchantName}`),typeof t?.amount=="number"&&console.log(`Cost: $${t.amount.toFixed(2)}`),typeof t?.transactionId=="string"&&console.log(`Transaction: ${t.transactionId}`),e.length>0){console.log(`
185
- Result URLs:`);for(let r of e)console.log(` ${r}`);return}let n=JSON.stringify(t,null,2);n&&n!=="{}"&&(console.log(`
186
- Result:`),console.log(n))}async function j$e(t,e={}){let n=await t.catalogSearch(e.query,e.category,"discover_tools");return Array.isArray(n.tools)?n.tools:[]}function q$e(t){let e=`
147
+ `);for(let[t,n]of nf(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${xo(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${bc(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log(`Shortcut: visa-cli generate image "a lobster"
148
+ `)}function Sc(e){if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){console.log(e.content[0].text);return}let t=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),t.length>0){console.log(`
149
+ Result URLs:`);for(let r of t)console.log(` ${r}`);return}let n=JSON.stringify(e,null,2);n&&n!=="{}"&&(console.log(`
150
+ Result:`),console.log(n))}async function of(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools");return Array.isArray(n.tools)?n.tools:[]}function af(e){let t=`
187
151
  Options:
188
152
  `,n=`
189
153
  Commands:
190
- `,r=t.indexOf(e),o=t.indexOf(n);if(r===-1||o===-1||r>o)return t;let s=p=>{let f=t.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return f===-1?t.length:p+1+f},i=s(r),a=s(o),c=t.slice(0,r),u=t.slice(r,i),l=t.slice(o,a),d=t.slice(a);return`${c}${l}${u}${d}`}function Y$e(t){if(!t.startsWith("Usage: "))return t;let e=t.indexOf(`
154
+ `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=h=>{let g=e.slice(h+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:h+1+g},i=o(r),a=o(s),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(s,a),m=e.slice(a);return`${l}${u}${c}${m}`}function cf(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
191
155
 
192
- `);if(e===-1)return t;let n=t.slice(0,e),r=t.slice(e+2),o=r.indexOf(`
156
+ `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
193
157
 
194
- `);if(o===-1)return t;let s=r.slice(0,o),i=r.slice(o+2);return s.trim()?`${s}
158
+ `);if(s===-1)return e;let o=r.slice(0,s),i=r.slice(s+2);return o.trim()?`${o}
195
159
 
196
160
  ${n}
197
161
 
198
- ${i}`:t}function K$e(t){return t.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(e,n,r,o)=>{let s=o.split(`
199
- `).map(i=>{let a=i.match(/^(\s{2})(\S+)(?:\s+(?:\[options\]|\[[^\]]+\]|<[^>]+>))*?(\s{2,})(\S.*)$/);if(!a)return i;let[,c,u,,l]=a,d=i.indexOf(l),p=Math.max(2,d-c.length-u.length);return`${c}${u}${" ".repeat(p)}${l}`}).join(`
200
- `);return`${n}${r}${s}`})}function W$e(t){return t.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function z$e(t){return t.replace(/^Options:$/gm,"Flags:")}function tQ(t){let e=t.helpInformation.bind(t);t.helpInformation=()=>z$e(W$e(K$e(q$e(Y$e(e())))));for(let n of t.commands)tQ(n)}function X$e(t){let e=new Map(t.map((r,o)=>[r,o]));ze.commands.sort((r,o)=>{let s=e.get(r.name())??Number.MAX_SAFE_INTEGER,i=e.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}ze.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(kp().version).addHelpCommand(!1);ze.hook("preAction",async()=>{await Iv()});ze.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Claude Code HUD during setup").option("--no-hud","Do not install the HUD during setup (default)").action(async t=>{try{if(t.check){let f=yl();JZ(f,"MCP config check:"),f.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let e=yl(),n=new Map(e.map(f=>[f.client.id,f])),r=new Set,o=new Set,s=new Set;for(let f of Sr)if(Al(f)){let E;try{E=Rl(f)}catch(R){if(R instanceof oc){KZ(R),o.add(f.displayName),s.add(f.id);continue}throw R}let S=n.get(f.id),h=S?` \u2014 repaired stale ${S.staleReason} entry`:"";console.log(` \u2713 ${f.displayName} (${E.configPath.replace(pt.homedir(),"~")})${h}`),S&&r.add(f.id)}let i=e.filter(f=>!r.has(f.client.id)&&!s.has(f.client.id)),a=0;for(let f of i){try{mT(f)}catch(E){if(E instanceof oc){KZ(E),o.add(f.client.displayName),s.add(f.client.id);continue}throw E}console.log(` \u2713 ${f.client.displayName} (${f.configPath.replace(pt.homedir(),"~")}) \u2014 repaired stale ${f.staleReason} entry`),a++}let c=r.size+a;c===0&&o.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):c>0&&console.log(` \u2713 Repaired ${c} stale MCP config ${c===1?"entry":"entries"}.`),o.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(o).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
201
- Step 2: Checking authentication...`);let u=await Ae.getSessionToken();if(u)try{await new $n(()=>Promise.resolve(u)).getStatus(),console.log(" Already authenticated.")}catch(f){let E=f instanceof Error?f.message:"";E.includes("session has expired")||E.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await Ae.clearAll(),u=null):console.log(` Couldn't verify session (${E||"unknown error"}) \u2014 continuing with existing token.`)}if(!u){let f=null;try{let{stdout:E}=await mv("gh",["auth","token"],{timeout:5e3});f=E.trim()}catch{}if(f||(f=process.env.GITHUB_TOKEN||null),f)try{console.log(" Found GitHub token \u2014 attempting headless login...");let E=await globalThis.fetch(`${Hn()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:f}),signal:AbortSignal.timeout(1e4)});if(E.ok){let S=await E.json();if(S.success&&S.sessionToken){let h=S.sessionToken;u=h,await Ae.saveSessionToken(h),console.log(` Signed in as ${S.user} (headless).`)}}else(await E.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(u||(console.log(" No session found. Opening browser for GitHub login..."),u=await new Promise(async(f,E)=>{let S=Np.randomUUID(),h=`${Hn()}/login?state=${S}`;await rh(h);let R=3e4,A=300*1e3,O=Date.now()+A;for(;Date.now()<O;)try{let y=await globalThis.fetch(`${Hn()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:S,timeout:R}),signal:AbortSignal.timeout(R+5e3)});if(!y.ok){await us(y,I=>{T.warn("auth_status:retry_after_http_error",{status:y.status,delayMs:I})});continue}let M=await y.json();if(M.status==="pending")continue;if(M.status==="expired"){E(new Error("Session expired. Please run setup again."));return}if(M.status==="complete"&&M.sessionToken){console.log(` Signed in as ${M.user}.`),f(M.sessionToken);return}}catch{await us(void 0,y=>{T.warn("auth_status:retry_after_network_error",{delayMs:y})})}E(new Error("Login timed out after 5 minutes. Please run setup again."))}),await Ae.saveSessionToken(u),console.log(" Session token saved.")),console.log(`
202
- Step 3: Setting up authentication...`),!it())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await mv("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}try{let f=await a_();console.log(" Attestation key generated."),await Vt().registerAttestationKey(f),console.log(" Attestation key registered with server.")}catch(f){let E=f?.message||"unknown error";x$e(E)&&(console.error(" Server already has a biometric key for this account, but this device cannot prove access to it."),console.error(" Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again."),process.exit(1)),console.log(` Skipped: ${E}`)}}let l=os.join(pt.homedir(),".claude","settings.json"),d=Ur.existsSync(os.join(pt.homedir(),".claude.json"));if(t.hud===!0)if(!d)console.log(`
162
+ ${i}`:e}function lf(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
163
+ `).map(i=>{let a=i.match(/^(\s{2})(\S+)(?:\s+(?:\[options\]|\[[^\]]+\]|<[^>]+>))*?(\s{2,})(\S.*)$/);if(!a)return i;let[,l,c,,u]=a,m=i.indexOf(u),h=Math.max(2,m-l.length-c.length);return`${l}${c}${" ".repeat(h)}${u}`}).join(`
164
+ `);return`${n}${r}${o}`})}function uf(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function df(e){return e.replace(/^Options:$/gm,"Flags:")}function wc(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>df(uf(lf(af(cf(t())))));for(let n of e.commands)wc(n)}function mf(e){let t=new Map(e.map((r,s)=>[r,s]));q.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}q.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Gn().version).addHelpCommand(!1);q.hook("preAction",async()=>{await Oo()});q.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Claude Code HUD during setup").option("--no-hud","Do not install the HUD during setup (default)").action(async e=>{try{if(e.check){let g=Un();_c(g,"MCP config check:"),g.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=Un(),n=new Map(t.map(g=>[g.client.id,g])),r=new Set,s=new Set,o=new Set;for(let g of Re)if(On(g)){let x;try{x=Nn(g)}catch(j){if(j instanceof cn){fc(j),s.add(g.displayName),o.add(g.id);continue}throw j}let O=n.get(g.id),F=O?` \u2014 repaired stale ${O.staleReason} entry`:"";console.log(` \u2713 ${g.displayName} (${x.configPath.replace(W.homedir(),"~")})${F}`),O&&r.add(g.id)}let i=t.filter(g=>!r.has(g.client.id)&&!o.has(g.client.id)),a=0;for(let g of i){try{_o(g)}catch(x){if(x instanceof cn){fc(x),s.add(g.client.displayName),o.add(g.client.id);continue}throw x}console.log(` \u2713 ${g.client.displayName} (${g.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${g.staleReason} entry`),a++}let l=r.size+a;l===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):l>0&&console.log(` \u2713 Repaired ${l} stale MCP config ${l===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
165
+ Step 2: Checking authentication...`);let c=await D.getSessionToken();if(c)try{await new ve(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(g){let x=g instanceof Error?g.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await D.clearAll(),c=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let g=null;try{let{stdout:x}=await bo("gh",["auth","token"],{timeout:5e3});g=x.trim()}catch{}if(g||(g=process.env.GITHUB_TOKEN||null),g)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${_e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:g}),signal:AbortSignal.timeout(1e4)});if(x.ok){let O=await x.json();if(O.success&&O.sessionToken){let F=O.sessionToken;c=F,await D.saveSessionToken(F),console.log(` Signed in as ${O.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(c||(console.log(" No session found. Opening browser for GitHub login..."),c=await new Promise(async(g,x)=>{let O=Ln.randomUUID(),F=`${_e()}/login?state=${O}`;await os(F);let j=3e4,k=300*1e3,P=Date.now()+k;for(;Date.now()<P;)try{let U=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:O,timeout:j}),signal:AbortSignal.timeout(j+5e3)});if(!U.ok){await tt(U,Y=>{d.warn("auth_status:retry_after_http_error",{status:U.status,delayMs:Y})});continue}let J=await U.json();if(J.status==="pending")continue;if(J.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(J.status==="complete"&&J.sessionToken){console.log(` Signed in as ${J.user}.`),g(J.sessionToken);return}}catch{await tt(void 0,U=>{d.warn("auth_status:retry_after_network_error",{delayMs:U})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await D.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
166
+ Step 3: Setting up authentication...`),!z())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await bo("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}try{let g=await hr();console.log(" Attestation key generated."),await oe().registerAttestationKey(g),console.log(" Attestation key registered with server.")}catch(g){let x=g?.message||"unknown error";Wp(x)&&(console.error(" Server already has a biometric key for this account, but this device cannot prove access to it."),console.error(" Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again."),process.exit(1)),console.log(` Skipped: ${x}`)}}let u=Ze.join(W.homedir(),".claude","settings.json"),m=Ie.existsSync(Ze.join(W.homedir(),".claude.json"));if(e.hud===!0)if(!m)console.log(`
203
167
  Step 4: HUD requested, but Claude Code config was not detected.`),console.log(" Skipped. Enable later with: visa-cli config hud enable");else{console.log(`
204
- Step 4: Enabling the Visa spend HUD...`);let f=$p(l),E=f.installed==="new"||f.installed==="already-visa"||f.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${E}${f.message}`);try{let S=Vt(),h=await S.getStatus(),R={currentVersion:S.getClientVersion(),latestVersion:S.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Vr()},A=Hh(h,R);$h(A,h),console.log(` Preview: ${A.split(`
205
- `)[0]}`)}catch{}}let p="\x1B[1m",_="\x1B[0m";console.log(`
168
+ Step 4: Enabling the Visa spend HUD...`);let g=Zn(u),x=g.installed==="new"||g.installed==="already-visa"||g.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${g.message}`);try{let O=oe(),F=await O.getStatus(),j={currentVersion:O.getClientVersion(),latestVersion:O.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Me()},k=Bs(F,j);Hs(k,F),console.log(` Preview: ${k.split(`
169
+ `)[0]}`)}catch{}}let h="\x1B[1m",v="\x1B[0m";console.log(`
206
170
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
207
171
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
208
172
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -210,64 +174,64 @@ Step 4: Enabling the Visa spend HUD...`);let f=$p(l),E=f.installed==="new"||f.in
210
174
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
211
175
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
212
176
 
213
- ${p}Setup complete.${_} Restart Claude Code or run /mcp to connect.
177
+ ${h}Setup complete.${v} Restart Claude Code or run /mcp to connect.
214
178
 
215
- ${p}Try it out:${_}
179
+ ${h}Try it out:${v}
216
180
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
217
181
  \u2022 Ask Claude: "What's the price of ETH on Base?"
218
182
  \u2022 Check balance: visa-cli balance show
219
183
 
220
- ${p}Enable the HUD${_} \u2014 see live spend + context in Claude Code:
184
+ ${h}Enable the HUD${v} \u2014 see live spend + context in Claude Code:
221
185
  visa-cli config hud enable
222
186
 
223
- ${p}Verify:${_} visa-cli status
224
- ${p}Docs:${_} https://visacli.sh
225
- `)}catch(e){console.error("Error:",e.message),process.exit(1)}});ze.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(t,e)=>{try{if(e.check){let s=yl();JZ(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(e.repair){let s=yl();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)mT(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(pt.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
226
- Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(e.list){console.log(`
187
+ ${h}Verify:${v} visa-cli status
188
+ ${h}Docs:${v} https://visacli.sh
189
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});q.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Un();_c(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Un();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)_o(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
190
+ Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
227
191
  \x1B[1mSupported MCP Clients\x1B[0m
228
- `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of Sr){let c=Al(a),u=ib(a),l=c?"Yes":"No",d=u?"Yes":"No",p=a.globalConfigPath.replace(pt.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${l.padEnd(10)} ${d.padEnd(11)} ${p}`)}console.log("");return}let n=e.scope==="project"?"project":"global";if(e.all){let s=[],i=[];for(let a of Sr){if(!Al(a)){i.push(a.displayName);continue}Rl(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}t||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
229
- Supported clients: ${Sr.map(s=>s.id).join(", ")}`),process.exit(1));let r=lT(t);r||(console.error(`Unknown client: ${t}`),console.error(`Supported clients: ${Sr.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Al(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Rl(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});ze.command("pay <url>",{hidden:!0}).description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(t,e)=>{try{console.warn("Warning: `visa-cli pay` is deprecated and will be removed in a future release.\n Use the MCP `pay` tool via Claude Code or Cursor instead.\n See: https://github.com/Visa-Crypto-Labs/Visa-mono/issues/1913\n"),XP(t);let n=JP(e.method),r=ZP(e.body),o=new $n(()=>Ae.getSessionToken());console.log(`Checking payment for ${t}...`);let s=QP(await o.paymentPreview({url:t}));console.log(` Merchant: ${s.merchantName}`),console.log(` Amount: $${s.amount.toFixed(2)} ${s.currency}`),console.log(` Rail: auto-detected
230
- `);let a=(await o.getStatus()).attestationRequired!==!1;a&&!it()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let c=Np.randomUUID(),u=await ec(o,async()=>{let l;if(a&&it())try{let{nonce:d}=await o.getAttestationChallenge(),p=Buffer.from(JSON.stringify({nonce:d,amount:s.amount,merchant:s.merchantName,context:t})).toString("base64");l={signature:await Ka(p,`pay $${s.amount.toFixed(2)} to ${s.merchantName}`),nonce:d,amount:s.amount,merchant:s.merchantName}}catch(d){throw new Error(`Touch ID confirmation failed: ${d?.message||"user cancelled or biometric error"}`)}return o.pay({url:t,method:n,body:r,attestation:l,idempotencyKey:c})});if(u.success){if(console.log(`Payment complete: $${(u.amount??s.amount).toFixed(2)} \u2192 ${u.merchantName??s.merchantName}`),u.receipt?.urls?.length){console.log(`
231
- Result URLs:`);for(let l of u.receipt.urls)console.log(` ${l}`)}}else console.error(`Payment failed: ${u.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof hn?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});ze.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Op=!1;try{let t=Vt(),e=await t.getStatus(),n={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Vr()},r=await t.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
232
- `)}return{transactions:[]}});process.stdout.write(WP(e,Array.isArray(r?.transactions)?r.transactions:[],it(),n)),Op=!0}catch(t){Op=!1,console.error("Error:",t.message),process.exit(1)}});var hv=ze.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1);function Tv(t){let e=t instanceof Error?t.message:String(t);console.error("Error:",e),e.includes("Not logged in")&&(console.error(""),console.error("Hint: if `visa-cli status` or `visa-cli setup` says you are authenticated, this process may not have access to your macOS Keychain."),console.error("In sandboxed agents such as Codex, rerun the tokens command with keychain access or run it from a normal terminal.")),process.exit(1)}hv.command("create [label]").description("Create an API token for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100 (default: server default)").option("--json","Output raw JSON").action(async(t,e)=>{try{let r=await Vt().createAppApiKey({label:k$e(t),allowed_tools:V$e(e.tools),daily_cap_cents:B$e(e.dailyCap)});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${ZZ(r.allowed_tools)}`),console.log(`Daily cap: ${Sv(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("WARNING: Biometric (Touch ID) is currently ON for this account."),console.log("API tokens bypass biometric verification. Calls will fail with an"),console.log("attestation error until you disable biometric:"),console.log(""),console.log(" visa-cli config biometric off"),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass biometric verification. If you later"),console.log("enable biometric, API key calls will fail until you turn it off."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${Hn()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){Tv(n)}});hv.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async t=>{try{let n=await Vt().listAppApiKeys();if(t.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let o of r)console.log(`${o.id}. ${o.label} (${o.key_prefix})`),console.log(` Status: ${o.status}`),console.log(` Owner: ${o.owner}`),console.log(` Allowed tools: ${ZZ(o.allowed_tools)}`),console.log(` Daily cap: ${Sv(o.daily_cap_cents)}/day`),console.log(` Last used: ${o.last_used_at||"never"}`)}catch(e){Tv(e)}});hv.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async t=>{try{let e=Number(t);if(!Number.isInteger(e)||e<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await Vt().revokeAppApiKey(e);console.log(`Revoked API token ${r.revoked}.`)}catch(e){Tv(e)}});async function nQ(){try{console.log(`Resetting Visa CLI...
233
- `);let t=Vt();await U$e(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await Ae.clearAll(),console.log(" Keychain credentials cleared."),it())try{await c_(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
234
- Reset complete.`)}catch(t){console.error("Error:",t.message),process.exit(1)}}ze.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(nQ);var J$e=100,rQ=ze.command("balance").description("Manage prepaid balance").addHelpCommand(!1);rQ.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let e=await new $n(()=>Ae.getSessionToken()).getBalance();if(console.log(`
235
- Balance: ${Ev(e.balanceMicros,e.balanceCents)}
236
- `),e.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
237
- `);return}let n=e.ledger.slice(0,20),r=[],o=e.balanceCents,s=e.balanceMicros?BigInt(e.balanceMicros):null;for(let l of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&l.deltaMicros?s-=BigInt(l.deltaMicros):(s=null,o-=l.deltaCents);let i=19,a=11,c=13,u=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(u)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(u)} ${"\u2500".repeat(20)}`),n.forEach((l,d)=>{let p=(l.createdAt||"").slice(0,19),_=Ev(l.deltaMicros,l.deltaCents,!0),f=w$e(r[d]),E=(l.reason??"").slice(0,u),S=l.toolName??"";console.log(` ${p.padEnd(i)} ${_.padStart(a)} ${f.padStart(c)} ${E.padEnd(u)} ${S}`)}),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});rQ.command("topup").description("Top up prepaid balance from your default card (Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async t=>{try{let e=parseFloat(t.amount);if(!Number.isFinite(e)||e<=0)throw new Error("amount must be a positive number");let n=Math.round(e*100);if(n<J$e)throw new Error("minimum top-up is $1.00");let r=new $n(()=>Ae.getSessionToken()),s=(await r.getStatus()).attestationRequired!==!1;s&&!it()&&console.warn("Warning: Touch ID unavailable on this system \u2014 top-up will proceed without biometric attestation.");let i=Np.randomUUID(),a=await ec(r,async()=>{let c;if(s&&it()){let{nonce:u}=await r.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:u,amount:e,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");c={signature:await Ka(l,`top up balance with $${e.toFixed(2)}`),nonce:u,amount:e,merchant:"Visa CLI Balance"}}return r.topupBalance({amount_cents:n,idempotency_key:i,attestation:c})});if(a.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((a.balanceCents??0)/100).toFixed(2)}`),a.transactionId&&console.log(`Transaction: ${a.transactionId}`);else{let c=a.error_code?` [${a.error_code}]`:"";console.error(`Top-up failed${c}: ${a.error||"Unknown error"}`),process.exit(1)}}catch(e){console.error("Error:",e.message),process.exit(1)}});var Z$e=ze.command("session",{hidden:!0}).description("Inspect session budgets");Z$e.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async t=>{try{if(!t||t.length===0)throw new Error("session id required");let e=new $n(()=>Ae.getSessionToken()),[n,r]=await Promise.allSettled([e.getSessionBudget(t),e.getSessionLedger(t)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${t}`),process.exit(1)),console.log(`
238
- Session: ${t}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),c=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${c}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
239
- PSP References (CyberSource activity):`);let i=8,a=9,c=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(c)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(19)}`);for(let u of s.ledger){let l=`$${(u.amountCents/100).toFixed(2)}`;console.log(` ${u.type.padEnd(i)} ${l.padStart(a)} ${(u.transactionId||"").padEnd(c)} ${(u.createdAt||"").slice(0,19)}`)}}else o&&console.log(`
240
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});async function oQ(t){(!t||t.trim().length===0)&&(console.log('Usage: visa-cli config feedback "your message"'),process.exit(1));try{await Ae.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await Vt().feedback(t.trim()),console.log("Feedback submitted. Thanks!")}catch(e){console.error("Error:",e.message),process.exit(1)}}ze.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(oQ);ze.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let t=kh();try{console.log(`Updating Visa CLI with ${t.packageManager}: ${t.display}`);let{stdout:e,stderr:n}=await mv(t.command,t.args,{timeout:5*6e4,maxBuffer:10*1024*1024});e.trim()&&process.stdout.write(e),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(e){console.error(`Update failed while running: ${t.display}`),console.error(e?.message??String(e)),process.exit(1)}});var ss=ze.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1);ss.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(oQ);ss.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async t=>{try{let e=Vt(),n=await T_({api:e,includeDev:!!t.dev});if(t.json){console.log(aP(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(iP(n.entries,{verbose:!!t.verbose}))}catch(e){console.error("Error:",e.message),process.exit(1)}});function Q$e(){return Object.entries(ps).map(([t,e])=>` ${t.padEnd(22)} (${e.type}) ${e.description}`).join(`
241
- `)}ss.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
192
+ `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of Re){let l=On(a),c=pc(a),u=l?"Yes":"No",m=c?"Yes":"No",h=a.globalConfigPath.replace(W.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${m.padEnd(11)} ${h}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of Re){if(!On(a)){i.push(a.displayName);continue}Nn(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
193
+ Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=po(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!On(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Nn(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("pay <url>",{hidden:!0}).description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{console.warn("Warning: `visa-cli pay` is deprecated and will be removed in a future release.\n Use the MCP `pay` tool via Claude Code or Cursor instead.\n See: https://github.com/Visa-Crypto-Labs/Visa-mono/issues/1913\n"),rc(e);let n=sc(t.method),r=oc(t.body),s=new ve(()=>D.getSessionToken());console.log(`Checking payment for ${e}...`);let o=ic(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
194
+ `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let l=Ln.randomUUID(),c=await rn(s,async()=>{let u;if(a&&z())try{let{nonce:m}=await s.getAttestationChallenge(),h=Buffer.from(JSON.stringify({nonce:m,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await Yt(h,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:m,amount:o.amount,merchant:o.merchantName}}catch(m){throw new Error(`Touch ID confirmation failed: ${m?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:l})});if(c.success){if(console.log(`Payment complete: $${(c.amount??o.amount).toFixed(2)} \u2192 ${c.merchantName??o.merchantName}`),c.receipt?.urls?.length){console.log(`
195
+ Result URLs:`);for(let u of c.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${c.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof ge?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});q.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Dn=!1;try{let e=oe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
196
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()};process.stdout.write(tc(t,Array.isArray(n?.transactions)?n.transactions:[],z(),r)),Dn=!0}catch(e){Dn=!1,console.error("Error:",e.message),process.exit(1)}});var Co=q.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1);function ko(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),t.includes("Not logged in")&&(console.error(""),console.error("Hint: if `visa-cli status` or `visa-cli setup` says you are authenticated, this process may not have access to your macOS Keychain."),console.error("In sandboxed agents such as Codex, rerun the tokens command with keychain access or run it from a normal terminal.")),process.exit(1)}Co.command("create [label]").description("Create an API token for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100 (default: server default)").option("--json","Output raw JSON").action(async(e,t)=>{try{let r=await oe().createAppApiKey({label:Xp(e),allowed_tools:Qp(t.tools),daily_cap_cents:ef(t.dailyCap)});if(t.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${vc(r.allowed_tools)}`),console.log(`Daily cap: ${wo(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("WARNING: Biometric (Touch ID) is currently ON for this account."),console.log("API tokens bypass biometric verification. Calls will fail with an"),console.log("attestation error until you disable biometric:"),console.log(""),console.log(" visa-cli config biometric off"),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass biometric verification. If you later"),console.log("enable biometric, API key calls will fail until you turn it off."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${_e()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){ko(n)}});Co.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await oe().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let s of r)console.log(`${s.id}. ${s.label} (${s.key_prefix})`),console.log(` Status: ${s.status}`),console.log(` Owner: ${s.owner}`),console.log(` Allowed tools: ${vc(s.allowed_tools)}`),console.log(` Daily cap: ${wo(s.daily_cap_cents)}/day`),console.log(` Last used: ${s.last_used_at||"never"}`)}catch(t){ko(t)}});Co.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await oe().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){ko(t)}});async function xc(){try{console.log(`Resetting Visa CLI...
197
+ `);let e=oe();await Yp(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await D.clearAll(),console.log(" Keychain credentials cleared."),z())try{await yr(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
198
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}q.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(xc);var pf=100,Cc=q.command("balance").description("Manage prepaid balance").addHelpCommand(!1);Cc.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new ve(()=>D.getSessionToken()).getBalance();if(console.log(`
199
+ Balance: ${So(t.balanceMicros,t.balanceCents)}
200
+ `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
201
+ `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,m)=>{let h=(u.createdAt||"").slice(0,19),v=So(u.deltaMicros,u.deltaCents,!0),g=Zp(r[m]),x=(u.reason??"").slice(0,c),O=u.toolName??"";console.log(` ${h.padEnd(i)} ${v.padStart(a)} ${g.padStart(l)} ${x.padEnd(c)} ${O}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Cc.command("topup").description("Top up prepaid balance from your default card (Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=parseFloat(e.amount);if(!Number.isFinite(t)||t<=0)throw new Error("amount must be a positive number");let n=Math.round(t*100);if(n<pf)throw new Error("minimum top-up is $1.00");let r=new ve(()=>D.getSessionToken()),o=(await r.getStatus()).attestationRequired!==!1;o&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 top-up will proceed without biometric attestation.");let i=Ln.randomUUID(),a=await rn(r,async()=>{let l;if(o&&z()){let{nonce:c}=await r.getAttestationChallenge(),u=Buffer.from(JSON.stringify({nonce:c,amount:t,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");l={signature:await Yt(u,`top up balance with $${t.toFixed(2)}`),nonce:c,amount:t,merchant:"Visa CLI Balance"}}return r.topupBalance({amount_cents:n,idempotency_key:i,attestation:l})});if(a.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((a.balanceCents??0)/100).toFixed(2)}`),a.transactionId&&console.log(`Transaction: ${a.transactionId}`);else{let l=a.error_code?` [${a.error_code}]`:"";console.error(`Top-up failed${l}: ${a.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var ff=q.command("session",{hidden:!0}).description("Inspect session budgets");ff.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new ve(()=>D.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
202
+ Session: ${e}`),s){let i=(s.totalCents/100).toFixed(2),a=(s.cumulativeCents/100).toFixed(2),l=(s.remainingCents/100).toFixed(2);console.log(` Status: ${s.status}${s.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${l}`),console.log(` Created: ${s.createdAt}`),console.log(` Expires: ${s.expiresAt}`)}if(o?.ledger?.length){console.log(`
203
+ PSP References (CyberSource activity):`);let i=8,a=9,l=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(l)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(19)}`);for(let c of o.ledger){let u=`$${(c.amountCents/100).toFixed(2)}`;console.log(` ${c.type.padEnd(i)} ${u.padStart(a)} ${(c.transactionId||"").padEnd(l)} ${(c.createdAt||"").slice(0,19)}`)}}else s&&console.log(`
204
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function kc(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli config feedback "your message"'),process.exit(1));try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await oe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}q.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(kc);q.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=js();try{console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:t,stderr:n}=await bo(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});t.trim()&&process.stdout.write(t),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(t){console.error(`Update failed while running: ${e.display}`),console.error(t?.message??String(t)),process.exit(1)}});var Xe=q.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1);Xe.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(kc);Xe.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=oe(),n=await $r({api:t,includeDev:!!e.dev});if(e.json){console.log(fa(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(pa(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function gf(){return Object.entries(st).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
205
+ `)}Xe.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
242
206
  Settable keys:
243
- ${Q$e()}`).action((t,e)=>{try{let n=Kp(t,e);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof yo||n instanceof Oo||n instanceof ls?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});ss.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(t=>{try{let e=Wp(t);e.removed?(console.log(`Removed ${e.key} from ${e.path}`),e.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${e.key} was not set in ${e.path}.`)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}});ss.command("reset").description("Log out and clear all credentials").action(nQ);var Av=ss.command("biometric").description("Manage Touch ID / biometric attestation enforcement");Av.command("status").description("Show current biometric enforcement state").action(async()=>{try{await Ae.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await Vt().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=it();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(t){console.error("Error:",t.message),process.exit(1)}});Av.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await Ae.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let e=Vt(),n=await e.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await e.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(t){console.error("Error:",t.message),process.exit(1)}});Av.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await Ae.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let e=Vt(),n=await e.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!it()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await ec(e,async()=>{let o;if(n.hasAttestationKey&&it())try{let{nonce:s}=await e.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Ka(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return e.setBiometricPreference({required:!1,attestation:o})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(t){console.error("Error:",t.message),process.exit(1)}});var Ua=ss.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1);function Yg(){let t=m_();t.installed||(console.error(t.message),process.exit(1)),console.log(t.message)}function Kg(){let t=E_();t.removed||(console.error(t.message),process.exit(1)),console.log(t.message)}Ua.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Yg);Ua.command("enable").description("Enable the persistent shell HUD").action(Yg);Ua.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Kg);Ua.command("disable").description("Disable the persistent shell HUD").action(Kg);Ua.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${S_()}
244
- `)});Ua.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:t,readFileSync:e}=await import("fs"),n=!0,r=(d,p,_)=>{console.log(` ${p?"\u2713":"\u2717"} ${d}: ${_}`),p||(n=!1)};console.log(`Shell HUD Doctor
245
- `);let o=Qa();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=ll(o),p=t(d);if(r("RC file exists",p,d.replace(pt.homedir(),"~")),p){let f=e(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!f,f?"found in rc file":"missing \u2014 run: visa-cli config shell-hud install")}}let s=Ja(),i=t(s);if(r("Cache file",i,i?s.replace(pt.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(e(s,"utf-8")),p=Date.now()-(d.renderedAt??0),_=Math.round(p/1e3),f=_<=30;console.log(` ${f?"\u2713":"\u26A0"} Cache freshness: ${_}s old${f?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=__(),c=t(a),u="missing";if(c)try{u=e(a,"utf-8").trim().slice(0,80)}catch{u="unreadable"}r("Line file",c,u);let l=!1;try{l=!!await Ae.getSessionToken()}catch{}if(r("Auth token",l,l?"found in keychain":"missing \u2014 run: visa-cli setup"),l)try{await Vt().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let p=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,p)}console.log(n?`
207
+ ${gf()}`).action((e,t)=>{try{let n=nr(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof Fe||n instanceof Be||n instanceof nt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Xe.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=rr(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});Xe.command("reset").description("Log out and clear all credentials").action(xc);var To=Xe.command("biometric").description("Manage Touch ID / biometric attestation enforcement");To.command("status").description("Show current biometric enforcement state").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await oe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=z();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});To.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});To.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!z()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await rn(t,async()=>{let s;if(n.hasAttestationKey&&z())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Yt(l,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var jt=Xe.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1);function zr(){let e=Cr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Wr(){let e=kr();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}jt.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(zr);jt.command("enable").description("Enable the persistent shell HUD").action(zr);jt.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Wr);jt.command("disable").description("Disable the persistent shell HUD").action(Wr);jt.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
208
+ `)});jt.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(m,h,v)=>{console.log(` ${h?"\u2713":"\u2717"} ${m}: ${v}`),h||(n=!1)};console.log(`Shell HUD Doctor
209
+ `);let s=nn();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let m=xn(s),h=e(m);if(r("RC file exists",h,m.replace(W.homedir(),"~")),h){let g=t(m,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config shell-hud install")}}let o=en(),i=e(o);if(r("Cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let m=JSON.parse(t(o,"utf-8")),h=Date.now()-(m.renderedAt??0),v=Math.round(h/1e3),g=v<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${v}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=wr(),l=e(a),c="missing";if(l)try{c=t(a,"utf-8").trim().slice(0,80)}catch{c="unreadable"}r("Line file",l,c);let u=!1;try{u=!!await D.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await oe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(m){let h=m instanceof Error?m.message:"unknown error";r("API connectivity",!1,h)}console.log(n?`
246
210
  All checks passed.`:`
247
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function sQ(t){if(!(!t.force&&rP()))try{let e=Vt(),n=await e.getStatus(),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Vr()},o=Hh(n,r);$h(o,n)}catch{}finally{ul()}}Ua.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(sQ);var wa=ze.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");wa.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Yg);wa.command("enable").description("Enable the persistent shell HUD").action(Yg);wa.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Kg);wa.command("disable").description("Disable the persistent shell HUD").action(Kg);wa.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${S_()}
248
- `)});wa.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});wa.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(sQ);async function iQ(t){try{let e=await $v(),r=S_().split(`
249
- `)[0],o=oP();if(!e&&r.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
250
- `);return}if(t.json){let i=await Kv(r,e,o);process.stdout.write(`${JSON.stringify(i,null,2)}
251
- `);return}let s=await jv(r,e,o);process.stdout.write(`${s}
252
- `)}catch(e){let n=e instanceof Error?e.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}ss.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(iQ);ze.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(iQ);var Xu=ss.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Xu.description("Show which HUD surfaces are currently enabled").action(()=>{let t="\x1B[1m",e="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
253
- ${t}Visa HUD Status${o}
254
- `);let s=os.join(pt.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(Ur.existsSync(s)){let _=JSON.parse(Ur.readFileSync(s,"utf-8")),f=typeof _.statusLine=="object"?_.statusLine.command:"";i=Ci(f),a=!!_.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${e}\u2717${o}`,u=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${t}Claude Code${o} (statusLine) ${u}`);let l=f_(),d=l?`${n}\u2713${o}`:`${e}\u2717${o}`;console.log(` ${d} ${t}Shell prompt${o} ${l?"installed in shell rc file":"not installed (opt-in)"}`),console.log(`
255
- ${t}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${e}# Claude Code statusLine (recommended)${o}`),l||console.log(` visa-cli config hud enable shell ${e}# zsh/bash prompt line (opt-in)${o}`),i&&l&&console.log(` ${n}All surfaces enabled.${o}`),(i||l)&&console.log(` visa-cli config hud disable [shell] ${e}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${e}# diagnose connectivity${o}`),console.log()});Xu.command("enable").description("Enable the Visa HUD \u2014 auto-detects Claude Code, or specify: shell, codex, all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(t=>{let e=t??"claude",n=lh(e);if(e==="shell"||e==="prompt"){let r=m_();r.installed||(console.error(r.message),process.exit(1)),console.log(r.message);return}if(n||(console.error(`Unknown HUD surface: ${e}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1)),n==="claude"||n==="claude-code"||n==="all"){let r=os.join(pt.homedir(),".claude","settings.json"),o=$p(r);console.log(o.message),(o.installed==="error"||o.installed==="malformed-json")&&process.exit(1)}if(n==="codex"||n==="all"){let r=m_();console.log(r.message),console.log("Codex structured HUD payload is available with: visa-cli config statusline --json"),r.installed||process.exit(1)}});Xu.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, codex, or all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(t=>{let e=t??"claude";if(e==="shell"||e==="prompt"){let s=E_();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=lh(e);n||(console.error(`Unknown HUD surface: ${e}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=os.join(pt.homedir(),".claude","settings.json"),i=oh(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="codex"||n==="all"){let s=E_();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Xu.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let t=!0,e=(c,u,l)=>{console.log(` ${u?"\u2713":"\u2717"} ${c}: ${l}`),u||(t=!1)};console.log(`Visa HUD Doctor
256
- `);let n=os.join(pt.homedir(),".claude","settings.json"),r=!1;try{if(Ur.existsSync(n)){let c=JSON.parse(Ur.readFileSync(n,"utf-8")),u=typeof c.statusLine=="object"?c.statusLine.command:"";r=Ci(u)}}catch{}e("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let o=Qa();if(e("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let c=ll(o),u=Ur.existsSync(c);if(e("RC file exists",u,c.replace(pt.homedir(),"~")),u){let d=Ur.readFileSync(c,"utf-8").includes("visa-cli shell hud v2");console.log(` ${d?"\u2713":"\u2013"} Shell HUD block: ${d?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}let s=Ja(),i=Ur.existsSync(s);if(e("HUD cache file",i,i?s.replace(pt.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let c=JSON.parse(Ur.readFileSync(s,"utf-8")),u=Date.now()-(c.renderedAt??0),l=Math.round(u/1e3),d=l<=30;console.log(` ${d?"\u2713":"\u26A0"} Cache freshness: ${l}s old${d?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{e("Cache readable",!1,"corrupt JSON")}let a=!1;try{a=!!await Ae.getSessionToken()}catch{}if(e("Auth token",a,a?"found in keychain":"missing \u2014 run: visa-cli setup"),a)try{await Vt().getStatus(),e("API connectivity",!0,"GET /v1/status OK")}catch(c){let u=c instanceof Error?c.message:"unknown error";e("API connectivity",!1,u)}console.log(t?`
211
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Tc(e){if(!(!e.force&&ua()))try{let t=oe(),[n,r]=await Promise.allSettled([t.getStatus(),t.getBalance()]);if(n.status==="rejected")throw n.reason;let s=n.value;r.status==="fulfilled"&&r.value.success&&(s.balanceCents=r.value.balanceCents,s.amountUsd=r.value.amountUsd);let o={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()},i=Bs(s,o);Hs(i,s)}catch{}finally{wn()}}jt.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Tc);var Vt=q.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Vt.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(zr);Vt.command("enable").description("Enable the persistent shell HUD").action(zr);Vt.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Wr);Vt.command("disable").description("Disable the persistent shell HUD").action(Wr);Vt.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
212
+ `)});Vt.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Vt.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Tc);async function Ac(e){try{let t=await Wo(),r=Tr().split(`
213
+ `)[0],s=da();if(!t&&r.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
214
+ `);return}if(e.json){let i=await Qo(r,t,s);process.stdout.write(`${JSON.stringify(i,null,2)}
215
+ `);return}let o=await Yo(r,t,s);process.stdout.write(`${o}
216
+ `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Xe.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Ac);q.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Ac);var ln=Xe.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);ln.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
217
+ ${e}Visa HUD Status${s}
218
+ `);let o=Ze.join(W.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(Ie.existsSync(o)){let v=JSON.parse(Ie.readFileSync(o,"utf-8")),g=typeof v.statusLine=="object"?v.statusLine.command:"";i=_t(g),a=!!v.statusLine&&!i}}catch{}let l=i?`${n}\u2713${s}`:`${t}\u2717${s}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${s} (statusLine) ${c}`);let u=xr(),m=u?`${n}\u2713${s}`:`${t}\u2717${s}`;console.log(` ${m} ${e}Shell prompt${s} ${u?"installed in shell rc file":"not installed (opt-in)"}`),console.log(`
219
+ ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),u||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&u&&console.log(` ${n}All surfaces enabled.${s}`),(i||u)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});ln.command("enable").description("Enable the Visa HUD \u2014 auto-detects Claude Code, or specify: shell, codex, all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude",n=ms(t);if(t==="shell"||t==="prompt"){let r=Cr();r.installed||(console.error(r.message),process.exit(1)),console.log(r.message);return}if(n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1)),n==="claude"||n==="claude-code"||n==="all"){let r=Ze.join(W.homedir(),".claude","settings.json"),s=Zn(r);console.log(s.message),(s.installed==="error"||s.installed==="malformed-json")&&process.exit(1)}if(n==="codex"||n==="all"){let r=Cr();console.log(r.message),console.log("Codex structured HUD payload is available with: visa-cli config statusline --json"),r.installed||process.exit(1)}});ln.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, codex, or all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=kr();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=ms(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Ze.join(W.homedir(),".claude","settings.json"),i=is(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="codex"||n==="all"){let o=kr();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});ln.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let e=!0,t=(l,c,u)=>{console.log(` ${c?"\u2713":"\u2717"} ${l}: ${u}`),c||(e=!1)};console.log(`Visa HUD Doctor
220
+ `);let n=Ze.join(W.homedir(),".claude","settings.json"),r=!1;try{if(Ie.existsSync(n)){let l=JSON.parse(Ie.readFileSync(n,"utf-8")),c=typeof l.statusLine=="object"?l.statusLine.command:"";r=_t(c)}}catch{}t("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let s=nn();if(t("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let l=xn(s),c=Ie.existsSync(l);if(t("RC file exists",c,l.replace(W.homedir(),"~")),c){let m=Ie.readFileSync(l,"utf-8").includes("visa-cli shell hud v2");console.log(` ${m?"\u2713":"\u2013"} Shell HUD block: ${m?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}let o=en(),i=Ie.existsSync(o);if(t("HUD cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let l=JSON.parse(Ie.readFileSync(o,"utf-8")),c=Date.now()-(l.renderedAt??0),u=Math.round(c/1e3),m=u<=30;console.log(` ${m?"\u2713":"\u26A0"} Cache freshness: ${u}s old${m?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{t("Cache readable",!1,"corrupt JSON")}let a=!1;try{a=!!await D.getSessionToken()}catch{}if(t("Auth token",a,a?"found in keychain":"missing \u2014 run: visa-cli setup"),a)try{await oe().getStatus(),t("API connectivity",!0,"GET /v1/status OK")}catch(l){let c=l instanceof Error?l.message:"unknown error";t("API connectivity",!1,c)}console.log(e?`
257
221
  All checks passed.`:`
258
- Some checks failed \u2014 see above.`),t||process.exit(1)});Xu.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let t=os.join(pt.homedir(),".claude","settings.json"),e=$p(t);console.log(e.message),(e.installed==="error"||e.installed==="malformed-json")&&process.exit(1)});Xu.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let t=os.join(pt.homedir(),".claude","settings.json"),e=oh(t);console.log(e.message),e.removed||process.exit(1)});var Ju=ze.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1);Ju.description("Discover and run paid merchant tools");Ju.command("list").description("List live platform merchants and the tools they expose").option("--json","Print machine-readable JSON").action(async t=>{try{let e=new $n(()=>Ae.getSessionToken()),n=await e.listPublicMerchants();if(n.length===0){t.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
222
+ Some checks failed \u2014 see above.`),e||process.exit(1)});ln.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Ze.join(W.homedir(),".claude","settings.json"),t=Zn(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});ln.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Ze.join(W.homedir(),".claude","settings.json"),t=is(e);console.log(t.message),t.removed||process.exit(1)});var un=q.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1);un.description("Discover and run paid merchant tools");un.command("list").description("List live platform merchants and the tools they expose").option("--json","Print machine-readable JSON").action(async e=>{try{let t=new ve(()=>D.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
259
223
  No live platform merchants on this auth server.
260
- `);return}let r=await Promise.all(n.map(async a=>{let c=await e.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:c?.title??a.display_name,merchant_of_record:c?.merchant_of_record??a.display_name,upstream:c?.upstream,tools:(c?.routes??[]).filter(u=>u.tool_id).map(u=>({tool_id:u.tool_id,mcp_name:u.tool_id.replace(/-/g,"_"),method:u.method,path:u.path,price_cents:u.price_cents,category:u.category??null,description:u.description??null}))}}));if(t.json){console.log(JSON.stringify({merchants:r},null,2));return}let o="\x1B[1m",s="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let c=a.merchant_of_record!==a.provider?` ${s}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${o}${a.provider}${i}${c} ${s}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${s}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${s}(no routes with tool_id \u2014 agents can't see this merchant yet)${i}`);else for(let u of a.tools){let l=u.category?` ${s}[${u.category}]${i}`:"",d=`$${(u.price_cents/100).toFixed(2)}`;console.log(` ${u.tool_id}${l} ${s}\u2192 Claude: ${u.mcp_name}${i} ${d} ${s}${u.method} ${u.path}${i}`),u.description&&console.log(` ${s}${u.description}${i}`)}console.log()}console.log(` ${s}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
261
- `)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ju.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").action(async t=>{try{let e=Vt(),n=await j$e(e,{query:t.query,category:t.category});if(t.json){console.log(JSON.stringify({tools:n},null,2));return}if(n.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}t.verbose?F$e(n):$$e(n)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ju.command("describe <tool>").description("Show tool schema, price, and examples").action(async t=>{try{let n=await Vt().catalogTool(t,"discover_tools");n||(console.error(`Tool not found: ${t}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
224
+ `);return}let r=await Promise.all(n.map(async a=>{let l=await t.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:l?.title??a.display_name,merchant_of_record:l?.merchant_of_record??a.display_name,upstream:l?.upstream,tools:(l?.routes??[]).filter(c=>c.tool_id).map(c=>({tool_id:c.tool_id,mcp_name:c.tool_id.replace(/-/g,"_"),method:c.method,path:c.path,price_cents:c.price_cents,category:c.category??null,description:c.description??null}))}}));if(e.json){console.log(JSON.stringify({merchants:r},null,2));return}let s="\x1B[1m",o="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let l=a.merchant_of_record!==a.provider?` ${o}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${s}${a.provider}${i}${l} ${o}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${o}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${o}(no routes with tool_id \u2014 agents can't see this merchant yet)${i}`);else for(let c of a.tools){let u=c.category?` ${o}[${c.category}]${i}`:"",m=`$${(c.price_cents/100).toFixed(2)}`;console.log(` ${c.tool_id}${u} ${o}\u2192 Claude: ${c.mcp_name}${i} ${m} ${o}${c.method} ${c.path}${i}`),c.description&&console.log(` ${o}${c.description}${i}`)}console.log()}console.log(` ${o}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
225
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});un.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").action(async e=>{try{let t=oe(),n=await of(t,{query:e.query,category:e.category});if(e.json){console.log(JSON.stringify({tools:n},null,2));return}if(n.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?sf(n):rf(n)}catch(t){console.error("Error:",t.message),process.exit(1)}});un.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await oe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
262
226
  ${n.id}
263
227
  `),console.log(n.description),console.log(`
264
- Price`),console.log(` ${gv(n.priceCents,n.priceDisplay)}`),console.log(`
228
+ Price`),console.log(` ${xo(n.priceCents,n.priceDisplay)}`),console.log(`
265
229
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
266
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set;for(let[s,i]of Object.entries(r)){let a=o.has(s)?"required":"optional",c=i?.description?` - ${i.description}`:"";console.log(` ${s.padEnd(12)} ${a}${c}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
267
- Examples`),console.log(` visa-cli merchants run ${n.id} --json '{"prompt":"a lobster"}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});function eFe(t){return["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"].includes(t)}async function aQ(t,e,n){return eFe(t)?Wa.shortcut(t,e,n):Wa.executeTool({tool_id:t,params:e},n,"execute_tool")}Ju.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(t,e)=>{try{let n=G$e(e.json,"--json");if(e.prompt&&(n.prompt=e.prompt),Object.keys(n).length===0)throw new Error("Provide tool params with --json or --prompt.");console.log(`Running ${t}`);let r=await aQ(t,n,`visa-cli merchants run ${t}`);eQ(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Ju.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
230
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set;for(let[o,i]of Object.entries(r)){let a=s.has(o)?"required":"optional",l=i?.description?` - ${i.description}`:"";console.log(` ${o.padEnd(12)} ${a}${l}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
231
+ Examples`),console.log(` visa-cli merchants run ${n.id} --json '{"prompt":"a lobster"}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function hf(e){return["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"].includes(e)}async function Ec(e,t,n){return hf(e)?Zt.shortcut(e,t,n):Zt.executeTool({tool_id:e,params:t},n,"execute_tool")}un.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(e,t)=>{try{let n=tf(t.json,"--json");if(t.prompt&&(n.prompt=t.prompt),Object.keys(n).length===0)throw new Error("Provide tool params with --json or --prompt.");console.log(`Running ${e}`);let r=await Ec(e,n,`visa-cli merchants run ${e}`);Sc(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});un.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
268
232
  Platform-merchant tool discovery is cached in-process by the MCP server.`),console.log(" Cache TTL: VISA_MERCHANT_DISCOVER_TTL_MS (default 300000ms = 5min)."),console.log(` To force-refresh now, restart Claude / Cursor \u2014 the next tools/list will re-fetch.
269
- `)});var Cp=ze.command("generate").description("Generate media with merchant tools").addHelpCommand(!1);async function vp(t){console.log(`
270
- ${t.kind}
271
- `),console.log(`Using: ${t.toolId}`),console.log(`Prompt: ${t.prompt}
272
- `);let e=await aQ(t.toolId,t.params,`visa-cli generate ${t.kind.toLowerCase()}: ${t.prompt}`);eQ(e)}Cp.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high","standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(t,e)=>{try{let n=e.tool??(e.fast||e.quality!=="high"?"generate_image_fast_card":"generate_image_card");await vp({kind:"Image generation",toolId:n,params:{prompt:t},prompt:t})}catch(n){console.error("Error:",n.message),process.exit(1)}});Cp.command("video <prompt>").description("Generate a video from a prompt").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(t,e)=>{try{let n={prompt:t};e.aspectRatio&&(n.aspect_ratio=e.aspectRatio),e.duration&&(n.duration=Number(e.duration)),await vp({kind:"Video generation",toolId:e.tool??"generate_video_tempo_card",params:n,prompt:t})}catch(n){console.error("Error:",n.message),process.exit(1)}});Cp.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--model <model>","Suno model, when supported","V4").action(async(t,e)=>{try{await vp({kind:"Music generation",toolId:e.tool??"generate_music_tempo_card",params:{prompt:t,instrumental:!!e.instrumental,model:e.model??"V4"},prompt:t})}catch(n){console.error("Error:",n.message),process.exit(1)}});Cp.command("speech <text>").description("Generate speech from text").option("--tool <tool>","Exact tool id override").option("--ref-audio-url <url>","Reference audio URL for voice cloning").option("--ref-text <text>","Transcription of reference audio").option("--remove-silence","Remove silence from generated speech").action(async(t,e)=>{try{let n={gen_text:t};e.refAudioUrl&&(n.ref_audio_url=e.refAudioUrl),e.refText&&(n.ref_text=e.refText),e.removeSilence&&(n.remove_silence=!0),await vp({kind:"Speech generation",toolId:e.tool??"generate_speech_card",params:n,prompt:t})}catch(n){console.error("Error:",n.message),process.exit(1)}});Cp.command("3d <prompt>").alias("model").description("Generate a 3D model from a prompt").option("--tool <tool>","Exact tool id override").option("--style <style>","Style prompt for the generated model").option("--negative <prompt>","Negative prompt").option("--art-style <style>","Art style, when supported by the selected tool").action(async(t,e)=>{try{let n={object_prompt:t};e.style&&(n.style_prompt=e.style),e.negative&&(n.negative_prompt=e.negative),e.artStyle&&(n.art_style=e.artStyle),await vp({kind:"3D generation",toolId:e.tool??"generate_3d_card",params:n,prompt:t})}catch(n){console.error("Error:",n.message),process.exit(1)}});ze.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(t,e)=>{try{let n=e.scope==="project"?"project":"global";if(e.all){let s=[];for(let i of Sr)fT(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}t||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
273
- Supported clients: ${Sr.map(s=>s.id).join(", ")}`),process.exit(1));let r=lT(t);r||(console.error(`Unknown client: ${t}`),console.error(`Supported clients: ${Sr.map(s=>s.id).join(", ")}`),process.exit(1));let o=fT(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});ze.hook("postAction",()=>{if(Op){Op=!1;return}jg&&YP(jg.lastSignals)});X$e(["setup","install","status","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);tQ(ze);ze.parse();
233
+ `)});var jn=q.command("generate").description("Generate media with merchant tools").addHelpCommand(!1);async function Vn(e){console.log(`
234
+ ${e.kind}
235
+ `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
236
+ `);let t=await Ec(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Sc(t)}var yf=(e,t)=>n=>(t.includes(n)||q.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);jn.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high",yf("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n=t.tool??(t.fast||t.quality!=="high"?"generate_image_fast_card":"generate_image_card");await Vn({kind:"Image generation",toolId:n,params:{prompt:e},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("video <prompt>").description("Generate a video from a prompt").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(e,t)=>{try{let n={prompt:e};t.aspectRatio&&(n.aspect_ratio=t.aspectRatio),t.duration&&(n.duration=Number(t.duration)),await Vn({kind:"Video generation",toolId:t.tool??"generate_video_tempo_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--model <model>","Suno model, when supported","V4").action(async(e,t)=>{try{await Vn({kind:"Music generation",toolId:t.tool??"generate_music_tempo_card",params:{prompt:e,instrumental:!!t.instrumental,model:t.model??"V4"},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("speech <text>").description("Generate speech from text").option("--tool <tool>","Exact tool id override").option("--ref-audio-url <url>","Reference audio URL for voice cloning").option("--ref-text <text>","Transcription of reference audio").option("--remove-silence","Remove silence from generated speech").action(async(e,t)=>{try{let n={gen_text:e};t.refAudioUrl&&(n.ref_audio_url=t.refAudioUrl),t.refText&&(n.ref_text=t.refText),t.removeSilence&&(n.remove_silence=!0),await Vn({kind:"Speech generation",toolId:t.tool??"generate_speech_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("3d <prompt>").alias("model").description("Generate a 3D model from a prompt").option("--tool <tool>","Exact tool id override").option("--style <style>","Style prompt for the generated model").option("--negative <prompt>","Negative prompt").option("--art-style <style>","Art style, when supported by the selected tool").action(async(e,t)=>{try{let n={object_prompt:e};t.style&&(n.style_prompt=t.style),t.negative&&(n.negative_prompt=t.negative),t.artStyle&&(n.art_style=t.artStyle),await Vn({kind:"3D generation",toolId:t.tool??"generate_3d_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of Re)yo(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
237
+ Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=po(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let s=yo(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.hook("postAction",()=>{if(Dn){Dn=!1;return}Kr&&Qa(Kr.lastSignals)});mf(["setup","install","status","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);wc(q);q.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});