@iflow-ai/iflow-cli 0.3.24-beta.0 → 0.3.24
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/bundle/iflow.js +7 -7
- package/package.json +1 -1
package/bundle/iflow.js
CHANGED
|
@@ -482,9 +482,9 @@ ${a}`.trim()}_serializeSingularDataPoint(e,r,n){let i="";e=BAt(e,r);let{value:o,
|
|
|
482
482
|
${i}
|
|
483
483
|
${o}
|
|
484
484
|
`}};bIe.PrometheusSerializer=OAt});var z7r=w(CIe=>{"use strict";Object.defineProperty(CIe,"__esModule",{value:!0});CIe.PrometheusExporter=void 0;var Ufe=(Kt(),yt(ar)),$to=si(),PAt=Bx(),Wto=Ae("http"),zto=kAt(),Yto=Ae("url"),MAt=class t extends PAt.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:"/metrics",prefix:"",appendTimestamp:!1,withResourceConstantLabels:void 0};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(e={},r=()=>{}){super({aggregationSelector:i=>({type:PAt.AggregationType.DEFAULT}),aggregationTemporalitySelector:i=>PAt.AggregationTemporality.CUMULATIVE,metricProducers:e.metricProducers}),this._host=e.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||t.DEFAULT_OPTIONS.host,this._port=e.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||t.DEFAULT_OPTIONS.port,this._prefix=e.prefix||t.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof e.appendTimestamp=="boolean"?e.appendTimestamp:t.DEFAULT_OPTIONS.appendTimestamp;let n=e.withResourceConstantLabels||t.DEFAULT_OPTIONS.withResourceConstantLabels;this._server=(0,Wto.createServer)(this._requestHandler).unref(),this._serializer=new zto.PrometheusSerializer(this._prefix,this._appendTimestamp,n),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(e.endpoint||t.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,"/$1"),e.preventServerStart!==!0?this.startServer().then(r,i=>{Ufe.diag.error(i),r(i)}):r&&queueMicrotask(r)}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){return this._server?new Promise(e=>{this._server.close(r=>{r?r.code!=="ERR_SERVER_NOT_RUNNING"&&(0,$to.globalErrorHandler)(r):Ufe.diag.debug("Prometheus exporter was stopped"),e()})}):(Ufe.diag.debug("Prometheus stopServer() was called but server was never started."),Promise.resolve())}startServer(){return this._startServerPromise??=new Promise((e,r)=>{this._server.once("error",r),this._server.listen({port:this._port,host:this._host},()=>{Ufe.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),e()})}),this._startServerPromise}getMetricsRequestHandler(e,r){this._exportMetrics(r)}_requestHandler=(e,r)=>{e.url!=null&&new Yto.URL(e.url,this._baseUrl).pathname===this._endpoint?this._exportMetrics(r):this._notFound(r)};_exportMetrics=e=>{e.statusCode=200,e.setHeader("content-type","text/plain"),this.collect().then(r=>{let{resourceMetrics:n,errors:i}=r;i.length&&Ufe.diag.error("PrometheusExporter: metrics collection errors",...i),e.end(this._serializer.serialize(n))},r=>{e.end(`# failed to export metrics: ${r}`)})};_notFound=e=>{e.statusCode=404,e.end()}};CIe.PrometheusExporter=MAt});var Y7r=w(EK=>{"use strict";Object.defineProperty(EK,"__esModule",{value:!0});EK.PrometheusSerializer=EK.PrometheusExporter=void 0;var Kto=z7r();Object.defineProperty(EK,"PrometheusExporter",{enumerable:!0,get:function(){return Kto.PrometheusExporter}});var Jto=kAt();Object.defineProperty(EK,"PrometheusSerializer",{enumerable:!0,get:function(){return Jto.PrometheusSerializer}})});var K7r=w(_Ie=>{"use strict";Object.defineProperty(_Ie,"__esModule",{value:!0});_Ie.VERSION=void 0;_Ie.VERSION="0.206.0"});var X7r=w(xIe=>{"use strict";Object.defineProperty(xIe,"__esModule",{value:!0});xIe.OTLPTraceExporter=void 0;var Xto=(Cx(),yt(bx)),Zto=K7r(),ero=kx(),J7r=(K9(),yt(LR)),LAt=class extends Xto.OTLPExporterBase{constructor(e={}){super((0,J7r.createOtlpHttpExportDelegate)((0,J7r.convertLegacyHttpOptions)(e,"TRACES","v1/traces",{"User-Agent":`OTel-OTLP-Exporter-JavaScript/${Zto.VERSION}`,"Content-Type":"application/json"}),ero.JsonTraceSerializer))}};xIe.OTLPTraceExporter=LAt});var Z7r=w(SIe=>{"use strict";Object.defineProperty(SIe,"__esModule",{value:!0});SIe.OTLPTraceExporter=void 0;var tro=X7r();Object.defineProperty(SIe,"OTLPTraceExporter",{enumerable:!0,get:function(){return tro.OTLPTraceExporter}})});var eIr=w(wIe=>{"use strict";Object.defineProperty(wIe,"__esModule",{value:!0});wIe.OTLPTraceExporter=void 0;var rro=Z7r();Object.defineProperty(wIe,"OTLPTraceExporter",{enumerable:!0,get:function(){return rro.OTLPTraceExporter}})});var tIr=w(TIe=>{"use strict";Object.defineProperty(TIe,"__esModule",{value:!0});TIe.OTLPTraceExporter=void 0;var nro=eIr();Object.defineProperty(TIe,"OTLPTraceExporter",{enumerable:!0,get:function(){return nro.OTLPTraceExporter}})});var nIr=w(IIe=>{"use strict";Object.defineProperty(IIe,"__esModule",{value:!0});IIe.OTLPTraceExporter=void 0;var rIr=lIe(),iro=kx(),oro=(Cx(),yt(bx)),FAt=class extends oro.OTLPExporterBase{constructor(e={}){super((0,rIr.createOtlpGrpcExportDelegate)((0,rIr.convertLegacyOtlpGrpcOptions)(e,"TRACES"),iro.ProtobufTraceSerializer,"TraceExportService","/opentelemetry.proto.collector.trace.v1.TraceService/Export"))}};IIe.OTLPTraceExporter=FAt});var iIr=w(DIe=>{"use strict";Object.defineProperty(DIe,"__esModule",{value:!0});DIe.OTLPTraceExporter=void 0;var sro=nIr();Object.defineProperty(DIe,"OTLPTraceExporter",{enumerable:!0,get:function(){return sro.OTLPTraceExporter}})});var oIr=w(BIe=>{"use strict";Object.defineProperty(BIe,"__esModule",{value:!0});BIe.prepareSend=void 0;var UAt=(Kt(),yt(ar)),RIe=si(),aro=Ae("http"),cro=Ae("https");function lro(t,e){let r=new URL(t),n=Object.assign({method:"POST",headers:{"Content-Type":"application/json",...e}});return function(o,s){if(o.length===0)return UAt.diag.debug("Zipkin send with empty spans"),s({code:RIe.ExportResultCode.SUCCESS});let{request:a}=r.protocol==="http:"?aro:cro,c=a(r,n,d=>{let f="";d.on("data",p=>{f+=p}),d.on("end",()=>{let p=d.statusCode||0;return UAt.diag.debug(`Zipkin response status code: ${p}, body: ${f}`),p<400?s({code:RIe.ExportResultCode.SUCCESS}):s({code:RIe.ExportResultCode.FAILED,error:new Error(`Got unexpected status code from zipkin: ${p}`)})})});c.on("error",d=>s({code:RIe.ExportResultCode.FAILED,error:d}));let u=JSON.stringify(o);UAt.diag.debug(`Zipkin request payload: ${u}`),c.write(u,"utf8"),c.end()}}BIe.prepareSend=lro});var sIr=w(NIe=>{"use strict";Object.defineProperty(NIe,"__esModule",{value:!0});NIe.prepareSend=void 0;var uro=oIr();Object.defineProperty(NIe,"prepareSend",{enumerable:!0,get:function(){return uro.prepareSend}})});var QAt=w(OIe=>{"use strict";Object.defineProperty(OIe,"__esModule",{value:!0});OIe.prepareSend=void 0;var dro=sIr();Object.defineProperty(OIe,"prepareSend",{enumerable:!0,get:function(){return dro.prepareSend}})});var aIr=w(Qfe=>{"use strict";Object.defineProperty(Qfe,"__esModule",{value:!0});Qfe.SpanKind=void 0;var fro;(function(t){t.CLIENT="CLIENT",t.SERVER="SERVER",t.CONSUMER="CONSUMER",t.PRODUCER="PRODUCER"})(fro=Qfe.SpanKind||(Qfe.SpanKind={}))});var uIr=w(qv=>{"use strict";Object.defineProperty(qv,"__esModule",{value:!0});qv._toZipkinAnnotations=qv._toZipkinTags=qv.toZipkinSpan=qv.defaultStatusErrorTagName=qv.defaultStatusCodeTagName=void 0;var oB=(Kt(),yt(ar)),qAt=si(),kIe=aIr(),pro={[oB.SpanKind.CLIENT]:kIe.SpanKind.CLIENT,[oB.SpanKind.SERVER]:kIe.SpanKind.SERVER,[oB.SpanKind.CONSUMER]:kIe.SpanKind.CONSUMER,[oB.SpanKind.PRODUCER]:kIe.SpanKind.PRODUCER,[oB.SpanKind.INTERNAL]:void 0};qv.defaultStatusCodeTagName="otel.status_code";qv.defaultStatusErrorTagName="error";function hro(t,e,r,n){return{traceId:t.spanContext().traceId,parentId:t.parentSpanContext?.spanId,name:t.name,id:t.spanContext().spanId,kind:pro[t.kind],timestamp:(0,qAt.hrTimeToMicroseconds)(t.startTime),duration:Math.round((0,qAt.hrTimeToMicroseconds)(t.duration)),localEndpoint:{serviceName:e},tags:cIr(t,r,n),annotations:t.events.length?lIr(t.events):void 0}}qv.toZipkinSpan=hro;function cIr({attributes:t,resource:e,status:r,droppedAttributesCount:n,droppedEventsCount:i,droppedLinksCount:o},s,a){let c={};for(let u of Object.keys(t))c[u]=String(t[u]);return r.code!==oB.SpanStatusCode.UNSET&&(c[s]=String(oB.SpanStatusCode[r.code])),r.code===oB.SpanStatusCode.ERROR&&r.message&&(c[a]=r.message),n&&(c["otel.dropped_attributes_count"]=String(n)),i&&(c["otel.dropped_events_count"]=String(i)),o&&(c["otel.dropped_links_count"]=String(o)),Object.keys(e.attributes).forEach(u=>c[u]=String(e.attributes[u])),c}qv._toZipkinTags=cIr;function lIr(t){return t.map(e=>({timestamp:Math.round((0,qAt.hrTimeToMicroseconds)(e.time)),value:e.name}))}qv._toZipkinAnnotations=lIr});var dIr=w(PIe=>{"use strict";Object.defineProperty(PIe,"__esModule",{value:!0});PIe.prepareGetHeaders=void 0;function mro(t){return function(){return t()}}PIe.prepareGetHeaders=mro});var mIr=w(MIe=>{"use strict";Object.defineProperty(MIe,"__esModule",{value:!0});MIe.ZipkinExporter=void 0;var fIr=(Kt(),yt(ar)),pIr=si(),hIr=QAt(),HAt=uIr(),GAt=(Nh(),yt(c2)),gro=dIr(),jAt=class{DEFAULT_SERVICE_NAME="OpenTelemetry Service";_statusCodeTagName;_statusDescriptionTagName;_urlStr;_send;_getHeaders;_serviceName;_isShutdown;_sendingPromises=[];constructor(e={}){this._urlStr=e.url||((0,pIr.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT")??"http://localhost:9411/api/v2/spans"),this._send=(0,hIr.prepareSend)(this._urlStr,e.headers),this._serviceName=e.serviceName,this._statusCodeTagName=e.statusCodeTagName||HAt.defaultStatusCodeTagName,this._statusDescriptionTagName=e.statusDescriptionTagName||HAt.defaultStatusErrorTagName,this._isShutdown=!1,typeof e.getExportRequestHeaders=="function"?this._getHeaders=(0,gro.prepareGetHeaders)(e.getExportRequestHeaders):this._beforeSend=function(){}}export(e,r){let n=String(this._serviceName||e[0].resource.attributes[GAt.ATTR_SERVICE_NAME]||this.DEFAULT_SERVICE_NAME);if(fIr.diag.debug("Zipkin exporter export"),this._isShutdown){setTimeout(()=>r({code:pIr.ExportResultCode.FAILED,error:new Error("Exporter has been shutdown")}));return}let i=new Promise(s=>{this._sendSpans(e,n,a=>{s(),r(a)})});this._sendingPromises.push(i);let o=()=>{let s=this._sendingPromises.indexOf(i);this._sendingPromises.splice(s,1)};i.then(o,o)}shutdown(){return fIr.diag.debug("Zipkin exporter shutdown"),this._isShutdown=!0,this.forceFlush()}forceFlush(){return new Promise((e,r)=>{Promise.all(this._sendingPromises).then(()=>{e()},r)})}_beforeSend(){this._getHeaders&&(this._send=(0,hIr.prepareSend)(this._urlStr,this._getHeaders()))}_sendSpans(e,r,n){let i=e.map(o=>(0,HAt.toZipkinSpan)(o,String(o.attributes[GAt.ATTR_SERVICE_NAME]||o.resource.attributes[GAt.ATTR_SERVICE_NAME]||r),this._statusCodeTagName,this._statusDescriptionTagName));return this._beforeSend(),this._send(i,o=>{if(n)return n(o)})}};MIe.ZipkinExporter=jAt});var gIr=w(vK=>{"use strict";Object.defineProperty(vK,"__esModule",{value:!0});vK.ZipkinExporter=vK.prepareSend=void 0;var Aro=QAt();Object.defineProperty(vK,"prepareSend",{enumerable:!0,get:function(){return Aro.prepareSend}});var yro=mIr();Object.defineProperty(vK,"ZipkinExporter",{enumerable:!0,get:function(){return yro.ZipkinExporter}})});var VAt=w(LIe=>{"use strict";Object.defineProperty(LIe,"__esModule",{value:!0});LIe.B3_DEBUG_FLAG_KEY=void 0;var Ero=(Kt(),yt(ar));LIe.B3_DEBUG_FLAG_KEY=(0,Ero.createContextKey)("OpenTelemetry Context Key B3 Debug Flag")});var qfe=w(x3=>{"use strict";Object.defineProperty(x3,"__esModule",{value:!0});x3.X_B3_FLAGS=x3.X_B3_PARENT_SPAN_ID=x3.X_B3_SAMPLED=x3.X_B3_SPAN_ID=x3.X_B3_TRACE_ID=x3.B3_CONTEXT_HEADER=void 0;x3.B3_CONTEXT_HEADER="b3";x3.X_B3_TRACE_ID="x-b3-traceid";x3.X_B3_SPAN_ID="x-b3-spanid";x3.X_B3_SAMPLED="x-b3-sampled";x3.X_B3_PARENT_SPAN_ID="x-b3-parentspanid";x3.X_B3_FLAGS="x-b3-flags"});var EIr=w(UIe=>{"use strict";Object.defineProperty(UIe,"__esModule",{value:!0});UIe.B3MultiPropagator=void 0;var KC=(Kt(),yt(ar)),vro=si(),AIr=VAt(),mE=qfe(),bro=new Set([!0,"true","True","1",1]),Cro=new Set([!1,"false","False","0",0]);function _ro(t){return t===KC.TraceFlags.SAMPLED||t===KC.TraceFlags.NONE}function xro(t){return Array.isArray(t)?t[0]:t}function FIe(t,e,r){let n=e.get(t,r);return xro(n)}function Sro(t,e){let r=FIe(t,e,mE.X_B3_TRACE_ID);return typeof r=="string"?r.padStart(32,"0"):""}function wro(t,e){let r=FIe(t,e,mE.X_B3_SPAN_ID);return typeof r=="string"?r:""}function yIr(t,e){return FIe(t,e,mE.X_B3_FLAGS)==="1"?"1":void 0}function Tro(t,e){let r=FIe(t,e,mE.X_B3_SAMPLED);if(yIr(t,e)==="1"||bro.has(r))return KC.TraceFlags.SAMPLED;if(r===void 0||Cro.has(r))return KC.TraceFlags.NONE}var $At=class{inject(e,r,n){let i=KC.trace.getSpanContext(e);if(!i||!(0,KC.isSpanContextValid)(i)||(0,vro.isTracingSuppressed)(e))return;let o=e.getValue(AIr.B3_DEBUG_FLAG_KEY);n.set(r,mE.X_B3_TRACE_ID,i.traceId),n.set(r,mE.X_B3_SPAN_ID,i.spanId),o==="1"?n.set(r,mE.X_B3_FLAGS,o):i.traceFlags!==void 0&&n.set(r,mE.X_B3_SAMPLED,(KC.TraceFlags.SAMPLED&i.traceFlags)===KC.TraceFlags.SAMPLED?"1":"0")}extract(e,r,n){let i=Sro(r,n),o=wro(r,n),s=Tro(r,n),a=yIr(r,n);return(0,KC.isValidTraceId)(i)&&(0,KC.isValidSpanId)(o)&&_ro(s)?(e=e.setValue(AIr.B3_DEBUG_FLAG_KEY,a),KC.trace.setSpanContext(e,{traceId:i,spanId:o,isRemote:!0,traceFlags:s})):e}fields(){return[mE.X_B3_TRACE_ID,mE.X_B3_SPAN_ID,mE.X_B3_FLAGS,mE.X_B3_SAMPLED,mE.X_B3_PARENT_SPAN_ID]}};UIe.B3MultiPropagator=$At});var bIr=w(QIe=>{"use strict";Object.defineProperty(QIe,"__esModule",{value:!0});QIe.B3SinglePropagator=void 0;var EF=(Kt(),yt(ar)),Iro=si(),vIr=VAt(),WAt=qfe(),Dro=/((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/,Rro="0".repeat(16),Bro=new Set(["d","1"]),Nro="d";function Oro(t){return t.length===32?t:`${Rro}${t}`}function kro(t){return t&&Bro.has(t)?EF.TraceFlags.SAMPLED:EF.TraceFlags.NONE}var zAt=class{inject(e,r,n){let i=EF.trace.getSpanContext(e);if(!i||!(0,EF.isSpanContextValid)(i)||(0,Iro.isTracingSuppressed)(e))return;let o=e.getValue(vIr.B3_DEBUG_FLAG_KEY)||i.traceFlags&1,s=`${i.traceId}-${i.spanId}-${o}`;n.set(r,WAt.B3_CONTEXT_HEADER,s)}extract(e,r,n){let i=n.get(r,WAt.B3_CONTEXT_HEADER),o=Array.isArray(i)?i[0]:i;if(typeof o!="string")return e;let s=o.match(Dro);if(!s)return e;let[,a,c,u]=s,d=Oro(a);if(!(0,EF.isValidTraceId)(d)||!(0,EF.isValidSpanId)(c))return e;let f=kro(u);return u===Nro&&(e=e.setValue(vIr.B3_DEBUG_FLAG_KEY,u)),EF.trace.setSpanContext(e,{traceId:d,spanId:c,isRemote:!0,traceFlags:f})}fields(){return[WAt.B3_CONTEXT_HEADER]}};QIe.B3SinglePropagator=zAt});var YAt=w(Hfe=>{"use strict";Object.defineProperty(Hfe,"__esModule",{value:!0});Hfe.B3InjectEncoding=void 0;var Pro;(function(t){t[t.SINGLE_HEADER=0]="SINGLE_HEADER",t[t.MULTI_HEADER=1]="MULTI_HEADER"})(Pro=Hfe.B3InjectEncoding||(Hfe.B3InjectEncoding={}))});var CIr=w(qIe=>{"use strict";Object.defineProperty(qIe,"__esModule",{value:!0});qIe.B3Propagator=void 0;var Mro=si(),Lro=EIr(),Fro=bIr(),Uro=qfe(),Qro=YAt(),KAt=class{_b3MultiPropagator=new Lro.B3MultiPropagator;_b3SinglePropagator=new Fro.B3SinglePropagator;_inject;_fields;constructor(e={}){e.injectEncoding===Qro.B3InjectEncoding.MULTI_HEADER?(this._inject=this._b3MultiPropagator.inject,this._fields=this._b3MultiPropagator.fields()):(this._inject=this._b3SinglePropagator.inject,this._fields=this._b3SinglePropagator.fields())}inject(e,r,n){(0,Mro.isTracingSuppressed)(e)||this._inject(e,r,n)}extract(e,r,n){let i=n.get(r,Uro.B3_CONTEXT_HEADER);return(Array.isArray(i)?i[0]:i)?this._b3SinglePropagator.extract(e,r,n):this._b3MultiPropagator.extract(e,r,n)}fields(){return this._fields}};qIe.B3Propagator=KAt});var _Ir=w(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});Fm.B3InjectEncoding=Fm.X_B3_TRACE_ID=Fm.X_B3_SPAN_ID=Fm.X_B3_SAMPLED=Fm.X_B3_PARENT_SPAN_ID=Fm.X_B3_FLAGS=Fm.B3_CONTEXT_HEADER=Fm.B3Propagator=void 0;var qro=CIr();Object.defineProperty(Fm,"B3Propagator",{enumerable:!0,get:function(){return qro.B3Propagator}});var bK=qfe();Object.defineProperty(Fm,"B3_CONTEXT_HEADER",{enumerable:!0,get:function(){return bK.B3_CONTEXT_HEADER}});Object.defineProperty(Fm,"X_B3_FLAGS",{enumerable:!0,get:function(){return bK.X_B3_FLAGS}});Object.defineProperty(Fm,"X_B3_PARENT_SPAN_ID",{enumerable:!0,get:function(){return bK.X_B3_PARENT_SPAN_ID}});Object.defineProperty(Fm,"X_B3_SAMPLED",{enumerable:!0,get:function(){return bK.X_B3_SAMPLED}});Object.defineProperty(Fm,"X_B3_SPAN_ID",{enumerable:!0,get:function(){return bK.X_B3_SPAN_ID}});Object.defineProperty(Fm,"X_B3_TRACE_ID",{enumerable:!0,get:function(){return bK.X_B3_TRACE_ID}});var Hro=YAt();Object.defineProperty(Fm,"B3InjectEncoding",{enumerable:!0,get:function(){return Hro.B3InjectEncoding}})});var xIr=w(JC=>{"use strict";Object.defineProperty(JC,"__esModule",{value:!0});JC.JaegerPropagator=JC.UBER_BAGGAGE_HEADER_PREFIX=JC.UBER_TRACE_ID_HEADER=void 0;var vF=(Kt(),yt(ar)),Gro=si();JC.UBER_TRACE_ID_HEADER="uber-trace-id";JC.UBER_BAGGAGE_HEADER_PREFIX="uberctx";var JAt=class{_jaegerTraceHeader;_jaegerBaggageHeaderPrefix;constructor(e){typeof e=="string"?(this._jaegerTraceHeader=e,this._jaegerBaggageHeaderPrefix=JC.UBER_BAGGAGE_HEADER_PREFIX):(this._jaegerTraceHeader=e?.customTraceHeader||JC.UBER_TRACE_ID_HEADER,this._jaegerBaggageHeaderPrefix=e?.customBaggageHeaderPrefix||JC.UBER_BAGGAGE_HEADER_PREFIX)}inject(e,r,n){let i=vF.trace.getSpanContext(e),o=vF.propagation.getBaggage(e);if(i&&(0,Gro.isTracingSuppressed)(e)===!1){let s=`0${(i.traceFlags||vF.TraceFlags.NONE).toString(16)}`;n.set(r,this._jaegerTraceHeader,`${i.traceId}:${i.spanId}:0:${s}`)}if(o)for(let[s,a]of o.getAllEntries())n.set(r,`${this._jaegerBaggageHeaderPrefix}-${s}`,encodeURIComponent(a.value))}extract(e,r,n){let i=n.get(r,this._jaegerTraceHeader),o=Array.isArray(i)?i[0]:i,s=n.keys(r).filter(u=>u.startsWith(`${this._jaegerBaggageHeaderPrefix}-`)).map(u=>{let d=n.get(r,u);return{key:u.substring(this._jaegerBaggageHeaderPrefix.length+1),value:Array.isArray(d)?d[0]:d}}),a=e;if(typeof o=="string"){let u=Vro(o);u&&(a=vF.trace.setSpanContext(a,u))}if(s.length===0)return a;let c=vF.propagation.getBaggage(e)??vF.propagation.createBaggage();for(let u of s)u.value!==void 0&&(c=c.setEntry(u.key,{value:decodeURIComponent(u.value)}));return a=vF.propagation.setBaggage(a,c),a}fields(){return[this._jaegerTraceHeader]}};JC.JaegerPropagator=JAt;var jro=/^[0-9a-f]{1,2}$/i;function Vro(t){let e=decodeURIComponent(t).split(":");if(e.length!==4)return null;let[r,n,,i]=e,o=r.padStart(32,"0"),s=n.padStart(16,"0"),a=jro.test(i)?parseInt(i,16)&1:1;return{traceId:o,spanId:s,isRemote:!0,traceFlags:a}}});var SIr=w(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0});sB.UBER_TRACE_ID_HEADER=sB.UBER_BAGGAGE_HEADER_PREFIX=sB.JaegerPropagator=void 0;var XAt=xIr();Object.defineProperty(sB,"JaegerPropagator",{enumerable:!0,get:function(){return XAt.JaegerPropagator}});Object.defineProperty(sB,"UBER_BAGGAGE_HEADER_PREFIX",{enumerable:!0,get:function(){return XAt.UBER_BAGGAGE_HEADER_PREFIX}});Object.defineProperty(sB,"UBER_TRACE_ID_HEADER",{enumerable:!0,get:function(){return XAt.UBER_TRACE_ID_HEADER}})});var DIr=w(Hv=>{"use strict";Object.defineProperty(Hv,"__esModule",{value:!0});Hv.getPropagatorFromEnv=Hv.getSpanProcessorsFromEnv=Hv.getOtlpProtocolFromEnv=Hv.filterBlanksAndNulls=Hv.getResourceDetectorsFromEnv=void 0;var aB=(Kt(),yt(ar)),cB=si(),wIr=nht(),$ro=tIr(),Wro=iIr(),zro=gIr(),Gfe=hY(),HIe=j9e(),ZAt=_Ir(),Yro=SIr(),Kro="env",Jro="host",Xro="os",Zro="process",eno="serviceinstance";function tno(){let t=new Map([[Kro,Gfe.envDetector],[Jro,Gfe.hostDetector],[Xro,Gfe.osDetector],[eno,Gfe.serviceInstanceIdDetector],[Zro,Gfe.processDetector]]),e=(0,cB.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")??["all"];return e.includes("all")?[...t.values()].flat():e.includes("none")?[]:e.flatMap(r=>{let n=t.get(r);return n||aB.diag.warn(`Invalid resource detector "${r}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`),n||[]})}Hv.getResourceDetectorsFromEnv=tno;function TIr(t){return t.map(e=>e.trim()).filter(e=>e!=="null"&&e!=="")}Hv.filterBlanksAndNulls=TIr;function IIr(){return(0,cB.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")??(0,cB.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL")??"http/protobuf"}Hv.getOtlpProtocolFromEnv=IIr;function rno(){let t=IIr();switch(t){case"grpc":return new Wro.OTLPTraceExporter;case"http/json":return new $ro.OTLPTraceExporter;case"http/protobuf":return new wIr.OTLPTraceExporter;default:return aB.diag.warn(`Unsupported OTLP traces protocol: ${t}. Using http/protobuf.`),new wIr.OTLPTraceExporter}}function nno(){try{let{JaegerExporter:t}=Ae("@opentelemetry/exporter-jaeger");return new t}catch(t){throw new Error(`Could not instantiate JaegerExporter. This could be due to the JaegerExporter's lack of support for bundling. If possible, use @opentelemetry/exporter-trace-otlp-proto instead. Original Error: ${t}`)}}function ino(){let t=new Map([["otlp",()=>rno()],["zipkin",()=>new zro.ZipkinExporter],["console",()=>new HIe.ConsoleSpanExporter],["jaeger",()=>nno()]]),e=[],r=[],n=TIr(Array.from(new Set((0,cB.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))));if(n[0]==="none")return aB.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.'),[];n.length===0?(aB.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter."),n=["otlp"]):n.length>1&&n.includes("none")&&(aB.diag.warn('OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.'),n=["otlp"]);for(let i of n){let o=t.get(i)?.();o?e.push(o):aB.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${i}.`)}for(let i of e)i instanceof HIe.ConsoleSpanExporter?r.push(new HIe.SimpleSpanProcessor(i)):r.push(new HIe.BatchSpanProcessor(i));return e.length===0&&aB.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values."),r}Hv.getSpanProcessorsFromEnv=ino;function ono(){let t=(0,cB.getStringListFromEnv)("OTEL_PROPAGATORS");if(t==null)return;let e=new Map([["tracecontext",()=>new cB.W3CTraceContextPropagator],["baggage",()=>new cB.W3CBaggagePropagator],["b3",()=>new ZAt.B3Propagator],["b3multi",()=>new ZAt.B3Propagator({injectEncoding:ZAt.B3InjectEncoding.MULTI_HEADER})],["jaeger",()=>new Yro.JaegerPropagator]]),r=Array.from(new Set(t)),i=r.map(o=>{let s=e.get(o)?.();if(!s){aB.diag.warn(`Propagator "${o}" requested through environment variable is unavailable.`);return}return s}).reduce((o,s)=>(s&&o.push(s),o),[]);return i.length===0?null:r.length===1?i[0]:new cB.CompositePropagator({propagators:i})}Hv.getPropagatorFromEnv=ono});var NIr=w(GIe=>{"use strict";Object.defineProperty(GIe,"__esModule",{value:!0});GIe.NodeSDK=void 0;var j1=(Kt(),yt(ar)),sno=uY(),ano=m8r(),CK=hY(),jfe=Hht(),cno=dht(),lno=M7r(),e3t=H7r(),uno=V7r(),RIr=lht(),dno=C8e(),fno=Y7r(),bF=Bx(),pno=j9e(),hno=E9e(),mno=(Nh(),yt(c2)),lB=si(),t3t=DIr();function BIr(t,e){return parseInt(process.env[t]||"")||e}function gno(){let t=[],e=(0,lB.getStringListFromEnv)("OTEL_METRICS_EXPORTER");return e?(e.length===0&&j1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter."),e.includes("none")?(j1.diag.info('OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.'),t):(e.forEach(r=>{if(r==="otlp"){let n=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),i=BIr("OTEL_METRIC_EXPORT_INTERVAL",6e4),o=BIr("OTEL_METRIC_EXPORT_TIMEOUT",3e4);switch(n){case"grpc":t.push(new bF.PeriodicExportingMetricReader({exporter:new uno.OTLPMetricExporter,exportIntervalMillis:i,exportTimeoutMillis:o}));break;case"http/json":t.push(new bF.PeriodicExportingMetricReader({exporter:new dno.OTLPMetricExporter,exportIntervalMillis:i,exportTimeoutMillis:o}));break;case"http/protobuf":t.push(new bF.PeriodicExportingMetricReader({exporter:new RIr.OTLPMetricExporter,exportIntervalMillis:i,exportTimeoutMillis:o}));break;default:j1.diag.warn(`Unsupported OTLP metrics protocol: "${n}". Using http/protobuf.`),t.push(new bF.PeriodicExportingMetricReader({exporter:new RIr.OTLPMetricExporter,exportIntervalMillis:i,exportTimeoutMillis:o}))}}else r==="console"?t.push(new bF.PeriodicExportingMetricReader({exporter:new bF.ConsoleMetricExporter})):r==="prometheus"?t.push(new fno.PrometheusExporter):j1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${r}". Supported values are: otlp, console, prometheus, none.`)}),t)):t}var r3t=class{_tracerProviderConfig;_loggerProviderConfig;_meterProviderConfig;_instrumentations;_resource;_resourceDetectors;_autoDetectResources;_tracerProvider;_loggerProvider;_meterProvider;_serviceName;_configuration;_disabled;constructor(e={}){(0,lB.getBooleanFromEnv)("OTEL_SDK_DISABLED")&&(this._disabled=!0);let r=(0,lB.getStringFromEnv)("OTEL_LOG_LEVEL");if(r!=null&&j1.diag.setLogger(new j1.DiagConsoleLogger,{logLevel:(0,lB.diagLogLevelFromString)(r)}),this._configuration=e,this._resource=e.resource??(0,CK.defaultResource)(),this._autoDetectResources=e.autoDetectResources??!0,this._autoDetectResources?e.resourceDetectors!=null?this._resourceDetectors=e.resourceDetectors:(0,lB.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")?this._resourceDetectors=(0,t3t.getResourceDetectorsFromEnv)():this._resourceDetectors=[CK.envDetector,CK.processDetector,CK.hostDetector]:this._resourceDetectors=[],this._serviceName=e.serviceName,e.traceExporter||e.spanProcessor||e.spanProcessors){let n={};e.sampler&&(n.sampler=e.sampler),e.spanLimits&&(n.spanLimits=e.spanLimits),e.idGenerator&&(n.idGenerator=e.idGenerator),e.spanProcessor&&j1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");let i=e.spanProcessor??new pno.BatchSpanProcessor(e.traceExporter),o=e.spanProcessors??[i];this._tracerProviderConfig={tracerConfig:n,spanProcessors:o,contextManager:e.contextManager,textMapPropagator:e.textMapPropagator}}if(e.logRecordProcessors?this._loggerProviderConfig={logRecordProcessors:e.logRecordProcessors}:e.logRecordProcessor?(this._loggerProviderConfig={logRecordProcessors:[e.logRecordProcessor]},j1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead.")):this.configureLoggerProviderFromEnv(),e.metricReaders||e.metricReader||e.views){let n={};e.metricReaders?n.readers=e.metricReaders:e.metricReader&&(n.readers=[e.metricReader],j1.diag.warn("The 'metricReader' option is deprecated. Please use 'metricReaders' instead.")),e.views&&(n.views=e.views),this._meterProviderConfig=n}this._instrumentations=e.instrumentations?.flat()??[]}start(){if(this._disabled)return;if((0,ano.registerInstrumentations)({instrumentations:this._instrumentations}),this._autoDetectResources){let n={detectors:this._resourceDetectors};this._resource=this._resource.merge((0,CK.detectResources)(n))}this._resource=this._serviceName===void 0?this._resource:this._resource.merge((0,CK.resourceFromAttributes)({[mno.ATTR_SERVICE_NAME]:this._serviceName}));let e=this._tracerProviderConfig?this._tracerProviderConfig.spanProcessors:(0,t3t.getSpanProcessorsFromEnv)();if(this._tracerProvider=new hno.NodeTracerProvider({...this._configuration,resource:this._resource,spanProcessors:e}),e.length>0&&this._tracerProvider.register({contextManager:this._tracerProviderConfig?.contextManager??this._configuration?.contextManager,propagator:this._tracerProviderConfig?.textMapPropagator??(0,t3t.getPropagatorFromEnv)()}),this._loggerProviderConfig){let n=new jfe.LoggerProvider({resource:this._resource,processors:this._loggerProviderConfig.logRecordProcessors});this._loggerProvider=n,sno.logs.setGlobalLoggerProvider(n)}let r=gno();if(this._meterProviderConfig||r.length>0){let n=[];this._meterProviderConfig?.readers&&n.push(...this._meterProviderConfig.readers),n.length===0&&r.forEach(o=>n.push(o));let i=new bF.MeterProvider({resource:this._resource,views:this._meterProviderConfig?.views??[],readers:n});this._meterProvider=i,j1.metrics.setGlobalMeterProvider(i);for(let o of this._instrumentations)o.setMeterProvider(j1.metrics.getMeterProvider())}}shutdown(){let e=[];return this._tracerProvider&&e.push(this._tracerProvider.shutdown()),this._loggerProvider&&e.push(this._loggerProvider.shutdown()),this._meterProvider&&e.push(this._meterProvider.shutdown()),Promise.all(e).then(()=>{})}configureLoggerProviderFromEnv(){let e=(0,lB.getStringListFromEnv)("OTEL_LOGS_EXPORTER")??[];if(e.length===0&&(j1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."),e.push("otlp")),e.includes("none")){j1.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.');return}let r=[];e.forEach(n=>{if(n==="otlp"){let i=((0,lB.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")??(0,lB.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();switch(i){case"grpc":r.push(new lno.OTLPLogExporter);break;case"http/json":r.push(new cno.OTLPLogExporter);break;case"http/protobuf":r.push(new e3t.OTLPLogExporter);break;case void 0:case"":r.push(new e3t.OTLPLogExporter);break;default:j1.diag.warn(`Unsupported OTLP logs protocol: "${i}". Using http/protobuf.`),r.push(new e3t.OTLPLogExporter)}}else n==="console"?r.push(new jfe.ConsoleLogRecordExporter):j1.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${n}". Supported values are: otlp, console, none.`)}),r.length>0&&(this._loggerProviderConfig={logRecordProcessors:r.map(n=>n instanceof jfe.ConsoleLogRecordExporter?new jfe.SimpleLogRecordProcessor(n):new jfe.BatchLogRecordProcessor(n))})}};GIe.NodeSDK=r3t});var OIr=w(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.NodeSDK=Kp.tracing=Kp.resources=Kp.node=Kp.metrics=Kp.logs=Kp.core=Kp.contextBase=Kp.api=void 0;Kp.api=(Kt(),yt(ar));Kp.contextBase=(Kt(),yt(ar));Kp.core=si();Kp.logs=Hht();Kp.metrics=Bx();Kp.node=E9e();Kp.resources=hY();Kp.tracing=j9e();var Ano=NIr();Object.defineProperty(Kp,"NodeSDK",{enumerable:!0,get:function(){return Ano.NodeSDK}})});function yno(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>{n(new Error(`Operation timed out after ${e} ms`))},e);t.then(r).catch(n).finally(()=>clearTimeout(i))})}var kIr,jIe,PIr=Z(()=>{"use strict";kIr=Te(Bx(),1);jIe=class extends kIr.PeriodicExportingMetricReader{_alignSeconds=[0,20,40];_intervalSeconds=20;constructor(e){if(super({...e,exportIntervalMillis:e.exportIntervalMillis??2e4}),(e.exportIntervalMillis??2e4)!==2e4)throw new Error("Aligned reader only supports 20-second intervals for 0/20/40 alignment")}onInitialized(){let e=new Date,r=e.getSeconds(),n=e.getMilliseconds(),i=this._alignSeconds.find(a=>a>=r),o;i!==void 0?o=(i-r)*1e3-n:(o=(60-r)*1e3-n,i=0),o=Math.max(0,o);let s=setTimeout(()=>{this._alignedExport(),this._interval=setInterval(()=>{this._alignedExport()},this._intervalSeconds*1e3);let a=this._interval;typeof a!="number"&&a?.unref&&a.unref()},o);typeof s!="number"&&s?.unref&&s.unref()}async _alignedExport(){let e=this._exportTimeout;try{await yno(this._doCollectAndExport(),e)}catch{}}async _doCollectAndExport(){let e=this._exportTimeout,{resourceMetrics:r,errors:n}=await this.collect({timeoutMillis:e});if(n.length>0,r.resource.asyncAttributesPending)try{await r.resource.waitForAsyncAttributes?.()}catch{}if(r.scopeMetrics.length===0)return;await this._exporter.export(r)}async onShutdown(){let e=this._interval;e&&clearInterval(e),await super.onShutdown()}}});var Vfe=w(uB=>{"use strict";Object.defineProperty(uB,"__esModule",{value:!0});uB.isTracingSuppressed=uB.unsuppressTracing=uB.suppressTracing=void 0;var Eno=(Kt(),yt(ar)),n3t=(0,Eno.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function vno(t){return t.setValue(n3t,!0)}uB.suppressTracing=vno;function bno(t){return t.deleteValue(n3t)}uB.unsuppressTracing=bno;function Cno(t){return t.getValue(n3t)===!0}uB.isTracingSuppressed=Cno});var i3t=w(p2=>{"use strict";Object.defineProperty(p2,"__esModule",{value:!0});p2.BAGGAGE_MAX_TOTAL_LENGTH=p2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=p2.BAGGAGE_MAX_NAME_VALUE_PAIRS=p2.BAGGAGE_HEADER=p2.BAGGAGE_ITEMS_SEPARATOR=p2.BAGGAGE_PROPERTIES_SEPARATOR=p2.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;p2.BAGGAGE_KEY_PAIR_SEPARATOR="=";p2.BAGGAGE_PROPERTIES_SEPARATOR=";";p2.BAGGAGE_ITEMS_SEPARATOR=",";p2.BAGGAGE_HEADER="baggage";p2.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;p2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;p2.BAGGAGE_MAX_TOTAL_LENGTH=8192});var o3t=w(lS=>{"use strict";Object.defineProperty(lS,"__esModule",{value:!0});lS.parseKeyPairsIntoRecord=lS.parsePairKeyValue=lS.getKeyPairs=lS.serializeKeyPairs=void 0;var _no=(Kt(),yt(ar)),CF=i3t();function xno(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?CF.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>CF.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}lS.serializeKeyPairs=xno;function Sno(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=CF.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}lS.getKeyPairs=Sno;function MIr(t){let e=t.split(CF.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(CF.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim()),s;return e.length>0&&(s=(0,_no.baggageEntryMetadataFromString)(e.join(CF.BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}lS.parsePairKeyValue=MIr;function wno(t){let e={};return typeof t=="string"&&t.length>0&&t.split(CF.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=MIr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}lS.parseKeyPairsIntoRecord=wno});var LIr=w(VIe=>{"use strict";Object.defineProperty(VIe,"__esModule",{value:!0});VIe.W3CBaggagePropagator=void 0;var s3t=(Kt(),yt(ar)),Tno=Vfe(),_F=i3t(),a3t=o3t(),c3t=class{inject(e,r,n){let i=s3t.propagation.getBaggage(e);if(!i||(0,Tno.isTracingSuppressed)(e))return;let o=(0,a3t.getKeyPairs)(i).filter(a=>a.length<=_F.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,_F.BAGGAGE_MAX_NAME_VALUE_PAIRS),s=(0,a3t.serializeKeyPairs)(o);s.length>0&&n.set(r,_F.BAGGAGE_HEADER,s)}extract(e,r,n){let i=n.get(r,_F.BAGGAGE_HEADER),o=Array.isArray(i)?i.join(_F.BAGGAGE_ITEMS_SEPARATOR):i;if(!o)return e;let s={};return o.length===0||(o.split(_F.BAGGAGE_ITEMS_SEPARATOR).forEach(c=>{let u=(0,a3t.parsePairKeyValue)(c);if(u){let d={value:u.value};u.metadata&&(d.metadata=u.metadata),s[u.key]=d}}),Object.entries(s).length===0)?e:s3t.propagation.setBaggage(e,s3t.propagation.createBaggage(s))}fields(){return[_F.BAGGAGE_HEADER]}};VIe.W3CBaggagePropagator=c3t});var FIr=w($Ie=>{"use strict";Object.defineProperty($Ie,"__esModule",{value:!0});$Ie.AnchoredClock=void 0;var l3t=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};$Ie.AnchoredClock=l3t});var GIr=w(dB=>{"use strict";Object.defineProperty(dB,"__esModule",{value:!0});dB.isAttributeValue=dB.isAttributeKey=dB.sanitizeAttributes=void 0;var UIr=(Kt(),yt(ar));function Ino(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!QIr(r)){UIr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!qIr(n)){UIr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}dB.sanitizeAttributes=Ino;function QIr(t){return typeof t=="string"&&t!==""}dB.isAttributeKey=QIr;function qIr(t){return t==null?!0:Array.isArray(t)?Dno(t):HIr(typeof t)}dB.isAttributeValue=qIr;function Dno(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(HIr(n)){e=n;continue}return!1}return!1}}return!0}function HIr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var u3t=w(WIe=>{"use strict";Object.defineProperty(WIe,"__esModule",{value:!0});WIe.loggingErrorHandler=void 0;var Rno=(Kt(),yt(ar));function Bno(){return t=>{Rno.diag.error(Nno(t))}}WIe.loggingErrorHandler=Bno;function Nno(t){return typeof t=="string"?t:JSON.stringify(Ono(t))}function Ono(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let i=r[n];i&&(e[n]=String(i))}),r=Object.getPrototypeOf(r);return e}});var VIr=w(_K=>{"use strict";Object.defineProperty(_K,"__esModule",{value:!0});_K.globalErrorHandler=_K.setGlobalErrorHandler=void 0;var kno=u3t(),jIr=(0,kno.loggingErrorHandler)();function Pno(t){jIr=t}_K.setGlobalErrorHandler=Pno;function Mno(t){try{jIr(t)}catch{}}_K.globalErrorHandler=Mno});var YIr=w(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});uS.getStringListFromEnv=uS.getBooleanFromEnv=uS.getStringFromEnv=uS.getNumberFromEnv=void 0;var $Ir=(Kt(),yt(ar)),WIr=Ae("util");function Lno(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){$Ir.diag.warn(`Unknown value ${(0,WIr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}uS.getNumberFromEnv=Lno;function zIr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}uS.getStringFromEnv=zIr;function Fno(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||$Ir.diag.warn(`Unknown value ${(0,WIr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}uS.getBooleanFromEnv=Fno;function Uno(t){return zIr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}uS.getStringListFromEnv=Uno});var KIr=w(zIe=>{"use strict";Object.defineProperty(zIe,"__esModule",{value:!0});zIe._globalThis=void 0;zIe._globalThis=typeof globalThis=="object"?globalThis:global});var JIr=w(YIe=>{"use strict";Object.defineProperty(YIe,"__esModule",{value:!0});YIe.otperformance=void 0;var Qno=Ae("perf_hooks");YIe.otperformance=Qno.performance});var XIr=w(KIe=>{"use strict";Object.defineProperty(KIe,"__esModule",{value:!0});KIe.VERSION=void 0;KIe.VERSION="2.2.0"});var ZIr=w(JIe=>{"use strict";Object.defineProperty(JIe,"__esModule",{value:!0});JIe.ATTR_PROCESS_RUNTIME_NAME=void 0;JIe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var eDr=w(ZIe=>{"use strict";Object.defineProperty(ZIe,"__esModule",{value:!0});ZIe.SDK_INFO=void 0;var qno=XIr(),XIe=(Nh(),yt(c2)),Hno=ZIr();ZIe.SDK_INFO={[XIe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[Hno.ATTR_PROCESS_RUNTIME_NAME]:"node",[XIe.ATTR_TELEMETRY_SDK_LANGUAGE]:XIe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[XIe.ATTR_TELEMETRY_SDK_VERSION]:qno.VERSION}});var tDr=w(h2=>{"use strict";Object.defineProperty(h2,"__esModule",{value:!0});h2.SDK_INFO=h2.otperformance=h2._globalThis=h2.getStringListFromEnv=h2.getNumberFromEnv=h2.getBooleanFromEnv=h2.getStringFromEnv=void 0;var eDe=YIr();Object.defineProperty(h2,"getStringFromEnv",{enumerable:!0,get:function(){return eDe.getStringFromEnv}});Object.defineProperty(h2,"getBooleanFromEnv",{enumerable:!0,get:function(){return eDe.getBooleanFromEnv}});Object.defineProperty(h2,"getNumberFromEnv",{enumerable:!0,get:function(){return eDe.getNumberFromEnv}});Object.defineProperty(h2,"getStringListFromEnv",{enumerable:!0,get:function(){return eDe.getStringListFromEnv}});var Gno=KIr();Object.defineProperty(h2,"_globalThis",{enumerable:!0,get:function(){return Gno._globalThis}});var jno=JIr();Object.defineProperty(h2,"otperformance",{enumerable:!0,get:function(){return jno.otperformance}});var Vno=eDr();Object.defineProperty(h2,"SDK_INFO",{enumerable:!0,get:function(){return Vno.SDK_INFO}})});var d3t=w(m2=>{"use strict";Object.defineProperty(m2,"__esModule",{value:!0});m2.getStringListFromEnv=m2.getNumberFromEnv=m2.getStringFromEnv=m2.getBooleanFromEnv=m2.otperformance=m2._globalThis=m2.SDK_INFO=void 0;var xF=tDr();Object.defineProperty(m2,"SDK_INFO",{enumerable:!0,get:function(){return xF.SDK_INFO}});Object.defineProperty(m2,"_globalThis",{enumerable:!0,get:function(){return xF._globalThis}});Object.defineProperty(m2,"otperformance",{enumerable:!0,get:function(){return xF.otperformance}});Object.defineProperty(m2,"getBooleanFromEnv",{enumerable:!0,get:function(){return xF.getBooleanFromEnv}});Object.defineProperty(m2,"getStringFromEnv",{enumerable:!0,get:function(){return xF.getStringFromEnv}});Object.defineProperty(m2,"getNumberFromEnv",{enumerable:!0,get:function(){return xF.getNumberFromEnv}});Object.defineProperty(m2,"getStringListFromEnv",{enumerable:!0,get:function(){return xF.getStringListFromEnv}})});var oDr=w(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.addHrTimes=pu.isTimeInput=pu.isTimeInputHrTime=pu.hrTimeToMicroseconds=pu.hrTimeToMilliseconds=pu.hrTimeToNanoseconds=pu.hrTimeToTimeStamp=pu.hrTimeDuration=pu.timeInputToHrTime=pu.hrTime=pu.getTimeOrigin=pu.millisToHrTime=void 0;var f3t=d3t(),rDr=9,$no=6,Wno=Math.pow(10,$no),tDe=Math.pow(10,rDr);function $fe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Wno);return[r,n]}pu.millisToHrTime=$fe;function p3t(){let t=f3t.otperformance.timeOrigin;if(typeof t!="number"){let e=f3t.otperformance;t=e.timing&&e.timing.fetchStart}return t}pu.getTimeOrigin=p3t;function nDr(t){let e=$fe(p3t()),r=$fe(typeof t=="number"?t:f3t.otperformance.now());return iDr(e,r)}pu.hrTime=nDr;function zno(t){if(h3t(t))return t;if(typeof t=="number")return t<p3t()?nDr(t):$fe(t);if(t instanceof Date)return $fe(t.getTime());throw TypeError("Invalid input type")}pu.timeInputToHrTime=zno;function Yno(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=tDe),[r,n]}pu.hrTimeDuration=Yno;function Kno(t){let e=rDr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}pu.hrTimeToTimeStamp=Kno;function Jno(t){return t[0]*tDe+t[1]}pu.hrTimeToNanoseconds=Jno;function Xno(t){return t[0]*1e3+t[1]/1e6}pu.hrTimeToMilliseconds=Xno;function Zno(t){return t[0]*1e6+t[1]/1e3}pu.hrTimeToMicroseconds=Zno;function h3t(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}pu.isTimeInputHrTime=h3t;function eio(t){return h3t(t)||typeof t=="number"||t instanceof Date}pu.isTimeInput=eio;function iDr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=tDe&&(r[1]-=tDe,r[0]+=1),r}pu.addHrTimes=iDr});var sDr=w(rDe=>{"use strict";Object.defineProperty(rDe,"__esModule",{value:!0});rDe.unrefTimer=void 0;function tio(t){typeof t!="number"&&t.unref()}rDe.unrefTimer=tio});var aDr=w(Wfe=>{"use strict";Object.defineProperty(Wfe,"__esModule",{value:!0});Wfe.ExportResultCode=void 0;var rio;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(rio=Wfe.ExportResultCode||(Wfe.ExportResultCode={}))});var lDr=w(nDe=>{"use strict";Object.defineProperty(nDe,"__esModule",{value:!0});nDe.CompositePropagator=void 0;var cDr=(Kt(),yt(ar)),m3t=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let i of this._propagators)try{i.inject(e,r,n)}catch(o){cDr.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${o.message}`)}}extract(e,r,n){return this._propagators.reduce((i,o)=>{try{return o.extract(i,r,n)}catch(s){cDr.diag.warn(`Failed to extract with ${o.constructor.name}. Err: ${s.message}`)}return i},e)}fields(){return this._fields.slice()}};nDe.CompositePropagator=m3t});var uDr=w(xK=>{"use strict";Object.defineProperty(xK,"__esModule",{value:!0});xK.validateValue=xK.validateKey=void 0;var g3t="[_0-9a-z-*/]",nio=`[a-z]${g3t}{0,255}`,iio=`[a-z0-9]${g3t}{0,240}@[a-z]${g3t}{0,13}`,oio=new RegExp(`^(?:${nio}|${iio})$`),sio=/^[ -~]{0,255}[!-~]$/,aio=/,|=/;function cio(t){return oio.test(t)}xK.validateKey=cio;function lio(t){return sio.test(t)&&!aio.test(t)}xK.validateValue=lio});var y3t=w(iDe=>{"use strict";Object.defineProperty(iDe,"__esModule",{value:!0});iDe.TraceState=void 0;var dDr=uDr(),fDr=32,uio=512,pDr=",",hDr="=",A3t=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+hDr+this.get(r)),e),[]).join(pDr)}_parse(e){e.length>uio||(this._internalState=e.split(pDr).reverse().reduce((r,n)=>{let i=n.trim(),o=i.indexOf(hDr);if(o!==-1){let s=i.slice(0,o),a=i.slice(o+1,n.length);(0,dDr.validateKey)(s)&&(0,dDr.validateValue)(a)&&r.set(s,a)}return r},new Map),this._internalState.size>fDr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,fDr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};iDe.TraceState=A3t});var gDr=w(g2=>{"use strict";Object.defineProperty(g2,"__esModule",{value:!0});g2.W3CTraceContextPropagator=g2.parseTraceParent=g2.TRACE_STATE_HEADER=g2.TRACE_PARENT_HEADER=void 0;var oDe=(Kt(),yt(ar)),dio=Vfe(),fio=y3t();g2.TRACE_PARENT_HEADER="traceparent";g2.TRACE_STATE_HEADER="tracestate";var pio="00",hio="(?!ff)[\\da-f]{2}",mio="(?![0]{32})[\\da-f]{32}",gio="(?![0]{16})[\\da-f]{16}",Aio="[\\da-f]{2}",yio=new RegExp(`^\\s?(${hio})-(${mio})-(${gio})-(${Aio})(-.*)?\\s?$`);function mDr(t){let e=yio.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}g2.parseTraceParent=mDr;var E3t=class{inject(e,r,n){let i=oDe.trace.getSpanContext(e);if(!i||(0,dio.isTracingSuppressed)(e)||!(0,oDe.isSpanContextValid)(i))return;let o=`${pio}-${i.traceId}-${i.spanId}-0${Number(i.traceFlags||oDe.TraceFlags.NONE).toString(16)}`;n.set(r,g2.TRACE_PARENT_HEADER,o),i.traceState&&n.set(r,g2.TRACE_STATE_HEADER,i.traceState.serialize())}extract(e,r,n){let i=n.get(r,g2.TRACE_PARENT_HEADER);if(!i)return e;let o=Array.isArray(i)?i[0]:i;if(typeof o!="string")return e;let s=mDr(o);if(!s)return e;s.isRemote=!0;let a=n.get(r,g2.TRACE_STATE_HEADER);if(a){let c=Array.isArray(a)?a.join(","):a;s.traceState=new fio.TraceState(typeof c=="string"?c:void 0)}return oDe.trace.setSpanContext(e,s)}fields(){return[g2.TRACE_PARENT_HEADER,g2.TRACE_STATE_HEADER]}};g2.W3CTraceContextPropagator=E3t});var ADr=w(XC=>{"use strict";Object.defineProperty(XC,"__esModule",{value:!0});XC.getRPCMetadata=XC.deleteRPCMetadata=XC.setRPCMetadata=XC.RPCType=void 0;var Eio=(Kt(),yt(ar)),v3t=(0,Eio.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),vio;(function(t){t.HTTP="http"})(vio=XC.RPCType||(XC.RPCType={}));function bio(t,e){return t.setValue(v3t,e)}XC.setRPCMetadata=bio;function Cio(t){return t.deleteValue(v3t)}XC.deleteRPCMetadata=Cio;function _io(t){return t.getValue(v3t)}XC.getRPCMetadata=_io});var CDr=w(sDe=>{"use strict";Object.defineProperty(sDe,"__esModule",{value:!0});sDe.isPlainObject=void 0;var xio="[object Object]",Sio="[object Null]",wio="[object Undefined]",Tio=Function.prototype,yDr=Tio.toString,Iio=yDr.call(Object),Dio=Object.getPrototypeOf,EDr=Object.prototype,vDr=EDr.hasOwnProperty,SF=Symbol?Symbol.toStringTag:void 0,bDr=EDr.toString;function Rio(t){if(!Bio(t)||Nio(t)!==xio)return!1;let e=Dio(t);if(e===null)return!0;let r=vDr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&yDr.call(r)===Iio}sDe.isPlainObject=Rio;function Bio(t){return t!=null&&typeof t=="object"}function Nio(t){return t==null?t===void 0?wio:Sio:SF&&SF in Object(t)?Oio(t):kio(t)}function Oio(t){let e=vDr.call(t,SF),r=t[SF],n=!1;try{t[SF]=void 0,n=!0}catch{}let i=bDr.call(t);return n&&(e?t[SF]=r:delete t[SF]),i}function kio(t){return bDr.call(t)}});var TDr=w(lDe=>{"use strict";Object.defineProperty(lDe,"__esModule",{value:!0});lDe.merge=void 0;var _Dr=CDr(),Pio=20;function Mio(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=SDr(e,t.shift(),0,r);return e}lDe.merge=Mio;function b3t(t){return cDe(t)?t.slice():t}function SDr(t,e,r=0,n){let i;if(!(r>Pio)){if(r++,aDe(t)||aDe(e)||wDr(e))i=b3t(e);else if(cDe(t)){if(i=t.slice(),cDe(e))for(let o=0,s=e.length;o<s;o++)i.push(b3t(e[o]));else if(zfe(e)){let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s];i[c]=b3t(e[c])}}}else if(zfe(t))if(zfe(e)){if(!Lio(t,e))return e;i=Object.assign({},t);let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s],u=e[c];if(aDe(u))typeof u>"u"?delete i[c]:i[c]=u;else{let d=i[c],f=u;if(xDr(t,c,n)||xDr(e,c,n))delete i[c];else{if(zfe(d)&&zfe(f)){let p=n.get(d)||[],h=n.get(f)||[];p.push({obj:t,key:c}),h.push({obj:e,key:c}),n.set(d,p),n.set(f,h)}i[c]=SDr(i[c],u,r,n)}}}}else i=e;return i}}function xDr(t,e,r){let n=r.get(t[e])||[];for(let i=0,o=n.length;i<o;i++){let s=n[i];if(s.key===e&&s.obj===t)return!0}return!1}function cDe(t){return Array.isArray(t)}function wDr(t){return typeof t=="function"}function zfe(t){return!aDe(t)&&!cDe(t)&&!wDr(t)&&typeof t=="object"}function aDe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Lio(t,e){return!(!(0,_Dr.isPlainObject)(t)||!(0,_Dr.isPlainObject)(e))}});var IDr=w(SK=>{"use strict";Object.defineProperty(SK,"__esModule",{value:!0});SK.callWithTimeout=SK.TimeoutError=void 0;var uDe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};SK.TimeoutError=uDe;function Fio(t,e){let r,n=new Promise(function(o,s){r=setTimeout(function(){s(new uDe("Operation timed out."))},e)});return Promise.race([t,n]).then(i=>(clearTimeout(r),i),i=>{throw clearTimeout(r),i})}SK.callWithTimeout=Fio});var RDr=w(wK=>{"use strict";Object.defineProperty(wK,"__esModule",{value:!0});wK.isUrlIgnored=wK.urlMatches=void 0;function DDr(t,e){return typeof e=="string"?t===e:!!t.match(e)}wK.urlMatches=DDr;function Uio(t,e){if(!e)return!1;for(let r of e)if(DDr(t,r))return!0;return!1}wK.isUrlIgnored=Uio});var BDr=w(dDe=>{"use strict";Object.defineProperty(dDe,"__esModule",{value:!0});dDe.Deferred=void 0;var C3t=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};dDe.Deferred=C3t});var NDr=w(fDe=>{"use strict";Object.defineProperty(fDe,"__esModule",{value:!0});fDe.BindOnceFuture=void 0;var Qio=BDr(),_3t=class{_callback;_that;_isCalled=!1;_deferred=new Qio.Deferred;constructor(e,r){this._callback=e,this._that=r}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(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};fDe.BindOnceFuture=_3t});var kDr=w(pDe=>{"use strict";Object.defineProperty(pDe,"__esModule",{value:!0});pDe.diagLogLevelFromString=void 0;var dT=(Kt(),yt(ar)),ODr={ALL:dT.DiagLogLevel.ALL,VERBOSE:dT.DiagLogLevel.VERBOSE,DEBUG:dT.DiagLogLevel.DEBUG,INFO:dT.DiagLogLevel.INFO,WARN:dT.DiagLogLevel.WARN,ERROR:dT.DiagLogLevel.ERROR,NONE:dT.DiagLogLevel.NONE};function qio(t){if(t==null)return;let e=ODr[t.toUpperCase()];return e??(dT.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(ODr)}, using default`),dT.DiagLogLevel.INFO)}pDe.diagLogLevelFromString=qio});var MDr=w(hDe=>{"use strict";Object.defineProperty(hDe,"__esModule",{value:!0});hDe._export=void 0;var PDr=(Kt(),yt(ar)),Hio=Vfe();function Gio(t,e){return new Promise(r=>{PDr.context.with((0,Hio.suppressTracing)(PDr.context.active()),()=>{t.export(e,n=>{r(n)})})})}hDe._export=Gio});var S3t=w(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.internal=Mr.diagLogLevelFromString=Mr.BindOnceFuture=Mr.urlMatches=Mr.isUrlIgnored=Mr.callWithTimeout=Mr.TimeoutError=Mr.merge=Mr.TraceState=Mr.unsuppressTracing=Mr.suppressTracing=Mr.isTracingSuppressed=Mr.setRPCMetadata=Mr.getRPCMetadata=Mr.deleteRPCMetadata=Mr.RPCType=Mr.parseTraceParent=Mr.W3CTraceContextPropagator=Mr.TRACE_STATE_HEADER=Mr.TRACE_PARENT_HEADER=Mr.CompositePropagator=Mr.otperformance=Mr.getStringListFromEnv=Mr.getNumberFromEnv=Mr.getBooleanFromEnv=Mr.getStringFromEnv=Mr._globalThis=Mr.SDK_INFO=Mr.parseKeyPairsIntoRecord=Mr.ExportResultCode=Mr.unrefTimer=Mr.timeInputToHrTime=Mr.millisToHrTime=Mr.isTimeInputHrTime=Mr.isTimeInput=Mr.hrTimeToTimeStamp=Mr.hrTimeToNanoseconds=Mr.hrTimeToMilliseconds=Mr.hrTimeToMicroseconds=Mr.hrTimeDuration=Mr.hrTime=Mr.getTimeOrigin=Mr.addHrTimes=Mr.loggingErrorHandler=Mr.setGlobalErrorHandler=Mr.globalErrorHandler=Mr.sanitizeAttributes=Mr.isAttributeValue=Mr.AnchoredClock=Mr.W3CBaggagePropagator=void 0;var jio=LIr();Object.defineProperty(Mr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return jio.W3CBaggagePropagator}});var Vio=FIr();Object.defineProperty(Mr,"AnchoredClock",{enumerable:!0,get:function(){return Vio.AnchoredClock}});var LDr=GIr();Object.defineProperty(Mr,"isAttributeValue",{enumerable:!0,get:function(){return LDr.isAttributeValue}});Object.defineProperty(Mr,"sanitizeAttributes",{enumerable:!0,get:function(){return LDr.sanitizeAttributes}});var FDr=VIr();Object.defineProperty(Mr,"globalErrorHandler",{enumerable:!0,get:function(){return FDr.globalErrorHandler}});Object.defineProperty(Mr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return FDr.setGlobalErrorHandler}});var $io=u3t();Object.defineProperty(Mr,"loggingErrorHandler",{enumerable:!0,get:function(){return $io.loggingErrorHandler}});var Gv=oDr();Object.defineProperty(Mr,"addHrTimes",{enumerable:!0,get:function(){return Gv.addHrTimes}});Object.defineProperty(Mr,"getTimeOrigin",{enumerable:!0,get:function(){return Gv.getTimeOrigin}});Object.defineProperty(Mr,"hrTime",{enumerable:!0,get:function(){return Gv.hrTime}});Object.defineProperty(Mr,"hrTimeDuration",{enumerable:!0,get:function(){return Gv.hrTimeDuration}});Object.defineProperty(Mr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return Gv.hrTimeToMicroseconds}});Object.defineProperty(Mr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return Gv.hrTimeToMilliseconds}});Object.defineProperty(Mr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return Gv.hrTimeToNanoseconds}});Object.defineProperty(Mr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return Gv.hrTimeToTimeStamp}});Object.defineProperty(Mr,"isTimeInput",{enumerable:!0,get:function(){return Gv.isTimeInput}});Object.defineProperty(Mr,"isTimeInputHrTime",{enumerable:!0,get:function(){return Gv.isTimeInputHrTime}});Object.defineProperty(Mr,"millisToHrTime",{enumerable:!0,get:function(){return Gv.millisToHrTime}});Object.defineProperty(Mr,"timeInputToHrTime",{enumerable:!0,get:function(){return Gv.timeInputToHrTime}});var Wio=sDr();Object.defineProperty(Mr,"unrefTimer",{enumerable:!0,get:function(){return Wio.unrefTimer}});var zio=aDr();Object.defineProperty(Mr,"ExportResultCode",{enumerable:!0,get:function(){return zio.ExportResultCode}});var Yio=o3t();Object.defineProperty(Mr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Yio.parseKeyPairsIntoRecord}});var wF=d3t();Object.defineProperty(Mr,"SDK_INFO",{enumerable:!0,get:function(){return wF.SDK_INFO}});Object.defineProperty(Mr,"_globalThis",{enumerable:!0,get:function(){return wF._globalThis}});Object.defineProperty(Mr,"getStringFromEnv",{enumerable:!0,get:function(){return wF.getStringFromEnv}});Object.defineProperty(Mr,"getBooleanFromEnv",{enumerable:!0,get:function(){return wF.getBooleanFromEnv}});Object.defineProperty(Mr,"getNumberFromEnv",{enumerable:!0,get:function(){return wF.getNumberFromEnv}});Object.defineProperty(Mr,"getStringListFromEnv",{enumerable:!0,get:function(){return wF.getStringListFromEnv}});Object.defineProperty(Mr,"otperformance",{enumerable:!0,get:function(){return wF.otperformance}});var Kio=lDr();Object.defineProperty(Mr,"CompositePropagator",{enumerable:!0,get:function(){return Kio.CompositePropagator}});var mDe=gDr();Object.defineProperty(Mr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return mDe.TRACE_PARENT_HEADER}});Object.defineProperty(Mr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return mDe.TRACE_STATE_HEADER}});Object.defineProperty(Mr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return mDe.W3CTraceContextPropagator}});Object.defineProperty(Mr,"parseTraceParent",{enumerable:!0,get:function(){return mDe.parseTraceParent}});var gDe=ADr();Object.defineProperty(Mr,"RPCType",{enumerable:!0,get:function(){return gDe.RPCType}});Object.defineProperty(Mr,"deleteRPCMetadata",{enumerable:!0,get:function(){return gDe.deleteRPCMetadata}});Object.defineProperty(Mr,"getRPCMetadata",{enumerable:!0,get:function(){return gDe.getRPCMetadata}});Object.defineProperty(Mr,"setRPCMetadata",{enumerable:!0,get:function(){return gDe.setRPCMetadata}});var x3t=Vfe();Object.defineProperty(Mr,"isTracingSuppressed",{enumerable:!0,get:function(){return x3t.isTracingSuppressed}});Object.defineProperty(Mr,"suppressTracing",{enumerable:!0,get:function(){return x3t.suppressTracing}});Object.defineProperty(Mr,"unsuppressTracing",{enumerable:!0,get:function(){return x3t.unsuppressTracing}});var Jio=y3t();Object.defineProperty(Mr,"TraceState",{enumerable:!0,get:function(){return Jio.TraceState}});var Xio=TDr();Object.defineProperty(Mr,"merge",{enumerable:!0,get:function(){return Xio.merge}});var UDr=IDr();Object.defineProperty(Mr,"TimeoutError",{enumerable:!0,get:function(){return UDr.TimeoutError}});Object.defineProperty(Mr,"callWithTimeout",{enumerable:!0,get:function(){return UDr.callWithTimeout}});var QDr=RDr();Object.defineProperty(Mr,"isUrlIgnored",{enumerable:!0,get:function(){return QDr.isUrlIgnored}});Object.defineProperty(Mr,"urlMatches",{enumerable:!0,get:function(){return QDr.urlMatches}});var Zio=NDr();Object.defineProperty(Mr,"BindOnceFuture",{enumerable:!0,get:function(){return Zio.BindOnceFuture}});var eoo=kDr();Object.defineProperty(Mr,"diagLogLevelFromString",{enumerable:!0,get:function(){return eoo.diagLogLevelFromString}});var too=MDr();Mr.internal={_export:too._export}});var qDr=w(ADe=>{"use strict";Object.defineProperty(ADe,"__esModule",{value:!0});ADe.defaultServiceName=void 0;function roo(){return`unknown_service:${process.argv0}`}ADe.defaultServiceName=roo});var HDr=w(yDe=>{"use strict";Object.defineProperty(yDe,"__esModule",{value:!0});yDe.defaultServiceName=void 0;var noo=qDr();Object.defineProperty(yDe,"defaultServiceName",{enumerable:!0,get:function(){return noo.defaultServiceName}})});var w3t=w(EDe=>{"use strict";Object.defineProperty(EDe,"__esModule",{value:!0});EDe.defaultServiceName=void 0;var ioo=HDr();Object.defineProperty(EDe,"defaultServiceName",{enumerable:!0,get:function(){return ioo.defaultServiceName}})});var GDr=w(TK=>{"use strict";Object.defineProperty(TK,"__esModule",{value:!0});TK.identity=TK.isPromiseLike=void 0;var ooo=t=>t!==null&&typeof t=="object"&&typeof t.then=="function";TK.isPromiseLike=ooo;function soo(t){return t}TK.identity=soo});var D3t=w(dS=>{"use strict";Object.defineProperty(dS,"__esModule",{value:!0});dS.defaultResource=dS.emptyResource=dS.resourceFromDetectedResource=dS.resourceFromAttributes=void 0;var Kfe=(Kt(),yt(ar)),T3t=S3t(),TF=(Nh(),yt(c2)),aoo=w3t(),Yfe=GDr(),vDe=class t{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,r){let n=new t({},r);return n._rawAttributes=jDr(e),n._asyncAttributesPending=e.filter(([i,o])=>(0,Yfe.isPromiseLike)(o)).length>0,n}constructor(e,r){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([i,o])=>((0,Yfe.isPromiseLike)(o)&&(this._asyncAttributesPending=!0),[i,o])),this._rawAttributes=jDr(this._rawAttributes),this._schemaUrl=doo(r?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[r,n]=this._rawAttributes[e];this._rawAttributes[e]=[r,(0,Yfe.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&Kfe.diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[r,n]of this._rawAttributes){if((0,Yfe.isPromiseLike)(n)){Kfe.diag.debug(`Unsettled resource attribute ${r} skipped`);continue}n!=null&&(e[r]??=n)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(e){if(e==null)return this;let r=foo(this,e),n=r?{schemaUrl:r}:void 0;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],n)}};function I3t(t,e){return vDe.FromAttributeList(Object.entries(t),e)}dS.resourceFromAttributes=I3t;function coo(t,e){return new vDe(t,e)}dS.resourceFromDetectedResource=coo;function loo(){return I3t({})}dS.emptyResource=loo;function uoo(){return I3t({[TF.ATTR_SERVICE_NAME]:(0,aoo.defaultServiceName)(),[TF.ATTR_TELEMETRY_SDK_LANGUAGE]:T3t.SDK_INFO[TF.ATTR_TELEMETRY_SDK_LANGUAGE],[TF.ATTR_TELEMETRY_SDK_NAME]:T3t.SDK_INFO[TF.ATTR_TELEMETRY_SDK_NAME],[TF.ATTR_TELEMETRY_SDK_VERSION]:T3t.SDK_INFO[TF.ATTR_TELEMETRY_SDK_VERSION]})}dS.defaultResource=uoo;function jDr(t){return t.map(([e,r])=>(0,Yfe.isPromiseLike)(r)?[e,r.catch(n=>{Kfe.diag.debug("promise rejection for resource attribute: %s - %s",e,n)})]:[e,r])}function doo(t){if(typeof t=="string"||t===void 0)return t;Kfe.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t)}function foo(t,e){let r=t?.schemaUrl,n=e?.schemaUrl,i=r===void 0||r==="",o=n===void 0||n==="";if(i)return n;if(o||r===n)return r;Kfe.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}});var $Dr=w(bDe=>{"use strict";Object.defineProperty(bDe,"__esModule",{value:!0});bDe.detectResources=void 0;var VDr=(Kt(),yt(ar)),R3t=D3t(),poo=(t={})=>(t.detectors||[]).map(r=>{try{let n=(0,R3t.resourceFromDetectedResource)(r.detect(t));return VDr.diag.debug(`${r.constructor.name} found resource.`,n),n}catch(n){return VDr.diag.debug(`${r.constructor.name} failed: ${n.message}`),(0,R3t.emptyResource)()}}).reduce((r,n)=>r.merge(n),(0,R3t.emptyResource)());bDe.detectResources=poo});var zDr=w(CDe=>{"use strict";Object.defineProperty(CDe,"__esModule",{value:!0});CDe.envDetector=void 0;var hoo=(Kt(),yt(ar)),moo=(Nh(),yt(c2)),WDr=S3t(),B3t=class{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){let r={},n=(0,WDr.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"),i=(0,WDr.getStringFromEnv)("OTEL_SERVICE_NAME");if(n)try{let o=this._parseResourceAttributes(n);Object.assign(r,o)}catch(o){hoo.diag.debug(`EnvDetector failed: ${o.message}`)}return i&&(r[moo.ATTR_SERVICE_NAME]=i),{attributes:r}}_parseResourceAttributes(e){if(!e)return{};let r={},n=e.split(this._COMMA_SEPARATOR,-1);for(let i of n){let o=i.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(o.length!==2)continue;let[s,a]=o;if(s=s.trim(),a=a.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(s))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(a))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);r[s]=decodeURIComponent(a)}return r}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<33||n===44||n===59||n===92||n>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}};CDe.envDetector=new B3t});var Jfe=w(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.ATTR_WEBENGINE_VERSION=Bn.ATTR_WEBENGINE_NAME=Bn.ATTR_WEBENGINE_DESCRIPTION=Bn.ATTR_SERVICE_NAMESPACE=Bn.ATTR_SERVICE_INSTANCE_ID=Bn.ATTR_PROCESS_RUNTIME_VERSION=Bn.ATTR_PROCESS_RUNTIME_NAME=Bn.ATTR_PROCESS_RUNTIME_DESCRIPTION=Bn.ATTR_PROCESS_PID=Bn.ATTR_PROCESS_OWNER=Bn.ATTR_PROCESS_EXECUTABLE_PATH=Bn.ATTR_PROCESS_EXECUTABLE_NAME=Bn.ATTR_PROCESS_COMMAND_ARGS=Bn.ATTR_PROCESS_COMMAND=Bn.ATTR_OS_VERSION=Bn.ATTR_OS_TYPE=Bn.ATTR_K8S_POD_NAME=Bn.ATTR_K8S_NAMESPACE_NAME=Bn.ATTR_K8S_DEPLOYMENT_NAME=Bn.ATTR_K8S_CLUSTER_NAME=Bn.ATTR_HOST_TYPE=Bn.ATTR_HOST_NAME=Bn.ATTR_HOST_IMAGE_VERSION=Bn.ATTR_HOST_IMAGE_NAME=Bn.ATTR_HOST_IMAGE_ID=Bn.ATTR_HOST_ID=Bn.ATTR_HOST_ARCH=Bn.ATTR_CONTAINER_NAME=Bn.ATTR_CONTAINER_IMAGE_TAGS=Bn.ATTR_CONTAINER_IMAGE_NAME=Bn.ATTR_CONTAINER_ID=Bn.ATTR_CLOUD_REGION=Bn.ATTR_CLOUD_PROVIDER=Bn.ATTR_CLOUD_AVAILABILITY_ZONE=Bn.ATTR_CLOUD_ACCOUNT_ID=void 0;Bn.ATTR_CLOUD_ACCOUNT_ID="cloud.account.id";Bn.ATTR_CLOUD_AVAILABILITY_ZONE="cloud.availability_zone";Bn.ATTR_CLOUD_PROVIDER="cloud.provider";Bn.ATTR_CLOUD_REGION="cloud.region";Bn.ATTR_CONTAINER_ID="container.id";Bn.ATTR_CONTAINER_IMAGE_NAME="container.image.name";Bn.ATTR_CONTAINER_IMAGE_TAGS="container.image.tags";Bn.ATTR_CONTAINER_NAME="container.name";Bn.ATTR_HOST_ARCH="host.arch";Bn.ATTR_HOST_ID="host.id";Bn.ATTR_HOST_IMAGE_ID="host.image.id";Bn.ATTR_HOST_IMAGE_NAME="host.image.name";Bn.ATTR_HOST_IMAGE_VERSION="host.image.version";Bn.ATTR_HOST_NAME="host.name";Bn.ATTR_HOST_TYPE="host.type";Bn.ATTR_K8S_CLUSTER_NAME="k8s.cluster.name";Bn.ATTR_K8S_DEPLOYMENT_NAME="k8s.deployment.name";Bn.ATTR_K8S_NAMESPACE_NAME="k8s.namespace.name";Bn.ATTR_K8S_POD_NAME="k8s.pod.name";Bn.ATTR_OS_TYPE="os.type";Bn.ATTR_OS_VERSION="os.version";Bn.ATTR_PROCESS_COMMAND="process.command";Bn.ATTR_PROCESS_COMMAND_ARGS="process.command_args";Bn.ATTR_PROCESS_EXECUTABLE_NAME="process.executable.name";Bn.ATTR_PROCESS_EXECUTABLE_PATH="process.executable.path";Bn.ATTR_PROCESS_OWNER="process.owner";Bn.ATTR_PROCESS_PID="process.pid";Bn.ATTR_PROCESS_RUNTIME_DESCRIPTION="process.runtime.description";Bn.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name";Bn.ATTR_PROCESS_RUNTIME_VERSION="process.runtime.version";Bn.ATTR_SERVICE_INSTANCE_ID="service.instance.id";Bn.ATTR_SERVICE_NAMESPACE="service.namespace";Bn.ATTR_WEBENGINE_DESCRIPTION="webengine.description";Bn.ATTR_WEBENGINE_NAME="webengine.name";Bn.ATTR_WEBENGINE_VERSION="webengine.version"});var xDe=w(_De=>{"use strict";Object.defineProperty(_De,"__esModule",{value:!0});_De.execAsync=void 0;var goo=Ae("child_process"),Aoo=Ae("util");_De.execAsync=Aoo.promisify(goo.exec)});var YDr=w(SDe=>{"use strict";Object.defineProperty(SDe,"__esModule",{value:!0});SDe.getMachineId=void 0;var yoo=xDe(),Eoo=(Kt(),yt(ar));async function voo(){try{let e=(await(0,yoo.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
|
|
485
|
-
`).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){Eoo.diag.debug(`error reading machine id: ${t}`)}}SDe.getMachineId=voo});var KDr=w(wDe=>{"use strict";Object.defineProperty(wDe,"__esModule",{value:!0});wDe.getMachineId=void 0;var boo=Ae("fs"),Coo=(Kt(),yt(ar));async function _oo(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await boo.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){Coo.diag.debug(`error reading machine id: ${r}`)}}wDe.getMachineId=_oo});var XDr=w(TDe=>{"use strict";Object.defineProperty(TDe,"__esModule",{value:!0});TDe.getMachineId=void 0;var xoo=Ae("fs"),Soo=xDe(),JDr=(Kt(),yt(ar));async function woo(){try{return(await xoo.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){JDr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,Soo.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){JDr.diag.debug(`error reading machine id: ${t}`)}}TDe.getMachineId=woo});var eRr=w(IDe=>{"use strict";Object.defineProperty(IDe,"__esModule",{value:!0});IDe.getMachineId=void 0;var ZDr=Ae("process"),Too=xDe(),Ioo=(Kt(),yt(ar));async function Doo(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";ZDr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in ZDr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,Too.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){Ioo.diag.debug(`error reading machine id: ${r}`)}}IDe.getMachineId=Doo});var tRr=w(DDe=>{"use strict";Object.defineProperty(DDe,"__esModule",{value:!0});DDe.getMachineId=void 0;var Roo=(Kt(),yt(ar));async function Boo(){Roo.diag.debug("could not read machine-id: unsupported platform")}DDe.getMachineId=Boo});var rRr=w(RDe=>{"use strict";Object.defineProperty(RDe,"__esModule",{value:!0});RDe.getMachineId=void 0;var Noo=Ae("process"),IF;async function Ooo(){if(!IF)switch(Noo.platform){case"darwin":IF=(await Promise.resolve().then(()=>Te(YDr()))).getMachineId;break;case"linux":IF=(await Promise.resolve().then(()=>Te(KDr()))).getMachineId;break;case"freebsd":IF=(await Promise.resolve().then(()=>Te(XDr()))).getMachineId;break;case"win32":IF=(await Promise.resolve().then(()=>Te(eRr()))).getMachineId;break;default:IF=(await Promise.resolve().then(()=>Te(tRr()))).getMachineId;break}return IF()}RDe.getMachineId=Ooo});var N3t=w(IK=>{"use strict";Object.defineProperty(IK,"__esModule",{value:!0});IK.normalizeType=IK.normalizeArch=void 0;var koo=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};IK.normalizeArch=koo;var Poo=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};IK.normalizeType=Poo});var iRr=w(BDe=>{"use strict";Object.defineProperty(BDe,"__esModule",{value:!0});BDe.hostDetector=void 0;var O3t=Jfe(),nRr=Ae("os"),Moo=rRr(),Loo=N3t(),k3t=class{detect(e){return{attributes:{[O3t.ATTR_HOST_NAME]:(0,nRr.hostname)(),[O3t.ATTR_HOST_ARCH]:(0,Loo.normalizeArch)((0,nRr.arch)()),[O3t.ATTR_HOST_ID]:(0,Moo.getMachineId)()}}}};BDe.hostDetector=new k3t});var aRr=w(NDe=>{"use strict";Object.defineProperty(NDe,"__esModule",{value:!0});NDe.osDetector=void 0;var oRr=Jfe(),sRr=Ae("os"),Foo=N3t(),P3t=class{detect(e){return{attributes:{[oRr.ATTR_OS_TYPE]:(0,Foo.normalizeType)((0,sRr.platform)()),[oRr.ATTR_OS_VERSION]:(0,sRr.release)()}}}};NDe.osDetector=new P3t});var cRr=w(ODe=>{"use strict";Object.defineProperty(ODe,"__esModule",{value:!0});ODe.processDetector=void 0;var Uoo=(Kt(),yt(ar)),fT=Jfe(),Qoo=Ae("os"),M3t=class{detect(e){let r={[fT.ATTR_PROCESS_PID]:process.pid,[fT.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[fT.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[fT.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[fT.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[fT.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[fT.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[fT.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=Qoo.userInfo();r[fT.ATTR_PROCESS_OWNER]=n.username}catch(n){Uoo.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};ODe.processDetector=new M3t});var lRr=w(kDe=>{"use strict";Object.defineProperty(kDe,"__esModule",{value:!0});kDe.serviceInstanceIdDetector=void 0;var qoo=Jfe(),Hoo=Ae("crypto"),L3t=class{detect(e){return{attributes:{[qoo.ATTR_SERVICE_INSTANCE_ID]:(0,Hoo.randomUUID)()}}}};kDe.serviceInstanceIdDetector=new L3t});var uRr=w(fS=>{"use strict";Object.defineProperty(fS,"__esModule",{value:!0});fS.serviceInstanceIdDetector=fS.processDetector=fS.osDetector=fS.hostDetector=void 0;var Goo=iRr();Object.defineProperty(fS,"hostDetector",{enumerable:!0,get:function(){return Goo.hostDetector}});var joo=aRr();Object.defineProperty(fS,"osDetector",{enumerable:!0,get:function(){return joo.osDetector}});var Voo=cRr();Object.defineProperty(fS,"processDetector",{enumerable:!0,get:function(){return Voo.processDetector}});var $oo=lRr();Object.defineProperty(fS,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return $oo.serviceInstanceIdDetector}})});var dRr=w(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.serviceInstanceIdDetector=pS.processDetector=pS.osDetector=pS.hostDetector=void 0;var PDe=uRr();Object.defineProperty(pS,"hostDetector",{enumerable:!0,get:function(){return PDe.hostDetector}});Object.defineProperty(pS,"osDetector",{enumerable:!0,get:function(){return PDe.osDetector}});Object.defineProperty(pS,"processDetector",{enumerable:!0,get:function(){return PDe.processDetector}});Object.defineProperty(pS,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return PDe.serviceInstanceIdDetector}})});var fRr=w(DK=>{"use strict";Object.defineProperty(DK,"__esModule",{value:!0});DK.noopDetector=DK.NoopDetector=void 0;var MDe=class{detect(){return{attributes:{}}}};DK.NoopDetector=MDe;DK.noopDetector=new MDe});var pRr=w(S3=>{"use strict";Object.defineProperty(S3,"__esModule",{value:!0});S3.noopDetector=S3.serviceInstanceIdDetector=S3.processDetector=S3.osDetector=S3.hostDetector=S3.envDetector=void 0;var Woo=zDr();Object.defineProperty(S3,"envDetector",{enumerable:!0,get:function(){return Woo.envDetector}});var LDe=dRr();Object.defineProperty(S3,"hostDetector",{enumerable:!0,get:function(){return LDe.hostDetector}});Object.defineProperty(S3,"osDetector",{enumerable:!0,get:function(){return LDe.osDetector}});Object.defineProperty(S3,"processDetector",{enumerable:!0,get:function(){return LDe.processDetector}});Object.defineProperty(S3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return LDe.serviceInstanceIdDetector}});var zoo=fRr();Object.defineProperty(S3,"noopDetector",{enumerable:!0,get:function(){return zoo.noopDetector}})});var U3t=w(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});If.defaultServiceName=If.emptyResource=If.defaultResource=If.resourceFromAttributes=If.serviceInstanceIdDetector=If.processDetector=If.osDetector=If.hostDetector=If.envDetector=If.detectResources=void 0;var Yoo=$Dr();Object.defineProperty(If,"detectResources",{enumerable:!0,get:function(){return Yoo.detectResources}});var Xfe=pRr();Object.defineProperty(If,"envDetector",{enumerable:!0,get:function(){return Xfe.envDetector}});Object.defineProperty(If,"hostDetector",{enumerable:!0,get:function(){return Xfe.hostDetector}});Object.defineProperty(If,"osDetector",{enumerable:!0,get:function(){return Xfe.osDetector}});Object.defineProperty(If,"processDetector",{enumerable:!0,get:function(){return Xfe.processDetector}});Object.defineProperty(If,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Xfe.serviceInstanceIdDetector}});var F3t=D3t();Object.defineProperty(If,"resourceFromAttributes",{enumerable:!0,get:function(){return F3t.resourceFromAttributes}});Object.defineProperty(If,"defaultResource",{enumerable:!0,get:function(){return F3t.defaultResource}});Object.defineProperty(If,"emptyResource",{enumerable:!0,get:function(){return F3t.emptyResource}});var Koo=w3t();Object.defineProperty(If,"defaultServiceName",{enumerable:!0,get:function(){return Koo.defaultServiceName}})});var hRr=w(Zfe=>{"use strict";Object.defineProperty(Zfe,"__esModule",{value:!0});Zfe.SeverityNumber=void 0;var Joo;(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"})(Joo=Zfe.SeverityNumber||(Zfe.SeverityNumber={}))});var UDe=w(RK=>{"use strict";Object.defineProperty(RK,"__esModule",{value:!0});RK.NOOP_LOGGER=RK.NoopLogger=void 0;var FDe=class{emit(e){}};RK.NoopLogger=FDe;RK.NOOP_LOGGER=new FDe});var qDe=w(BK=>{"use strict";Object.defineProperty(BK,"__esModule",{value:!0});BK.NOOP_LOGGER_PROVIDER=BK.NoopLoggerProvider=void 0;var Xoo=UDe(),QDe=class{getLogger(e,r,n){return new Xoo.NoopLogger}};BK.NoopLoggerProvider=QDe;BK.NOOP_LOGGER_PROVIDER=new QDe});var q3t=w(HDe=>{"use strict";Object.defineProperty(HDe,"__esModule",{value:!0});HDe.ProxyLogger=void 0;var Zoo=UDe(),Q3t=class{constructor(e,r,n,i){this._provider=e,this.name=r,this.version=n,this.options=i}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):Zoo.NOOP_LOGGER}};HDe.ProxyLogger=Q3t});var G3t=w(GDe=>{"use strict";Object.defineProperty(GDe,"__esModule",{value:!0});GDe.ProxyLoggerProvider=void 0;var eso=qDe(),tso=q3t(),H3t=class{getLogger(e,r,n){var i;return(i=this._getDelegateLogger(e,r,n))!==null&&i!==void 0?i:new tso.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:eso.NOOP_LOGGER_PROVIDER}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,r,n){var i;return(i=this._delegate)===null||i===void 0?void 0:i.getLogger(e,r,n)}};GDe.ProxyLoggerProvider=H3t});var mRr=w(jDe=>{"use strict";Object.defineProperty(jDe,"__esModule",{value:!0});jDe._globalThis=void 0;jDe._globalThis=typeof globalThis=="object"?globalThis:global});var gRr=w(VDe=>{"use strict";Object.defineProperty(VDe,"__esModule",{value:!0});VDe._globalThis=void 0;var rso=mRr();Object.defineProperty(VDe,"_globalThis",{enumerable:!0,get:function(){return rso._globalThis}})});var ARr=w($De=>{"use strict";Object.defineProperty($De,"__esModule",{value:!0});$De._globalThis=void 0;var nso=gRr();Object.defineProperty($De,"_globalThis",{enumerable:!0,get:function(){return nso._globalThis}})});var yRr=w(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});hS.API_BACKWARDS_COMPATIBILITY_VERSION=hS.makeGetter=hS._global=hS.GLOBAL_LOGS_API_KEY=void 0;var iso=ARr();hS.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");hS._global=iso._globalThis;function oso(t,e,r){return n=>n===t?e:r}hS.makeGetter=oso;hS.API_BACKWARDS_COMPATIBILITY_VERSION=1});var vRr=w(WDe=>{"use strict";Object.defineProperty(WDe,"__esModule",{value:!0});WDe.LogsAPI=void 0;var jv=yRr(),sso=qDe(),ERr=G3t(),j3t=class t{constructor(){this._proxyLoggerProvider=new ERr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return jv._global[jv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(jv._global[jv.GLOBAL_LOGS_API_KEY]=(0,jv.makeGetter)(jv.API_BACKWARDS_COMPATIBILITY_VERSION,e,sso.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=jv._global[jv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(jv._global,jv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete jv._global[jv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new ERr.ProxyLoggerProvider}};WDe.LogsAPI=j3t});var _Rr=w(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});Um.logs=Um.ProxyLoggerProvider=Um.ProxyLogger=Um.NoopLoggerProvider=Um.NOOP_LOGGER_PROVIDER=Um.NoopLogger=Um.NOOP_LOGGER=Um.SeverityNumber=void 0;var aso=hRr();Object.defineProperty(Um,"SeverityNumber",{enumerable:!0,get:function(){return aso.SeverityNumber}});var bRr=UDe();Object.defineProperty(Um,"NOOP_LOGGER",{enumerable:!0,get:function(){return bRr.NOOP_LOGGER}});Object.defineProperty(Um,"NoopLogger",{enumerable:!0,get:function(){return bRr.NoopLogger}});var CRr=qDe();Object.defineProperty(Um,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return CRr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(Um,"NoopLoggerProvider",{enumerable:!0,get:function(){return CRr.NoopLoggerProvider}});var cso=q3t();Object.defineProperty(Um,"ProxyLogger",{enumerable:!0,get:function(){return cso.ProxyLogger}});var lso=G3t();Object.defineProperty(Um,"ProxyLoggerProvider",{enumerable:!0,get:function(){return lso.ProxyLoggerProvider}});var uso=vRr();Um.logs=uso.LogsAPI.getInstance()});var epe=w(fB=>{"use strict";Object.defineProperty(fB,"__esModule",{value:!0});fB.isTracingSuppressed=fB.unsuppressTracing=fB.suppressTracing=void 0;var dso=(Kt(),yt(ar)),V3t=(0,dso.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function fso(t){return t.setValue(V3t,!0)}fB.suppressTracing=fso;function pso(t){return t.deleteValue(V3t)}fB.unsuppressTracing=pso;function hso(t){return t.getValue(V3t)===!0}fB.isTracingSuppressed=hso});var $3t=w(A2=>{"use strict";Object.defineProperty(A2,"__esModule",{value:!0});A2.BAGGAGE_MAX_TOTAL_LENGTH=A2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=A2.BAGGAGE_MAX_NAME_VALUE_PAIRS=A2.BAGGAGE_HEADER=A2.BAGGAGE_ITEMS_SEPARATOR=A2.BAGGAGE_PROPERTIES_SEPARATOR=A2.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;A2.BAGGAGE_KEY_PAIR_SEPARATOR="=";A2.BAGGAGE_PROPERTIES_SEPARATOR=";";A2.BAGGAGE_ITEMS_SEPARATOR=",";A2.BAGGAGE_HEADER="baggage";A2.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;A2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;A2.BAGGAGE_MAX_TOTAL_LENGTH=8192});var W3t=w(mS=>{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});mS.parseKeyPairsIntoRecord=mS.parsePairKeyValue=mS.getKeyPairs=mS.serializeKeyPairs=void 0;var mso=(Kt(),yt(ar)),DF=$3t();function gso(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?DF.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>DF.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}mS.serializeKeyPairs=gso;function Aso(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=DF.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}mS.getKeyPairs=Aso;function xRr(t){let e=t.split(DF.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(DF.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim()),s;return e.length>0&&(s=(0,mso.baggageEntryMetadataFromString)(e.join(DF.BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}mS.parsePairKeyValue=xRr;function yso(t){let e={};return typeof t=="string"&&t.length>0&&t.split(DF.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=xRr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}mS.parseKeyPairsIntoRecord=yso});var SRr=w(zDe=>{"use strict";Object.defineProperty(zDe,"__esModule",{value:!0});zDe.W3CBaggagePropagator=void 0;var z3t=(Kt(),yt(ar)),Eso=epe(),RF=$3t(),Y3t=W3t(),K3t=class{inject(e,r,n){let i=z3t.propagation.getBaggage(e);if(!i||(0,Eso.isTracingSuppressed)(e))return;let o=(0,Y3t.getKeyPairs)(i).filter(a=>a.length<=RF.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,RF.BAGGAGE_MAX_NAME_VALUE_PAIRS),s=(0,Y3t.serializeKeyPairs)(o);s.length>0&&n.set(r,RF.BAGGAGE_HEADER,s)}extract(e,r,n){let i=n.get(r,RF.BAGGAGE_HEADER),o=Array.isArray(i)?i.join(RF.BAGGAGE_ITEMS_SEPARATOR):i;if(!o)return e;let s={};return o.length===0||(o.split(RF.BAGGAGE_ITEMS_SEPARATOR).forEach(c=>{let u=(0,Y3t.parsePairKeyValue)(c);if(u){let d={value:u.value};u.metadata&&(d.metadata=u.metadata),s[u.key]=d}}),Object.entries(s).length===0)?e:z3t.propagation.setBaggage(e,z3t.propagation.createBaggage(s))}fields(){return[RF.BAGGAGE_HEADER]}};zDe.W3CBaggagePropagator=K3t});var wRr=w(YDe=>{"use strict";Object.defineProperty(YDe,"__esModule",{value:!0});YDe.AnchoredClock=void 0;var J3t=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};YDe.AnchoredClock=J3t});var BRr=w(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0});pB.isAttributeValue=pB.isAttributeKey=pB.sanitizeAttributes=void 0;var TRr=(Kt(),yt(ar));function vso(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!IRr(r)){TRr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!DRr(n)){TRr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}pB.sanitizeAttributes=vso;function IRr(t){return typeof t=="string"&&t!==""}pB.isAttributeKey=IRr;function DRr(t){return t==null?!0:Array.isArray(t)?bso(t):RRr(typeof t)}pB.isAttributeValue=DRr;function bso(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(RRr(n)){e=n;continue}return!1}return!1}}return!0}function RRr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var X3t=w(KDe=>{"use strict";Object.defineProperty(KDe,"__esModule",{value:!0});KDe.loggingErrorHandler=void 0;var Cso=(Kt(),yt(ar));function _so(){return t=>{Cso.diag.error(xso(t))}}KDe.loggingErrorHandler=_so;function xso(t){return typeof t=="string"?t:JSON.stringify(Sso(t))}function Sso(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let i=r[n];i&&(e[n]=String(i))}),r=Object.getPrototypeOf(r);return e}});var ORr=w(NK=>{"use strict";Object.defineProperty(NK,"__esModule",{value:!0});NK.globalErrorHandler=NK.setGlobalErrorHandler=void 0;var wso=X3t(),NRr=(0,wso.loggingErrorHandler)();function Tso(t){NRr=t}NK.setGlobalErrorHandler=Tso;function Iso(t){try{NRr(t)}catch{}}NK.globalErrorHandler=Iso});var LRr=w(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.getStringListFromEnv=gS.getBooleanFromEnv=gS.getStringFromEnv=gS.getNumberFromEnv=void 0;var kRr=(Kt(),yt(ar)),PRr=Ae("util");function Dso(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){kRr.diag.warn(`Unknown value ${(0,PRr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}gS.getNumberFromEnv=Dso;function MRr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}gS.getStringFromEnv=MRr;function Rso(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||kRr.diag.warn(`Unknown value ${(0,PRr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}gS.getBooleanFromEnv=Rso;function Bso(t){return MRr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}gS.getStringListFromEnv=Bso});var FRr=w(JDe=>{"use strict";Object.defineProperty(JDe,"__esModule",{value:!0});JDe._globalThis=void 0;JDe._globalThis=typeof globalThis=="object"?globalThis:global});var URr=w(XDe=>{"use strict";Object.defineProperty(XDe,"__esModule",{value:!0});XDe.otperformance=void 0;var Nso=Ae("perf_hooks");XDe.otperformance=Nso.performance});var QRr=w(ZDe=>{"use strict";Object.defineProperty(ZDe,"__esModule",{value:!0});ZDe.VERSION=void 0;ZDe.VERSION="2.2.0"});var qRr=w(eRe=>{"use strict";Object.defineProperty(eRe,"__esModule",{value:!0});eRe.ATTR_PROCESS_RUNTIME_NAME=void 0;eRe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var HRr=w(rRe=>{"use strict";Object.defineProperty(rRe,"__esModule",{value:!0});rRe.SDK_INFO=void 0;var Oso=QRr(),tRe=(Nh(),yt(c2)),kso=qRr();rRe.SDK_INFO={[tRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[kso.ATTR_PROCESS_RUNTIME_NAME]:"node",[tRe.ATTR_TELEMETRY_SDK_LANGUAGE]:tRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[tRe.ATTR_TELEMETRY_SDK_VERSION]:Oso.VERSION}});var GRr=w(y2=>{"use strict";Object.defineProperty(y2,"__esModule",{value:!0});y2.SDK_INFO=y2.otperformance=y2._globalThis=y2.getStringListFromEnv=y2.getNumberFromEnv=y2.getBooleanFromEnv=y2.getStringFromEnv=void 0;var nRe=LRr();Object.defineProperty(y2,"getStringFromEnv",{enumerable:!0,get:function(){return nRe.getStringFromEnv}});Object.defineProperty(y2,"getBooleanFromEnv",{enumerable:!0,get:function(){return nRe.getBooleanFromEnv}});Object.defineProperty(y2,"getNumberFromEnv",{enumerable:!0,get:function(){return nRe.getNumberFromEnv}});Object.defineProperty(y2,"getStringListFromEnv",{enumerable:!0,get:function(){return nRe.getStringListFromEnv}});var Pso=FRr();Object.defineProperty(y2,"_globalThis",{enumerable:!0,get:function(){return Pso._globalThis}});var Mso=URr();Object.defineProperty(y2,"otperformance",{enumerable:!0,get:function(){return Mso.otperformance}});var Lso=HRr();Object.defineProperty(y2,"SDK_INFO",{enumerable:!0,get:function(){return Lso.SDK_INFO}})});var Z3t=w(E2=>{"use strict";Object.defineProperty(E2,"__esModule",{value:!0});E2.getStringListFromEnv=E2.getNumberFromEnv=E2.getStringFromEnv=E2.getBooleanFromEnv=E2.otperformance=E2._globalThis=E2.SDK_INFO=void 0;var BF=GRr();Object.defineProperty(E2,"SDK_INFO",{enumerable:!0,get:function(){return BF.SDK_INFO}});Object.defineProperty(E2,"_globalThis",{enumerable:!0,get:function(){return BF._globalThis}});Object.defineProperty(E2,"otperformance",{enumerable:!0,get:function(){return BF.otperformance}});Object.defineProperty(E2,"getBooleanFromEnv",{enumerable:!0,get:function(){return BF.getBooleanFromEnv}});Object.defineProperty(E2,"getStringFromEnv",{enumerable:!0,get:function(){return BF.getStringFromEnv}});Object.defineProperty(E2,"getNumberFromEnv",{enumerable:!0,get:function(){return BF.getNumberFromEnv}});Object.defineProperty(E2,"getStringListFromEnv",{enumerable:!0,get:function(){return BF.getStringListFromEnv}})});var WRr=w(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.addHrTimes=hu.isTimeInput=hu.isTimeInputHrTime=hu.hrTimeToMicroseconds=hu.hrTimeToMilliseconds=hu.hrTimeToNanoseconds=hu.hrTimeToTimeStamp=hu.hrTimeDuration=hu.timeInputToHrTime=hu.hrTime=hu.getTimeOrigin=hu.millisToHrTime=void 0;var eyt=Z3t(),jRr=9,Fso=6,Uso=Math.pow(10,Fso),iRe=Math.pow(10,jRr);function tpe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Uso);return[r,n]}hu.millisToHrTime=tpe;function tyt(){let t=eyt.otperformance.timeOrigin;if(typeof t!="number"){let e=eyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}hu.getTimeOrigin=tyt;function VRr(t){let e=tpe(tyt()),r=tpe(typeof t=="number"?t:eyt.otperformance.now());return $Rr(e,r)}hu.hrTime=VRr;function Qso(t){if(ryt(t))return t;if(typeof t=="number")return t<tyt()?VRr(t):tpe(t);if(t instanceof Date)return tpe(t.getTime());throw TypeError("Invalid input type")}hu.timeInputToHrTime=Qso;function qso(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=iRe),[r,n]}hu.hrTimeDuration=qso;function Hso(t){let e=jRr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}hu.hrTimeToTimeStamp=Hso;function Gso(t){return t[0]*iRe+t[1]}hu.hrTimeToNanoseconds=Gso;function jso(t){return t[0]*1e3+t[1]/1e6}hu.hrTimeToMilliseconds=jso;function Vso(t){return t[0]*1e6+t[1]/1e3}hu.hrTimeToMicroseconds=Vso;function ryt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}hu.isTimeInputHrTime=ryt;function $so(t){return ryt(t)||typeof t=="number"||t instanceof Date}hu.isTimeInput=$so;function $Rr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=iRe&&(r[1]-=iRe,r[0]+=1),r}hu.addHrTimes=$Rr});var zRr=w(oRe=>{"use strict";Object.defineProperty(oRe,"__esModule",{value:!0});oRe.unrefTimer=void 0;function Wso(t){typeof t!="number"&&t.unref()}oRe.unrefTimer=Wso});var YRr=w(rpe=>{"use strict";Object.defineProperty(rpe,"__esModule",{value:!0});rpe.ExportResultCode=void 0;var zso;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(zso=rpe.ExportResultCode||(rpe.ExportResultCode={}))});var JRr=w(sRe=>{"use strict";Object.defineProperty(sRe,"__esModule",{value:!0});sRe.CompositePropagator=void 0;var KRr=(Kt(),yt(ar)),nyt=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let i of this._propagators)try{i.inject(e,r,n)}catch(o){KRr.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${o.message}`)}}extract(e,r,n){return this._propagators.reduce((i,o)=>{try{return o.extract(i,r,n)}catch(s){KRr.diag.warn(`Failed to extract with ${o.constructor.name}. Err: ${s.message}`)}return i},e)}fields(){return this._fields.slice()}};sRe.CompositePropagator=nyt});var XRr=w(OK=>{"use strict";Object.defineProperty(OK,"__esModule",{value:!0});OK.validateValue=OK.validateKey=void 0;var iyt="[_0-9a-z-*/]",Yso=`[a-z]${iyt}{0,255}`,Kso=`[a-z0-9]${iyt}{0,240}@[a-z]${iyt}{0,13}`,Jso=new RegExp(`^(?:${Yso}|${Kso})$`),Xso=/^[ -~]{0,255}[!-~]$/,Zso=/,|=/;function eao(t){return Jso.test(t)}OK.validateKey=eao;function tao(t){return Xso.test(t)&&!Zso.test(t)}OK.validateValue=tao});var syt=w(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0});aRe.TraceState=void 0;var ZRr=XRr(),eBr=32,rao=512,tBr=",",rBr="=",oyt=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+rBr+this.get(r)),e),[]).join(tBr)}_parse(e){e.length>rao||(this._internalState=e.split(tBr).reverse().reduce((r,n)=>{let i=n.trim(),o=i.indexOf(rBr);if(o!==-1){let s=i.slice(0,o),a=i.slice(o+1,n.length);(0,ZRr.validateKey)(s)&&(0,ZRr.validateValue)(a)&&r.set(s,a)}return r},new Map),this._internalState.size>eBr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,eBr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};aRe.TraceState=oyt});var iBr=w(v2=>{"use strict";Object.defineProperty(v2,"__esModule",{value:!0});v2.W3CTraceContextPropagator=v2.parseTraceParent=v2.TRACE_STATE_HEADER=v2.TRACE_PARENT_HEADER=void 0;var cRe=(Kt(),yt(ar)),nao=epe(),iao=syt();v2.TRACE_PARENT_HEADER="traceparent";v2.TRACE_STATE_HEADER="tracestate";var oao="00",sao="(?!ff)[\\da-f]{2}",aao="(?![0]{32})[\\da-f]{32}",cao="(?![0]{16})[\\da-f]{16}",lao="[\\da-f]{2}",uao=new RegExp(`^\\s?(${sao})-(${aao})-(${cao})-(${lao})(-.*)?\\s?$`);function nBr(t){let e=uao.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}v2.parseTraceParent=nBr;var ayt=class{inject(e,r,n){let i=cRe.trace.getSpanContext(e);if(!i||(0,nao.isTracingSuppressed)(e)||!(0,cRe.isSpanContextValid)(i))return;let o=`${oao}-${i.traceId}-${i.spanId}-0${Number(i.traceFlags||cRe.TraceFlags.NONE).toString(16)}`;n.set(r,v2.TRACE_PARENT_HEADER,o),i.traceState&&n.set(r,v2.TRACE_STATE_HEADER,i.traceState.serialize())}extract(e,r,n){let i=n.get(r,v2.TRACE_PARENT_HEADER);if(!i)return e;let o=Array.isArray(i)?i[0]:i;if(typeof o!="string")return e;let s=nBr(o);if(!s)return e;s.isRemote=!0;let a=n.get(r,v2.TRACE_STATE_HEADER);if(a){let c=Array.isArray(a)?a.join(","):a;s.traceState=new iao.TraceState(typeof c=="string"?c:void 0)}return cRe.trace.setSpanContext(e,s)}fields(){return[v2.TRACE_PARENT_HEADER,v2.TRACE_STATE_HEADER]}};v2.W3CTraceContextPropagator=ayt});var oBr=w(ZC=>{"use strict";Object.defineProperty(ZC,"__esModule",{value:!0});ZC.getRPCMetadata=ZC.deleteRPCMetadata=ZC.setRPCMetadata=ZC.RPCType=void 0;var dao=(Kt(),yt(ar)),cyt=(0,dao.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),fao;(function(t){t.HTTP="http"})(fao=ZC.RPCType||(ZC.RPCType={}));function pao(t,e){return t.setValue(cyt,e)}ZC.setRPCMetadata=pao;function hao(t){return t.deleteValue(cyt)}ZC.deleteRPCMetadata=hao;function mao(t){return t.getValue(cyt)}ZC.getRPCMetadata=mao});var uBr=w(lRe=>{"use strict";Object.defineProperty(lRe,"__esModule",{value:!0});lRe.isPlainObject=void 0;var gao="[object Object]",Aao="[object Null]",yao="[object Undefined]",Eao=Function.prototype,sBr=Eao.toString,vao=sBr.call(Object),bao=Object.getPrototypeOf,aBr=Object.prototype,cBr=aBr.hasOwnProperty,NF=Symbol?Symbol.toStringTag:void 0,lBr=aBr.toString;function Cao(t){if(!_ao(t)||xao(t)!==gao)return!1;let e=bao(t);if(e===null)return!0;let r=cBr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&sBr.call(r)===vao}lRe.isPlainObject=Cao;function _ao(t){return t!=null&&typeof t=="object"}function xao(t){return t==null?t===void 0?yao:Aao:NF&&NF in Object(t)?Sao(t):wao(t)}function Sao(t){let e=cBr.call(t,NF),r=t[NF],n=!1;try{t[NF]=void 0,n=!0}catch{}let i=lBr.call(t);return n&&(e?t[NF]=r:delete t[NF]),i}function wao(t){return lBr.call(t)}});var mBr=w(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.merge=void 0;var dBr=uBr(),Tao=20;function Iao(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=pBr(e,t.shift(),0,r);return e}fRe.merge=Iao;function lyt(t){return dRe(t)?t.slice():t}function pBr(t,e,r=0,n){let i;if(!(r>Tao)){if(r++,uRe(t)||uRe(e)||hBr(e))i=lyt(e);else if(dRe(t)){if(i=t.slice(),dRe(e))for(let o=0,s=e.length;o<s;o++)i.push(lyt(e[o]));else if(npe(e)){let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s];i[c]=lyt(e[c])}}}else if(npe(t))if(npe(e)){if(!Dao(t,e))return e;i=Object.assign({},t);let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s],u=e[c];if(uRe(u))typeof u>"u"?delete i[c]:i[c]=u;else{let d=i[c],f=u;if(fBr(t,c,n)||fBr(e,c,n))delete i[c];else{if(npe(d)&&npe(f)){let p=n.get(d)||[],h=n.get(f)||[];p.push({obj:t,key:c}),h.push({obj:e,key:c}),n.set(d,p),n.set(f,h)}i[c]=pBr(i[c],u,r,n)}}}}else i=e;return i}}function fBr(t,e,r){let n=r.get(t[e])||[];for(let i=0,o=n.length;i<o;i++){let s=n[i];if(s.key===e&&s.obj===t)return!0}return!1}function dRe(t){return Array.isArray(t)}function hBr(t){return typeof t=="function"}function npe(t){return!uRe(t)&&!dRe(t)&&!hBr(t)&&typeof t=="object"}function uRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Dao(t,e){return!(!(0,dBr.isPlainObject)(t)||!(0,dBr.isPlainObject)(e))}});var gBr=w(kK=>{"use strict";Object.defineProperty(kK,"__esModule",{value:!0});kK.callWithTimeout=kK.TimeoutError=void 0;var pRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};kK.TimeoutError=pRe;function Rao(t,e){let r,n=new Promise(function(o,s){r=setTimeout(function(){s(new pRe("Operation timed out."))},e)});return Promise.race([t,n]).then(i=>(clearTimeout(r),i),i=>{throw clearTimeout(r),i})}kK.callWithTimeout=Rao});var yBr=w(PK=>{"use strict";Object.defineProperty(PK,"__esModule",{value:!0});PK.isUrlIgnored=PK.urlMatches=void 0;function ABr(t,e){return typeof e=="string"?t===e:!!t.match(e)}PK.urlMatches=ABr;function Bao(t,e){if(!e)return!1;for(let r of e)if(ABr(t,r))return!0;return!1}PK.isUrlIgnored=Bao});var EBr=w(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.Deferred=void 0;var uyt=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};hRe.Deferred=uyt});var vBr=w(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.BindOnceFuture=void 0;var Nao=EBr(),dyt=class{_callback;_that;_isCalled=!1;_deferred=new Nao.Deferred;constructor(e,r){this._callback=e,this._that=r}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(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};mRe.BindOnceFuture=dyt});var CBr=w(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.diagLogLevelFromString=void 0;var pT=(Kt(),yt(ar)),bBr={ALL:pT.DiagLogLevel.ALL,VERBOSE:pT.DiagLogLevel.VERBOSE,DEBUG:pT.DiagLogLevel.DEBUG,INFO:pT.DiagLogLevel.INFO,WARN:pT.DiagLogLevel.WARN,ERROR:pT.DiagLogLevel.ERROR,NONE:pT.DiagLogLevel.NONE};function Oao(t){if(t==null)return;let e=bBr[t.toUpperCase()];return e??(pT.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(bBr)}, using default`),pT.DiagLogLevel.INFO)}gRe.diagLogLevelFromString=Oao});var xBr=w(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe._export=void 0;var _Br=(Kt(),yt(ar)),kao=epe();function Pao(t,e){return new Promise(r=>{_Br.context.with((0,kao.suppressTracing)(_Br.context.active()),()=>{t.export(e,n=>{r(n)})})})}ARe._export=Pao});var hT=w(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.internal=Lr.diagLogLevelFromString=Lr.BindOnceFuture=Lr.urlMatches=Lr.isUrlIgnored=Lr.callWithTimeout=Lr.TimeoutError=Lr.merge=Lr.TraceState=Lr.unsuppressTracing=Lr.suppressTracing=Lr.isTracingSuppressed=Lr.setRPCMetadata=Lr.getRPCMetadata=Lr.deleteRPCMetadata=Lr.RPCType=Lr.parseTraceParent=Lr.W3CTraceContextPropagator=Lr.TRACE_STATE_HEADER=Lr.TRACE_PARENT_HEADER=Lr.CompositePropagator=Lr.otperformance=Lr.getStringListFromEnv=Lr.getNumberFromEnv=Lr.getBooleanFromEnv=Lr.getStringFromEnv=Lr._globalThis=Lr.SDK_INFO=Lr.parseKeyPairsIntoRecord=Lr.ExportResultCode=Lr.unrefTimer=Lr.timeInputToHrTime=Lr.millisToHrTime=Lr.isTimeInputHrTime=Lr.isTimeInput=Lr.hrTimeToTimeStamp=Lr.hrTimeToNanoseconds=Lr.hrTimeToMilliseconds=Lr.hrTimeToMicroseconds=Lr.hrTimeDuration=Lr.hrTime=Lr.getTimeOrigin=Lr.addHrTimes=Lr.loggingErrorHandler=Lr.setGlobalErrorHandler=Lr.globalErrorHandler=Lr.sanitizeAttributes=Lr.isAttributeValue=Lr.AnchoredClock=Lr.W3CBaggagePropagator=void 0;var Mao=SRr();Object.defineProperty(Lr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Mao.W3CBaggagePropagator}});var Lao=wRr();Object.defineProperty(Lr,"AnchoredClock",{enumerable:!0,get:function(){return Lao.AnchoredClock}});var SBr=BRr();Object.defineProperty(Lr,"isAttributeValue",{enumerable:!0,get:function(){return SBr.isAttributeValue}});Object.defineProperty(Lr,"sanitizeAttributes",{enumerable:!0,get:function(){return SBr.sanitizeAttributes}});var wBr=ORr();Object.defineProperty(Lr,"globalErrorHandler",{enumerable:!0,get:function(){return wBr.globalErrorHandler}});Object.defineProperty(Lr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return wBr.setGlobalErrorHandler}});var Fao=X3t();Object.defineProperty(Lr,"loggingErrorHandler",{enumerable:!0,get:function(){return Fao.loggingErrorHandler}});var Vv=WRr();Object.defineProperty(Lr,"addHrTimes",{enumerable:!0,get:function(){return Vv.addHrTimes}});Object.defineProperty(Lr,"getTimeOrigin",{enumerable:!0,get:function(){return Vv.getTimeOrigin}});Object.defineProperty(Lr,"hrTime",{enumerable:!0,get:function(){return Vv.hrTime}});Object.defineProperty(Lr,"hrTimeDuration",{enumerable:!0,get:function(){return Vv.hrTimeDuration}});Object.defineProperty(Lr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return Vv.hrTimeToMicroseconds}});Object.defineProperty(Lr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return Vv.hrTimeToMilliseconds}});Object.defineProperty(Lr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return Vv.hrTimeToNanoseconds}});Object.defineProperty(Lr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return Vv.hrTimeToTimeStamp}});Object.defineProperty(Lr,"isTimeInput",{enumerable:!0,get:function(){return Vv.isTimeInput}});Object.defineProperty(Lr,"isTimeInputHrTime",{enumerable:!0,get:function(){return Vv.isTimeInputHrTime}});Object.defineProperty(Lr,"millisToHrTime",{enumerable:!0,get:function(){return Vv.millisToHrTime}});Object.defineProperty(Lr,"timeInputToHrTime",{enumerable:!0,get:function(){return Vv.timeInputToHrTime}});var Uao=zRr();Object.defineProperty(Lr,"unrefTimer",{enumerable:!0,get:function(){return Uao.unrefTimer}});var Qao=YRr();Object.defineProperty(Lr,"ExportResultCode",{enumerable:!0,get:function(){return Qao.ExportResultCode}});var qao=W3t();Object.defineProperty(Lr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return qao.parseKeyPairsIntoRecord}});var OF=Z3t();Object.defineProperty(Lr,"SDK_INFO",{enumerable:!0,get:function(){return OF.SDK_INFO}});Object.defineProperty(Lr,"_globalThis",{enumerable:!0,get:function(){return OF._globalThis}});Object.defineProperty(Lr,"getStringFromEnv",{enumerable:!0,get:function(){return OF.getStringFromEnv}});Object.defineProperty(Lr,"getBooleanFromEnv",{enumerable:!0,get:function(){return OF.getBooleanFromEnv}});Object.defineProperty(Lr,"getNumberFromEnv",{enumerable:!0,get:function(){return OF.getNumberFromEnv}});Object.defineProperty(Lr,"getStringListFromEnv",{enumerable:!0,get:function(){return OF.getStringListFromEnv}});Object.defineProperty(Lr,"otperformance",{enumerable:!0,get:function(){return OF.otperformance}});var Hao=JRr();Object.defineProperty(Lr,"CompositePropagator",{enumerable:!0,get:function(){return Hao.CompositePropagator}});var yRe=iBr();Object.defineProperty(Lr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return yRe.TRACE_PARENT_HEADER}});Object.defineProperty(Lr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return yRe.TRACE_STATE_HEADER}});Object.defineProperty(Lr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return yRe.W3CTraceContextPropagator}});Object.defineProperty(Lr,"parseTraceParent",{enumerable:!0,get:function(){return yRe.parseTraceParent}});var ERe=oBr();Object.defineProperty(Lr,"RPCType",{enumerable:!0,get:function(){return ERe.RPCType}});Object.defineProperty(Lr,"deleteRPCMetadata",{enumerable:!0,get:function(){return ERe.deleteRPCMetadata}});Object.defineProperty(Lr,"getRPCMetadata",{enumerable:!0,get:function(){return ERe.getRPCMetadata}});Object.defineProperty(Lr,"setRPCMetadata",{enumerable:!0,get:function(){return ERe.setRPCMetadata}});var fyt=epe();Object.defineProperty(Lr,"isTracingSuppressed",{enumerable:!0,get:function(){return fyt.isTracingSuppressed}});Object.defineProperty(Lr,"suppressTracing",{enumerable:!0,get:function(){return fyt.suppressTracing}});Object.defineProperty(Lr,"unsuppressTracing",{enumerable:!0,get:function(){return fyt.unsuppressTracing}});var Gao=syt();Object.defineProperty(Lr,"TraceState",{enumerable:!0,get:function(){return Gao.TraceState}});var jao=mBr();Object.defineProperty(Lr,"merge",{enumerable:!0,get:function(){return jao.merge}});var TBr=gBr();Object.defineProperty(Lr,"TimeoutError",{enumerable:!0,get:function(){return TBr.TimeoutError}});Object.defineProperty(Lr,"callWithTimeout",{enumerable:!0,get:function(){return TBr.callWithTimeout}});var IBr=yBr();Object.defineProperty(Lr,"isUrlIgnored",{enumerable:!0,get:function(){return IBr.isUrlIgnored}});Object.defineProperty(Lr,"urlMatches",{enumerable:!0,get:function(){return IBr.urlMatches}});var Vao=vBr();Object.defineProperty(Lr,"BindOnceFuture",{enumerable:!0,get:function(){return Vao.BindOnceFuture}});var $ao=CBr();Object.defineProperty(Lr,"diagLogLevelFromString",{enumerable:!0,get:function(){return $ao.diagLogLevelFromString}});var Wao=xBr();Lr.internal={_export:Wao._export}});var DBr=w(bRe=>{"use strict";Object.defineProperty(bRe,"__esModule",{value:!0});bRe.LogRecordImpl=void 0;var kF=(Kt(),yt(ar)),vRe=hT(),pyt=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,n){let{timestamp:i,observedTimestamp:o,eventName:s,severityNumber:a,severityText:c,body:u,attributes:d={},context:f}=n,p=Date.now();if(this.hrTime=(0,vRe.timeInputToHrTime)(i??p),this.hrTimeObserved=(0,vRe.timeInputToHrTime)(o??p),f){let h=kF.trace.getSpanContext(f);h&&kF.isSpanContextValid(h)&&(this.spanContext=h)}this.severityNumber=a,this.severityText=c,this.body=u,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=s,this.setAttributes(d)}setAttribute(e,r){return this._isLogRecordReadonly()?this:r===null?this:e.length===0?(kF.diag.warn(`Invalid attribute key: ${e}`),this):!(0,vRe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(kF.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&kF.diag.warn("Dropping extra attributes."),this):((0,vRe.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let r=this._logRecordLimits.attributeValueLengthLimit;return r<=0?(kF.diag.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(n=>typeof n=="string"?this._truncateToLimitUtil(n,r):n):e}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_isLogRecordReadonly(){return this._isReadonly&&kF.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};bRe.LogRecordImpl=pyt});var RBr=w(CRe=>{"use strict";Object.defineProperty(CRe,"__esModule",{value:!0});CRe.Logger=void 0;var zao=(Kt(),yt(ar)),Yao=DBr(),hyt=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||zao.context.active(),n=new Yao.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};CRe.Logger=hyt});var BBr=w(LK=>{"use strict";Object.defineProperty(LK,"__esModule",{value:!0});LK.reconfigureLimits=LK.loadDefaultConfig=void 0;var MK=hT();function Kao(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}LK.loadDefaultConfig=Kao;function Jao(t){return{attributeCountLimit:t.attributeCountLimit??(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??(0,MK.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:t.attributeValueLengthLimit??(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??(0,MK.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}LK.reconfigureLimits=Jao});var gyt=w(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.NoopLogRecordProcessor=void 0;var myt=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};_Re.NoopLogRecordProcessor=myt});var NBr=w(xRe=>{"use strict";Object.defineProperty(xRe,"__esModule",{value:!0});xRe.MultiLogRecordProcessor=void 0;var Xao=hT(),Ayt=class{processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>(0,Xao.callWithTimeout)(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(n=>n.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};xRe.MultiLogRecordProcessor=Ayt});var OBr=w(SRe=>{"use strict";Object.defineProperty(SRe,"__esModule",{value:!0});SRe.LoggerProviderSharedState=void 0;var Zao=gyt(),eco=NBr(),yyt=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,n,i){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=n,this.processors=i,i.length>0?(this.registeredLogRecordProcessors=i,this.activeProcessor=new eco.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Zao.NoopLogRecordProcessor}};SRe.LoggerProviderSharedState=yyt});var MBr=w(PF=>{"use strict";Object.defineProperty(PF,"__esModule",{value:!0});PF.LoggerProvider=PF.DEFAULT_LOGGER_NAME=void 0;var wRe=(Kt(),yt(ar)),tco=_Rr(),rco=U3t(),kBr=hT(),nco=RBr(),PBr=BBr(),ico=OBr();PF.DEFAULT_LOGGER_NAME="unknown";var Eyt=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,kBr.merge)({},(0,PBr.loadDefaultConfig)(),e),n=e.resource??(0,rco.defaultResource)();this._sharedState=new ico.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,PBr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new kBr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return wRe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),tco.NOOP_LOGGER;e||wRe.diag.warn("Logger requested without instrumentation scope name.");let i=e||PF.DEFAULT_LOGGER_NAME,o=`${i}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(o)||this._sharedState.loggers.set(o,new nco.Logger({name:i,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(o)}forceFlush(){return this._shutdownOnce.isCalled?(wRe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(wRe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};PF.LoggerProvider=Eyt});var FBr=w(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0});TRe.ConsoleLogRecordExporter=void 0;var LBr=hT(),vyt=class{export(e,r){this._sendLogRecords(e,r)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,LBr.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,r){for(let n of e)console.dir(this._exportInfo(n),{depth:3});r?.({code:LBr.ExportResultCode.SUCCESS})}};TRe.ConsoleLogRecordExporter=vyt});var UBr=w(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.SimpleLogRecordProcessor=void 0;var FK=hT(),byt=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new FK.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let r=()=>FK.internal._export(this._exporter,[e]).then(n=>{n.code!==FK.ExportResultCode.SUCCESS&&(0,FK.globalErrorHandler)(n.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${n})`))}).catch(FK.globalErrorHandler);if(e.resource.asyncAttributesPending){let n=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(n),r()),FK.globalErrorHandler);n!=null&&this._unresolvedExports.add(n)}else r()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}};IRe.SimpleLogRecordProcessor=byt});var qBr=w(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe.InMemoryLogRecordExporter=void 0;var QBr=hT(),Cyt=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:QBr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:QBr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};DRe.InMemoryLogRecordExporter=Cyt});var HBr=w(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe.BatchLogRecordProcessorBase=void 0;var oco=(Kt(),yt(ar)),$v=hT(),_yt=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,$v.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,$v.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,$v.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,$v.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new $v.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(oco.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,r)=>{let n=[],i=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let o=0;o<i;o++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(r)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,r)=>{(0,$v.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(r)})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().then(()=>{this._isExporting=!1,this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(r=>{this._isExporting=!1,(0,$v.globalErrorHandler)(r)})};if(this._finishedLogRecords.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let r=()=>$v.internal._export(this._exporter,e).then(i=>{i.code!==$v.ExportResultCode.SUCCESS&&(0,$v.globalErrorHandler)(i.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${i})`))}).catch($v.globalErrorHandler),n=e.map(i=>i.resource).filter(i=>i.asyncAttributesPending);return n.length===0?r():Promise.all(n.map(i=>i.waitForAsyncAttributes?.())).then(r,$v.globalErrorHandler)}};RRe.BatchLogRecordProcessorBase=_yt});var GBr=w(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.BatchLogRecordProcessor=void 0;var sco=HBr(),xyt=class extends sco.BatchLogRecordProcessorBase{onShutdown(){}};BRe.BatchLogRecordProcessor=xyt});var jBr=w(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe.BatchLogRecordProcessor=void 0;var aco=GBr();Object.defineProperty(NRe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return aco.BatchLogRecordProcessor}})});var VBr=w(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe.BatchLogRecordProcessor=void 0;var cco=jBr();Object.defineProperty(ORe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return cco.BatchLogRecordProcessor}})});var $Br=w(w3=>{"use strict";Object.defineProperty(w3,"__esModule",{value:!0});w3.BatchLogRecordProcessor=w3.InMemoryLogRecordExporter=w3.SimpleLogRecordProcessor=w3.ConsoleLogRecordExporter=w3.NoopLogRecordProcessor=w3.LoggerProvider=void 0;var lco=MBr();Object.defineProperty(w3,"LoggerProvider",{enumerable:!0,get:function(){return lco.LoggerProvider}});var uco=gyt();Object.defineProperty(w3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return uco.NoopLogRecordProcessor}});var dco=FBr();Object.defineProperty(w3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return dco.ConsoleLogRecordExporter}});var fco=UBr();Object.defineProperty(w3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return fco.SimpleLogRecordProcessor}});var pco=qBr();Object.defineProperty(w3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return pco.InMemoryLogRecordExporter}});var hco=VBr();Object.defineProperty(w3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return hco.BatchLogRecordProcessor}})});var Ph,WBr,ipe,zBr,ope,spe,YBr,KBr,JBr,XBr,ZBr,eNr,tNr,rNr,nNr,iNr,oNr,sNr,aNr,cNr,lNr,uNr,dNr,fNr,pNr,hNr,mNr,gNr,ANr,yNr,ENr,ape=Z(()=>{"use strict";Ph="iflow-cli",WBr="iflow_cli.user_prompt",ipe="iflow_cli.tool_call",zBr="iflow_cli.api_request",ope="iflow_cli.api_error",spe="iflow_cli.api_response",YBr="iflow_cli.config",KBr="iflow_cli.flash_fallback",JBr="iflow_cli.next_speaker_check",XBr="iflow_cli.slash_command",ZBr="iflow_cli.cli_response",eNr="iflow_cli.tool.call.count",tNr="iflow_cli.tool.call.latency",rNr="iflow_cli.mcp.tool.call.count",nNr="iflow_cli.mcp.tool.call.latency",iNr="iflow_cli.builtin.tool.call.count",oNr="iflow_cli.builtin.tool.call.latency",sNr="gen_ai.client.operation",aNr="gen_ai.client.operation.duration",cNr="gen_ai.client.token.usage",lNr="iflow_cli.session.count",uNr="iflow_cli.file.operation.count",dNr="iflow_cli.user_request.count",fNr="iflow_cli.user_request.latency",pNr="iflow_cli.user_experience.success",hNr="iflow_cli.user.identity",mNr="iflow_cli.scheduler.lock.error",gNr="iflow_cli.mcp.connect.count",ANr="iflow_cli.loop.detection.count",yNr="iflow_cli.paste.operation.count",ENr="iflow_cli.paste.operation.latency"});import mco from"os";function vNr(){try{let t=mco.networkInterfaces();for(let e of Object.keys(t)){let r=t[e];if(r){for(let n of r)if(n.family==="IPv4"&&!n.internal)return n.address}}return"127.0.0.1"}catch{return"127.0.0.1"}}var bNr=Z(()=>{"use strict"});var UK,QK,qK,HK,GK,jK,VK,$K,WK,zK,e5,t5,CNr=Z(()=>{"use strict";UK="iflow_cli.cpu.usage_percentage",QK="iflow_cli.cpu.user_percentage",qK="iflow_cli.cpu.system_percentage",HK="iflow_cli.cpu.cores",GK="iflow_cli.memory.heap_used",jK="iflow_cli.memory.heap_total",VK="iflow_cli.memory.rss",$K="iflow_cli.memory.external",WK="iflow_cli.memory.system_usage_percentage",zK="iflow_cli.memory.process_usage_percentage",e5={[UK]:"CPU usage percentage",[QK]:"CPU user time percentage",[qK]:"CPU system time percentage",[HK]:"Number of CPU cores",[GK]:"Heap memory used in bytes",[jK]:"Heap memory total in bytes",[VK]:"Resident Set Size in bytes",[$K]:"External memory in bytes",[WK]:"System memory usage percentage",[zK]:"Process memory usage percentage relative to Node.js limits"},t5={[UK]:"percent",[QK]:"percent",[qK]:"percent",[HK]:"cores",[GK]:"bytes",[jK]:"bytes",[VK]:"bytes",[$K]:"bytes",[WK]:"percent",[zK]:"percent"}});import*as r5 from"os";var kRe,_Nr=Z(()=>{"use strict";CNr();kRe=class{meter;options;lastCpuMeasurement;lastMeasureTime;cpuCores;totalSystemMemory;nodeJSMemoryLimit;cpuUsageGauge;cpuUserGauge;cpuSystemGauge;cpuCoresGauge;memoryHeapUsedGauge;memoryHeapTotalGauge;memoryRssGauge;memoryExternalGauge;memorySystemUsageGauge;memoryProcessUsageGauge;constructor(e,r={}){this.meter=e,this.options={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...r},this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=Date.now(),this.cpuCores=r5.cpus().length,this.totalSystemMemory=r5.totalmem(),this.nodeJSMemoryLimit=this.getNodeJSMemoryLimit(),this.initializeMetrics()}getCurrentCpuMetrics(){try{let e=process.cpuUsage(this.lastCpuMeasurement),r=Date.now(),n=r-this.lastMeasureTime;if(this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=r,n<=0)return{usage:0,user:0,system:0,cores:this.cpuCores};let i=Math.max(0,e.user+e.system),o=Math.max(0,e.user),s=Math.max(0,e.system),a=i/(n*1e3)*100,c=o/(n*1e3)*100,u=s/(n*1e3)*100,d=Number.isFinite(a)?Math.min(100,Math.max(0,a)):0,f=Number.isFinite(c)?Math.min(100,Math.max(0,c)):0,p=Number.isFinite(u)?Math.min(100,Math.max(0,u)):0;return{usage:d,user:f,system:p,cores:this.cpuCores}}catch{return{usage:0,user:0,system:0,cores:this.cpuCores}}}getCurrentMemoryMetrics(){try{let e=process.memoryUsage(),r=r5.freemem(),i=(this.totalSystemMemory-r)/this.totalSystemMemory*100,o=e.rss/this.nodeJSMemoryLimit*100;return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external,systemUsage:Math.min(100,Math.max(0,i)),processUsage:Math.min(100,Math.max(0,o))}}catch{return{heapUsed:0,heapTotal:0,rss:0,external:0,systemUsage:0,processUsage:0}}}initializeMetrics(){let e=r5.platform(),r=r5.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(UK,{description:e5[UK],unit:t5[UK]}),this.cpuUserGauge=this.meter.createObservableGauge(QK,{description:e5[QK],unit:t5[QK]}),this.cpuSystemGauge=this.meter.createObservableGauge(qK,{description:e5[qK],unit:t5[qK]}),this.cpuCoresGauge=this.meter.createObservableGauge(HK,{description:e5[HK],unit:t5[HK]}),this.cpuUsageGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.usage,{platform:e,arch:r,node_version:n})}),this.cpuUserGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.user,{platform:e,arch:r,node_version:n})}),this.cpuSystemGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.system,{platform:e,arch:r,node_version:n})}),this.cpuCoresGauge?.addCallback(i=>{i.observe(this.cpuCores,{platform:e,arch:r})})),this.options.enableMemoryMetrics&&(this.memoryHeapUsedGauge=this.meter.createObservableGauge(GK,{description:e5[GK],unit:t5[GK]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(jK,{description:e5[jK],unit:t5[jK]}),this.memoryRssGauge=this.meter.createObservableGauge(VK,{description:e5[VK],unit:t5[VK]}),this.memoryExternalGauge=this.meter.createObservableGauge($K,{description:e5[$K],unit:t5[$K]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(WK,{description:e5[WK],unit:t5[WK]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(zK,{description:e5[zK],unit:t5[zK]}),this.memoryHeapUsedGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.heapUsed,{platform:e,arch:r,node_version:n})}),this.memoryHeapTotalGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.heapTotal,{platform:e,arch:r,node_version:n})}),this.memoryRssGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.rss,{platform:e,arch:r,node_version:n})}),this.memoryExternalGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.external,{platform:e,arch:r,node_version:n})}),this.memorySystemUsageGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.systemUsage,{platform:e,arch:r,node_version:n})}),this.memoryProcessUsageGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.processUsage,{platform:e,arch:r,node_version:n,memory_limit_mb:Math.round(this.nodeJSMemoryLimit/(1024*1024)).toString()})}))}getNodeJSMemoryLimit(){let e=process.execArgv.find(i=>i.startsWith("--max-old-space-size="))?.split("=")[1];if(e){let i=parseInt(e,10);if(!isNaN(i)&&i>0)return i*1024*1024}let r=process.execArgv.find(i=>i.startsWith("--max_old_space_size="))?.split("=")[1];if(r){let i=parseInt(r,10);if(!isNaN(i)&&i>0)return i*1024*1024}let n=r5.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function xNr(t,e={}){if(PRe)return PRe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return PRe=new kRe(t,r),PRe}var PRe,SNr=Z(()=>{"use strict";_Nr();PRe=null});import*as YK from"os";import*as MRe from"fs";function Jp(t){let e="0.3.24-beta.0",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},i=YK.platform(),o=n[i]||i,s="unknown";try{if(i==="darwin")s=YK.release();else if(i==="linux")try{if(MRe.existsSync("/etc/os-release")){let h=MRe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);h&&(s=h[1])}}catch{s=YK.release()}else i==="win32"&&(s=YK.release())}catch{s="unknown"}let a={name:"Node.js",version:process.version,architecture:process.arch},c=t.getModel()||"unknown",u=t.getUsageMode(),d=!1,f=t.getContentGeneratorConfig?.();if(f){let p=f.authType,h=f.baseUrl||"";(p===zt.LOGIN_WITH_IFLOW||p===zt.IFLOW||p===zt.OPENAI_COMPATIBLE&&h.includes("apis.iflow.cn"))&&(d=!0)}return{app_name:Ph,tenant__:"gen_ai",version:e,platform:o,os_model:s,runtime_name:a.name,runtime_version:a.version,runtime_architecture:a.architecture,model_name:c,is_iflow_open_user:String(d),ip:vNr(),iflow_env:r,usage_mode:u}}function wNr(){return Syt||(Syt=Hue.getMeter(Ph)),Syt}function TNr(){if(Xg)return;let t=wNr();if(t){try{xNr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}wyt=t.createHistogram(eNr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Tyt=t.createHistogram(tNr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),Iyt=t.createHistogram(rNr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Dyt=t.createHistogram(nNr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),Ryt=t.createHistogram(iNr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Byt=t.createHistogram(oNr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),cpe=t.createHistogram(sNr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:Ll.INT}),lpe=t.createHistogram(aNr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:Ll.INT}),Nyt=t.createHistogram(cNr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:Ll.INT}),Oyt=t.createHistogram(uNr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:Ll.INT}),kyt=t.createHistogram(dNr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:Ll.INT}),Pyt=t.createHistogram(fNr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:Ll.INT}),Myt=t.createHistogram(pNr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:Ll.INT}),Lyt=t.createHistogram(hNr,{description:"User identity for tracking unique installations.",unit:"count",valueType:Ll.INT}),Fyt=t.createHistogram(mNr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:Ll.INT}),Uyt=t.createHistogram(gNr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:Ll.INT}),Qyt=t.createHistogram(ANr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:Ll.INT}),qyt=t.createHistogram(yNr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:Ll.INT}),Hyt=t.createHistogram(ENr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:Ll.INT}),Xg=!0}}function LRe(t){let e=wNr();if(!e||!Xg)return;e.createHistogram(lNr,{description:"Count of CLI sessions started.",unit:"count",valueType:Ll.INT}).record(1,Jp(t))}function INr(t,e,r,n,i,o){if(!wyt||!Tyt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};wyt.record(1,s),Tyt.record(r,{...Jp(t),function_name:e??"unknown",tool_type:o??"unknown"})}function DNr(t,e,r,n,i,o){if(!Iyt||!Dyt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};o&&(s.execution_context=o),Iyt.record(1,s),Dyt.record(r,{...Jp(t),function_name:e??"unknown",execution_context:o??"unknown"})}function RNr(t,e,r,n,i,o){if(!Ryt||!Byt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};o&&(s.execution_context=o),Ryt.record(1,s),Byt.record(r,{...Jp(t),function_name:e??"unknown",execution_context:o??"unknown"})}function KK(t,e,r,n){!Nyt||!Xg||Nyt.record(r,{...Jp(t),model:e??"unknown",type:n??"unknown"})}function BNr(t,e,r,n,i,o,s,a){if(!cpe||!lpe||!Xg)return;let c={...Jp(t),model:e??"unknown",status_code:String(n??(i?"error":"ok"))};s!==void 0&&(c.http_status_code=String(s)),a!==void 0&&(c.business_code=String(a)),o&&(c.finish_reason=o),cpe.record(1,c);let u={...Jp(t),model:e??"unknown",http_status_code:String(s??200),finish_reason:o??"unknown"};a!=null&&(u.business_code=String(a)),lpe.record(r,u)}function NNr(t,e,r,n,i,o,s){if(!cpe||!lpe||!Xg)return;let a={...Jp(t),model:e??"unknown",status_code:String(n??"error"),error:i??"unknown"};o!==void 0&&(a.http_status_code=String(o)),s!==void 0&&(a.business_code=String(s)),cpe.record(1,a);let c={...Jp(t),model:e??"unknown",http_status_code:String(o??0),error:i??"unknown"};s!=null&&(c.business_code=String(s)),lpe.record(r,c)}function MF(t,e,r,n,i){if(!Oyt||!Xg)return;let o={...Jp(t),operation:e};r!==void 0&&(o.lines=String(r)),n!==void 0&&(o.mimetype=n),i!==void 0&&(o.extension=i),Oyt.record(1,o)}function ONr(t,e,r,n,i){if(!kyt||!Pyt||!Xg)return;let o={...Jp(t),prompt_id:e,success:String(n)};i&&(o.error=i),kyt.record(1,o),Pyt.record(r,o)}function Gyt(t,e,r=!1,n=!1,i){if(!Myt||!Xg)return;let o={...Jp(t),success:String(e),had_retries:String(r),had_fixes:String(n)};i&&(o.final_error=i),Myt.record(1,o)}function kNr(t,e){if(!Lyt||!Xg)return;let r={...Jp(t),user_id:e};Lyt.record(1,r)}function PNr(t,e,r){if(!Fyt||!Xg)return;let n={...Jp(t),running_calls_count:String(e)};r.forEach((i,o)=>{n[`call_${o}_name`]=i.name,n[`call_${o}_status`]=i.status}),Fyt.record(1,n)}function jyt(t,e,r,n,i){if(!Uyt||!Xg)return;let o={...Jp(t),server_name:e,success:String(r)};n&&(o.error_type=n),i&&(o.transport_type=i),Uyt.record(1,o)}function MNr(t,e,r){if(!Qyt||!Xg)return;let n={...Jp(t),loop_type:e,prompt_id:r};Qyt.record(1,n)}function FRe(t,e,r,n,i="text",o,s){if(!qyt||!Hyt||!Xg)return;let a={};try{a=Jp(t)}catch{a={app_name:Ph,tenant__:"gen_ai",version:"unknown",platform:s||"unknown",os_model:"unknown",runtime_name:"Node.js",runtime_version:process.version,runtime_architecture:process.arch,model_name:"unknown",is_iflow_open_user:"false",ip:"unknown",iflow_env:"test",usage_mode:"unknown"}}let c={...a,success:String(n),paste_type:i};o&&(c.error_type=o),s&&(c.platform_specific=s),qyt.record(1,c);let u={...a,paste_type:i,text_length_range:String(r),performance_ratio:gco(e,r)};Hyt.record(e,u)}function gco(t,e){if(e===0)return"no-text";let r=t/e;return r<=.1?"excellent":r<=.5?"good":r<=1?"normal":r<=2?"slow":"very-slow"}var mT,Syt,wyt,Tyt,Iyt,Dyt,Ryt,Byt,cpe,lpe,Nyt,Oyt,kyt,Pyt,Myt,Lyt,Fyt,Uyt,Qyt,qyt,Hyt,Xg,Wv=Z(()=>{"use strict";Kt();bNr();ape();iE();SNr();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(mT||(mT={}));Xg=!1});var Io,yn,Do,Ro,Id=Z(()=>{"use strict";Io=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(yn||(yn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(Do||(Do={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(Ro||(Ro={}))});function Aco(t){switch(t){case yn.ProceedOnce:case yn.ProceedAlways:case yn.ProceedAlwaysServer:case yn.ProceedAlwaysTool:return zv.ACCEPT;case yn.ModifyWithEditor:return zv.MODIFY;case yn.Cancel:default:return zv.REJECT}}var zv,JK,XK,ZK,eJ,tJ,b2,rJ,nJ,Yv,iJ,URe,oJ,QRe,hB=Z(()=>{"use strict";Id();iE();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(zv||(zv={}));JK=class{"event.name";"event.timestamp";model;embedding_model;sandbox_enabled;core_tools_enabled;approval_mode;api_key_enabled;vertex_ai_enabled;debug_enabled;mcp_servers;telemetry_enabled;telemetry_log_user_prompts_enabled;file_filtering_respect_git_ignore;constructor(e){let r=e.getContentGeneratorConfig(),n=e.getMcpServers(),i=!1,o=!1;r&&r.authType&&(i=r.authType===zt.IFLOW,o=r.authType===zt.AONE),this["event.name"]="cli_config",this.model=e.getModel(),this.embedding_model=e.getEmbeddingModel(),this.sandbox_enabled=typeof e.getSandbox()=="string"||!!e.getSandbox(),this.core_tools_enabled=(e.getCoreTools()??[]).join(","),this.approval_mode=e.getApprovalMode(),this.api_key_enabled=i||o,this.vertex_ai_enabled=o,this.debug_enabled=e.getDebugMode(),this.mcp_servers=n?Object.keys(n).join(","):"",this.telemetry_enabled=e.getTelemetryEnabled(),this.telemetry_log_user_prompts_enabled=e.getTelemetryLogPromptsEnabled(),this.file_filtering_respect_git_ignore=e.getFileFilteringRespectGitIgnore()}},XK=class{"event.name";"event.timestamp";session_id;constructor(e){this["event.name"]="end_session",this["event.timestamp"]=new Date().toISOString(),this.session_id=e?.getSessionId()}},ZK=class{"event.name";"event.timestamp";prompt_length;prompt_id;auth_type;prompt;constructor(e,r,n,i){this["event.name"]="user_prompt",this["event.timestamp"]=new Date().toISOString(),this.prompt_length=e,this.prompt_id=r,this.auth_type=n,this.prompt=i}},eJ=class{"event.name";"event.timestamp";function_name;function_args;duration_ms;success;decision;error;error_type;prompt_id;server_name;response_text;constructor(e){this["event.name"]="tool_call",this["event.timestamp"]=new Date().toISOString(),this.function_name=e.request.name,this.function_args=JSON.stringify(e.request.args),this.duration_ms=e.durationMs??0,this.success=e.status==="success",this.decision=e.outcome?Aco(e.outcome):void 0,this.error=e.response.error?.message,this.error_type=e.response.errorType,this.prompt_id=e.request.prompt_id,this.response_text=JSON.stringify(e.response,null,2),"tool"in e&&e.tool&&"serverName"in e.tool&&(this.server_name=e.tool.serverName)}},tJ=class{"event.name";"event.timestamp";model;prompt_id;request_text;base_url;openai_request;constructor(e,r,n,i,o){this["event.name"]="api_request",this["event.timestamp"]=new Date().toISOString(),this.model=r,this.prompt_id=i,this.request_text=o,this.base_url=e,this.openai_request=n}},b2=class{"event.name";"event.timestamp";model;error;error_type;status_code;http_status_code;business_code;duration_ms;prompt_id;auth_type;constructor(e,r,n,i,o,s,a,c,u){this["event.name"]="api_error",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.error=r,this.error_type=s,this.status_code=a,this.http_status_code=c,this.business_code=u,this.duration_ms=n,this.prompt_id=i,this.auth_type=o}},rJ=class{"event.name";"event.timestamp";model;status_code;http_status_code;business_code;duration_ms;error;input_token_count;output_token_count;cached_content_token_count;thoughts_token_count;tool_token_count;total_token_count;response_text;prompt_id;auth_type;finish_reason;constructor(e,r,n,i,o,s,a,c,u,d){this["event.name"]="api_response",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.duration_ms=r,this.status_code=200,this.http_status_code=u||200,this.business_code=d,this.input_token_count=o?.promptTokenCount??0,this.output_token_count=o?.candidatesTokenCount??0,this.cached_content_token_count=o?.cachedContentTokenCount??0,this.thoughts_token_count=o?.thoughtsTokenCount??0,this.tool_token_count=o?.toolUsePromptTokenCount??0,this.total_token_count=o?.totalTokenCount??0,this.response_text=s,this.error=a,this.prompt_id=n,this.auth_type=i,this.finish_reason=c}},nJ=class{"event.name";"event.timestamp";auth_type;constructor(e){this["event.name"]="flash_fallback",this["event.timestamp"]=new Date().toISOString(),this.auth_type=e}};(function(t){t.CONSECUTIVE_IDENTICAL_TOOL_CALLS="consecutive_identical_tool_calls",t.CHANTING_IDENTICAL_SENTENCES="chanting_identical_sentences",t.LLM_DETECTED_LOOP="llm_detected_loop"})(Yv||(Yv={}));iJ=class{"event.name";"event.timestamp";loop_type;prompt_id;constructor(e,r){this["event.name"]="loop_detected",this["event.timestamp"]=new Date().toISOString(),this.loop_type=e,this.prompt_id=r}},URe=class{"event.name";"event.timestamp";prompt_id;finish_reason;result;constructor(e,r,n){this["event.name"]="next_speaker_check",this["event.timestamp"]=new Date().toISOString(),this.prompt_id=e,this.finish_reason=r,this.result=n}},oJ=class{"event.name";"event.timestamp";command;subcommand;constructor(e,r){this["event.name"]="slash_command",this["event.timestamp"]=new Date().toISOString(),this.command=e,this.subcommand=r}},QRe=class{"event.name";"event.timestamp";model;constructor(e){this["event.name"]="malformed_json_response",this["event.timestamp"]=new Date().toISOString(),this.model=e}}});var Yn,LNr=Z(()=>{"use strict";(function(t){t[t.IFLOW_CLI_KEY_UNKNOWN=0]="IFLOW_CLI_KEY_UNKNOWN",t[t.IFLOW_CLI_START_SESSION_MODEL=1]="IFLOW_CLI_START_SESSION_MODEL",t[t.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL=2]="IFLOW_CLI_START_SESSION_EMBEDDING_MODEL",t[t.IFLOW_CLI_START_SESSION_SANDBOX=3]="IFLOW_CLI_START_SESSION_SANDBOX",t[t.IFLOW_CLI_START_SESSION_CORE_TOOLS=4]="IFLOW_CLI_START_SESSION_CORE_TOOLS",t[t.IFLOW_CLI_START_SESSION_APPROVAL_MODE=5]="IFLOW_CLI_START_SESSION_APPROVAL_MODE",t[t.IFLOW_CLI_START_SESSION_API_KEY_ENABLED=6]="IFLOW_CLI_START_SESSION_API_KEY_ENABLED",t[t.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED=7]="IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.IFLOW_CLI_START_SESSION_MCP_SERVERS=9]="IFLOW_CLI_START_SESSION_MCP_SERVERS",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED=10]="IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE=12]="IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.IFLOW_CLI_USER_PROMPT_LENGTH=13]="IFLOW_CLI_USER_PROMPT_LENGTH",t[t.IFLOW_CLI_TOOL_CALL_NAME=14]="IFLOW_CLI_TOOL_CALL_NAME",t[t.IFLOW_CLI_TOOL_CALL_DECISION=15]="IFLOW_CLI_TOOL_CALL_DECISION",t[t.IFLOW_CLI_TOOL_CALL_SUCCESS=16]="IFLOW_CLI_TOOL_CALL_SUCCESS",t[t.IFLOW_CLI_TOOL_CALL_DURATION_MS=17]="IFLOW_CLI_TOOL_CALL_DURATION_MS",t[t.IFLOW_CLI_TOOL_ERROR_MESSAGE=18]="IFLOW_CLI_TOOL_ERROR_MESSAGE",t[t.IFLOW_CLI_TOOL_CALL_ERROR_TYPE=19]="IFLOW_CLI_TOOL_CALL_ERROR_TYPE",t[t.IFLOW_CLI_API_REQUEST_MODEL=20]="IFLOW_CLI_API_REQUEST_MODEL",t[t.IFLOW_CLI_API_RESPONSE_MODEL=21]="IFLOW_CLI_API_RESPONSE_MODEL",t[t.IFLOW_CLI_API_RESPONSE_STATUS_CODE=22]="IFLOW_CLI_API_RESPONSE_STATUS_CODE",t[t.IFLOW_CLI_API_RESPONSE_DURATION_MS=23]="IFLOW_CLI_API_RESPONSE_DURATION_MS",t[t.IFLOW_CLI_API_ERROR_MESSAGE=24]="IFLOW_CLI_API_ERROR_MESSAGE",t[t.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.IFLOW_CLI_API_ERROR_MODEL=30]="IFLOW_CLI_API_ERROR_MODEL",t[t.IFLOW_CLI_API_ERROR_TYPE=31]="IFLOW_CLI_API_ERROR_TYPE",t[t.IFLOW_CLI_API_ERROR_STATUS_CODE=32]="IFLOW_CLI_API_ERROR_STATUS_CODE",t[t.IFLOW_CLI_API_ERROR_DURATION_MS=33]="IFLOW_CLI_API_ERROR_DURATION_MS",t[t.IFLOW_CLI_END_SESSION_ID=34]="IFLOW_CLI_END_SESSION_ID",t[t.IFLOW_CLI_PROMPT_ID=35]="IFLOW_CLI_PROMPT_ID",t[t.IFLOW_CLI_AUTH_TYPE=36]="IFLOW_CLI_AUTH_TYPE",t[t.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT=37]="IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.IFLOW_CLI_SURFACE=39]="IFLOW_CLI_SURFACE",t[t.IFLOW_CLI_SESSION_ID=40]="IFLOW_CLI_SESSION_ID",t[t.IFLOW_CLI_LOOP_DETECTED_TYPE=38]="IFLOW_CLI_LOOP_DETECTED_TYPE",t[t.IFLOW_CLI_SLASH_COMMAND_NAME=41]="IFLOW_CLI_SLASH_COMMAND_NAME",t[t.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND=42]="IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.IFLOW_CLI_RESPONSE_FINISH_REASON=43]="IFLOW_CLI_RESPONSE_FINISH_REASON",t[t.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.IFLOW_CLI_RESPONSE_TYPE=46]="IFLOW_CLI_RESPONSE_TYPE",t[t.IFLOW_CLI_RESPONSE_LENGTH=47]="IFLOW_CLI_RESPONSE_LENGTH",t[t.IFLOW_CLI_RESPONSE_SUCCESS=48]="IFLOW_CLI_RESPONSE_SUCCESS",t[t.IFLOW_CLI_ERROR_MESSAGE=49]="IFLOW_CLI_ERROR_MESSAGE"})(Yn||(Yn={}))});function LF(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var qRe=Z(()=>{"use strict";});import AS,{dirname as yco,join as Vyt}from"node:path";import HRe from"os";import*as FNr from"crypto";import{fileURLToPath as Eco}from"node:url";import vco from"node:fs";import{execSync as bco}from"node:child_process";function yS(t){let e=HRe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function gc(t,e=35){if(t.length<=e)return t;let n=AS.parse(t).root,i=AS.sep,s=t.substring(n.length).split(i).filter(h=>h!=="");if(s.length<=1){let h=Math.floor((e-3)/2);if(h<=0)return t.substring(0,e-3)+"...";let m=t.substring(0,h),g=t.substring(t.length-h);return`${m}...${g}`}let a=s[0],c=s[s.length-1],u=n+a,d=[],f=i.length+c.length;for(let h=s.length-2;h>=0;h--){let m=s[h],g=f+i.length+m.length;if(g<=e)d.unshift(m),f=g;else break}let p=d.join(i)+i+c;return f>e?p:(p=u+i+p,p.length>e?"..."+p.substring(p.length-e-3):p)}function Dd(t,e){let r=AS.resolve(t),n=AS.resolve(e);return AS.relative(n,r)||"."}function sJ(t){let e="";for(let r=0;r<t.length;r++)t[r]===" "&&(r===0||t[r-1]!=="\\")?e+="\\ ":e+=t[r];return e}function gT(t){return t.replace(/\\(.)/g,"$1")}function GRe(t){return FNr.createHash("sha256").update(t).digest("hex")}function V1(t){let e=GRe(t);return AS.join(HRe.homedir(),Qm,Cco,e)}function jRe(){return AS.join(HRe.homedir(),Qm,UNr)}function VRe(t){return AS.join(t,Qm,UNr)}function $Re(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=yco(Eco(import.meta.url)),e=[Vyt(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),Vyt(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),Vyt(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(vco.existsSync(r))return process.platform==="darwin"&&QNr(r),r}catch{}return e[0]}function QNr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{bco(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function upe(t,e){let n=HRe.platform()==="win32"?AS.win32:AS,i=n.relative(t,e);return!i.startsWith(`..${n.sep}`)&&i!==".."&&!n.isAbsolute(i)}var Qm,$yt,Cco,UNr,Rd=Z(()=>{"use strict";Qm=".iflow",$yt="google_accounts.json",Cco="tmp",UNr="commands"});import _co from"node:path";import{promises as sMa,existsSync as qNr,readFileSync as HNr}from"node:fs";import*as GNr from"os";function jNr(){return _co.join(GNr.homedir(),Qm,$yt)}function VNr(){try{let t=jNr();if(qNr(t)){let e=HNr(t,"utf-8").trim();return e?JSON.parse(e).active:null}return null}catch(t){return console.debug("Error reading cached Google Account:",t),null}}function $Nr(){try{let t=jNr();if(!qNr(t))return 0;let e=HNr(t,"utf-8").trim();if(!e)return 0;let r=JSON.parse(e),n=r.old.length;return r.active&&n++,n}catch(t){return console.debug("Error reading lifetime Google Accounts:",t),0}}var WNr=Z(()=>{"use strict";Rd();});import*as zNr from"os";import*as AT from"fs";import*as Yyt from"path";import{randomUUID as xco}from"crypto";function wco(){AT.existsSync(Wyt)||AT.mkdirSync(Wyt,{recursive:!0})}function Tco(){return AT.existsSync(zyt)&&AT.readFileSync(zyt,"utf-8").trim()||null}function Ico(t){AT.writeFileSync(zyt,t,"utf-8")}function WRe(){try{wco();let t=Tco();return t||(t=xco(),Ico(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var Sco,Wyt,zyt,Kyt=Z(()=>{"use strict";Rd();Sco=zNr.homedir()??"",Wyt=Yyt.join(Sco,Qm),zyt=Yyt.join(Wyt,"installation_id")});var YNr,Dco,Rco,Bco,Nco,Oco,kco,Pco,Mco,Lco,Fco,Uco,Qco,qco,Mh,dpe=Z(()=>{"use strict";YNr=Te(qct(),1);hB();LNr();qRe();WNr();Kyt();Dco="start_session",Rco="new_prompt",Bco="tool_call",Nco="api_request",Oco="api_response",kco="api_error",Pco="end_session",Mco="flash_fallback",Lco="loop_detected",Fco="next_speaker_check",Uco="slash_command",Qco="malformed_json_response",qco="cli_response",Mh=class t{static instance;config;events=[];last_flush_time=Date.now();flush_interval_ms=1e3*60;constructor(e){this.config=e}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}enqueueLogEvent(e){this.events.push([{event_time_ms:Date.now(),source_extension_json:LF(e)}])}createLogEvent(e,r){let n=VNr(),i=$Nr();r.push({iflow_cli_key:Yn.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT,value:i.toString()});let o={console_type:"IFLOW_CLI",application:102,event_name:e,event_metadata:[r]};return n?o.client_email=n:o.client_install_id=WRe(),o}flushIfNeeded(){Date.now()-this.last_flush_time<this.flush_interval_ms||this.flushToClearcut().catch(e=>{console.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){return this.config?.getDebugMode()&&console.log("Telemetry disabled - not sending log events to Clearcut."),this.events.length=0,this.last_flush_time=Date.now(),Promise.resolve({})}decodeLogResponse(e){if(e.length<1||e.readUInt8(0)!==8)return;let r=BigInt(0),n=!0;for(let o=1;n&&o<e.length;o++){let s=e.readUInt8(o);r|=BigInt(s&127)<<BigInt(7*(o-1)),n=(s&128)!==0}return n?void 0:{nextRequestWaitMs:Number(r)}}handleLogEvent(e,r,n=!1){this.enqueueLogEvent(this.createLogEvent(e,r)),n?this.flushToClearcut().catch(i=>{console.debug("Error flushing to Clearcut:",i)}):this.flushIfNeeded()}logStartSessionEvent(e){let r=process.env.SURFACE||"SURFACE_NOT_SET",n=[{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_MODEL,value:e.model},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_SURFACE,value:r}];this.handleLogEvent(Dco,n,!0)}logNewPromptEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Rco,r)}logToolCallEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)}];this.handleLogEvent(Bco,r)}logApiRequestEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)}];this.handleLogEvent(Nco,r)}logApiResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.input_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.output_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.cached_content_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.thoughts_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.tool_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Oco,r)}logApiErrorEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(kco,r)}logFlashFallbackEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Mco,r,!0)}logLoopDetectedEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];this.handleLogEvent(Lco,r)}logNextSpeakerCheck(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{iflow_cli_key:Yn.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Fco,r)}logSlashCommandEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({iflow_cli_key:Yn.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),this.handleLogEvent(Uco,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(Qco,r)}logCliResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_TYPE,value:JSON.stringify(e.response_type)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_LENGTH,value:JSON.stringify(e.response_length)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Yn.IFLOW_CLI_ERROR_MESSAGE,value:JSON.stringify(e.error)}];this.handleLogEvent(qco,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Pco,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new YNr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new XK(this.config);this.logEndSessionEvent(e)}}});import*as KNr from"node:fs";var FF,JNr,fpe,zRe,YRe,KRe,XNr=Z(()=>{"use strict";FF=Te(si(),1),JNr=Te(Bx(),1);fpe=class{writeStream;constructor(e){this.writeStream=KNr.createWriteStream(e,{flags:"a"})}serialize(e){let r=new WeakSet;return JSON.stringify(e,(i,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular]";r.add(o)}return o},2)+`
|
|
485
|
+
`).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){Eoo.diag.debug(`error reading machine id: ${t}`)}}SDe.getMachineId=voo});var KDr=w(wDe=>{"use strict";Object.defineProperty(wDe,"__esModule",{value:!0});wDe.getMachineId=void 0;var boo=Ae("fs"),Coo=(Kt(),yt(ar));async function _oo(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await boo.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){Coo.diag.debug(`error reading machine id: ${r}`)}}wDe.getMachineId=_oo});var XDr=w(TDe=>{"use strict";Object.defineProperty(TDe,"__esModule",{value:!0});TDe.getMachineId=void 0;var xoo=Ae("fs"),Soo=xDe(),JDr=(Kt(),yt(ar));async function woo(){try{return(await xoo.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){JDr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,Soo.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){JDr.diag.debug(`error reading machine id: ${t}`)}}TDe.getMachineId=woo});var eRr=w(IDe=>{"use strict";Object.defineProperty(IDe,"__esModule",{value:!0});IDe.getMachineId=void 0;var ZDr=Ae("process"),Too=xDe(),Ioo=(Kt(),yt(ar));async function Doo(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";ZDr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in ZDr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,Too.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){Ioo.diag.debug(`error reading machine id: ${r}`)}}IDe.getMachineId=Doo});var tRr=w(DDe=>{"use strict";Object.defineProperty(DDe,"__esModule",{value:!0});DDe.getMachineId=void 0;var Roo=(Kt(),yt(ar));async function Boo(){Roo.diag.debug("could not read machine-id: unsupported platform")}DDe.getMachineId=Boo});var rRr=w(RDe=>{"use strict";Object.defineProperty(RDe,"__esModule",{value:!0});RDe.getMachineId=void 0;var Noo=Ae("process"),IF;async function Ooo(){if(!IF)switch(Noo.platform){case"darwin":IF=(await Promise.resolve().then(()=>Te(YDr()))).getMachineId;break;case"linux":IF=(await Promise.resolve().then(()=>Te(KDr()))).getMachineId;break;case"freebsd":IF=(await Promise.resolve().then(()=>Te(XDr()))).getMachineId;break;case"win32":IF=(await Promise.resolve().then(()=>Te(eRr()))).getMachineId;break;default:IF=(await Promise.resolve().then(()=>Te(tRr()))).getMachineId;break}return IF()}RDe.getMachineId=Ooo});var N3t=w(IK=>{"use strict";Object.defineProperty(IK,"__esModule",{value:!0});IK.normalizeType=IK.normalizeArch=void 0;var koo=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};IK.normalizeArch=koo;var Poo=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};IK.normalizeType=Poo});var iRr=w(BDe=>{"use strict";Object.defineProperty(BDe,"__esModule",{value:!0});BDe.hostDetector=void 0;var O3t=Jfe(),nRr=Ae("os"),Moo=rRr(),Loo=N3t(),k3t=class{detect(e){return{attributes:{[O3t.ATTR_HOST_NAME]:(0,nRr.hostname)(),[O3t.ATTR_HOST_ARCH]:(0,Loo.normalizeArch)((0,nRr.arch)()),[O3t.ATTR_HOST_ID]:(0,Moo.getMachineId)()}}}};BDe.hostDetector=new k3t});var aRr=w(NDe=>{"use strict";Object.defineProperty(NDe,"__esModule",{value:!0});NDe.osDetector=void 0;var oRr=Jfe(),sRr=Ae("os"),Foo=N3t(),P3t=class{detect(e){return{attributes:{[oRr.ATTR_OS_TYPE]:(0,Foo.normalizeType)((0,sRr.platform)()),[oRr.ATTR_OS_VERSION]:(0,sRr.release)()}}}};NDe.osDetector=new P3t});var cRr=w(ODe=>{"use strict";Object.defineProperty(ODe,"__esModule",{value:!0});ODe.processDetector=void 0;var Uoo=(Kt(),yt(ar)),fT=Jfe(),Qoo=Ae("os"),M3t=class{detect(e){let r={[fT.ATTR_PROCESS_PID]:process.pid,[fT.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[fT.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[fT.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[fT.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[fT.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[fT.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[fT.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=Qoo.userInfo();r[fT.ATTR_PROCESS_OWNER]=n.username}catch(n){Uoo.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};ODe.processDetector=new M3t});var lRr=w(kDe=>{"use strict";Object.defineProperty(kDe,"__esModule",{value:!0});kDe.serviceInstanceIdDetector=void 0;var qoo=Jfe(),Hoo=Ae("crypto"),L3t=class{detect(e){return{attributes:{[qoo.ATTR_SERVICE_INSTANCE_ID]:(0,Hoo.randomUUID)()}}}};kDe.serviceInstanceIdDetector=new L3t});var uRr=w(fS=>{"use strict";Object.defineProperty(fS,"__esModule",{value:!0});fS.serviceInstanceIdDetector=fS.processDetector=fS.osDetector=fS.hostDetector=void 0;var Goo=iRr();Object.defineProperty(fS,"hostDetector",{enumerable:!0,get:function(){return Goo.hostDetector}});var joo=aRr();Object.defineProperty(fS,"osDetector",{enumerable:!0,get:function(){return joo.osDetector}});var Voo=cRr();Object.defineProperty(fS,"processDetector",{enumerable:!0,get:function(){return Voo.processDetector}});var $oo=lRr();Object.defineProperty(fS,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return $oo.serviceInstanceIdDetector}})});var dRr=w(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.serviceInstanceIdDetector=pS.processDetector=pS.osDetector=pS.hostDetector=void 0;var PDe=uRr();Object.defineProperty(pS,"hostDetector",{enumerable:!0,get:function(){return PDe.hostDetector}});Object.defineProperty(pS,"osDetector",{enumerable:!0,get:function(){return PDe.osDetector}});Object.defineProperty(pS,"processDetector",{enumerable:!0,get:function(){return PDe.processDetector}});Object.defineProperty(pS,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return PDe.serviceInstanceIdDetector}})});var fRr=w(DK=>{"use strict";Object.defineProperty(DK,"__esModule",{value:!0});DK.noopDetector=DK.NoopDetector=void 0;var MDe=class{detect(){return{attributes:{}}}};DK.NoopDetector=MDe;DK.noopDetector=new MDe});var pRr=w(S3=>{"use strict";Object.defineProperty(S3,"__esModule",{value:!0});S3.noopDetector=S3.serviceInstanceIdDetector=S3.processDetector=S3.osDetector=S3.hostDetector=S3.envDetector=void 0;var Woo=zDr();Object.defineProperty(S3,"envDetector",{enumerable:!0,get:function(){return Woo.envDetector}});var LDe=dRr();Object.defineProperty(S3,"hostDetector",{enumerable:!0,get:function(){return LDe.hostDetector}});Object.defineProperty(S3,"osDetector",{enumerable:!0,get:function(){return LDe.osDetector}});Object.defineProperty(S3,"processDetector",{enumerable:!0,get:function(){return LDe.processDetector}});Object.defineProperty(S3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return LDe.serviceInstanceIdDetector}});var zoo=fRr();Object.defineProperty(S3,"noopDetector",{enumerable:!0,get:function(){return zoo.noopDetector}})});var U3t=w(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});If.defaultServiceName=If.emptyResource=If.defaultResource=If.resourceFromAttributes=If.serviceInstanceIdDetector=If.processDetector=If.osDetector=If.hostDetector=If.envDetector=If.detectResources=void 0;var Yoo=$Dr();Object.defineProperty(If,"detectResources",{enumerable:!0,get:function(){return Yoo.detectResources}});var Xfe=pRr();Object.defineProperty(If,"envDetector",{enumerable:!0,get:function(){return Xfe.envDetector}});Object.defineProperty(If,"hostDetector",{enumerable:!0,get:function(){return Xfe.hostDetector}});Object.defineProperty(If,"osDetector",{enumerable:!0,get:function(){return Xfe.osDetector}});Object.defineProperty(If,"processDetector",{enumerable:!0,get:function(){return Xfe.processDetector}});Object.defineProperty(If,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Xfe.serviceInstanceIdDetector}});var F3t=D3t();Object.defineProperty(If,"resourceFromAttributes",{enumerable:!0,get:function(){return F3t.resourceFromAttributes}});Object.defineProperty(If,"defaultResource",{enumerable:!0,get:function(){return F3t.defaultResource}});Object.defineProperty(If,"emptyResource",{enumerable:!0,get:function(){return F3t.emptyResource}});var Koo=w3t();Object.defineProperty(If,"defaultServiceName",{enumerable:!0,get:function(){return Koo.defaultServiceName}})});var hRr=w(Zfe=>{"use strict";Object.defineProperty(Zfe,"__esModule",{value:!0});Zfe.SeverityNumber=void 0;var Joo;(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"})(Joo=Zfe.SeverityNumber||(Zfe.SeverityNumber={}))});var UDe=w(RK=>{"use strict";Object.defineProperty(RK,"__esModule",{value:!0});RK.NOOP_LOGGER=RK.NoopLogger=void 0;var FDe=class{emit(e){}};RK.NoopLogger=FDe;RK.NOOP_LOGGER=new FDe});var qDe=w(BK=>{"use strict";Object.defineProperty(BK,"__esModule",{value:!0});BK.NOOP_LOGGER_PROVIDER=BK.NoopLoggerProvider=void 0;var Xoo=UDe(),QDe=class{getLogger(e,r,n){return new Xoo.NoopLogger}};BK.NoopLoggerProvider=QDe;BK.NOOP_LOGGER_PROVIDER=new QDe});var q3t=w(HDe=>{"use strict";Object.defineProperty(HDe,"__esModule",{value:!0});HDe.ProxyLogger=void 0;var Zoo=UDe(),Q3t=class{constructor(e,r,n,i){this._provider=e,this.name=r,this.version=n,this.options=i}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):Zoo.NOOP_LOGGER}};HDe.ProxyLogger=Q3t});var G3t=w(GDe=>{"use strict";Object.defineProperty(GDe,"__esModule",{value:!0});GDe.ProxyLoggerProvider=void 0;var eso=qDe(),tso=q3t(),H3t=class{getLogger(e,r,n){var i;return(i=this._getDelegateLogger(e,r,n))!==null&&i!==void 0?i:new tso.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:eso.NOOP_LOGGER_PROVIDER}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,r,n){var i;return(i=this._delegate)===null||i===void 0?void 0:i.getLogger(e,r,n)}};GDe.ProxyLoggerProvider=H3t});var mRr=w(jDe=>{"use strict";Object.defineProperty(jDe,"__esModule",{value:!0});jDe._globalThis=void 0;jDe._globalThis=typeof globalThis=="object"?globalThis:global});var gRr=w(VDe=>{"use strict";Object.defineProperty(VDe,"__esModule",{value:!0});VDe._globalThis=void 0;var rso=mRr();Object.defineProperty(VDe,"_globalThis",{enumerable:!0,get:function(){return rso._globalThis}})});var ARr=w($De=>{"use strict";Object.defineProperty($De,"__esModule",{value:!0});$De._globalThis=void 0;var nso=gRr();Object.defineProperty($De,"_globalThis",{enumerable:!0,get:function(){return nso._globalThis}})});var yRr=w(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});hS.API_BACKWARDS_COMPATIBILITY_VERSION=hS.makeGetter=hS._global=hS.GLOBAL_LOGS_API_KEY=void 0;var iso=ARr();hS.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");hS._global=iso._globalThis;function oso(t,e,r){return n=>n===t?e:r}hS.makeGetter=oso;hS.API_BACKWARDS_COMPATIBILITY_VERSION=1});var vRr=w(WDe=>{"use strict";Object.defineProperty(WDe,"__esModule",{value:!0});WDe.LogsAPI=void 0;var jv=yRr(),sso=qDe(),ERr=G3t(),j3t=class t{constructor(){this._proxyLoggerProvider=new ERr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return jv._global[jv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(jv._global[jv.GLOBAL_LOGS_API_KEY]=(0,jv.makeGetter)(jv.API_BACKWARDS_COMPATIBILITY_VERSION,e,sso.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=jv._global[jv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(jv._global,jv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete jv._global[jv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new ERr.ProxyLoggerProvider}};WDe.LogsAPI=j3t});var _Rr=w(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});Um.logs=Um.ProxyLoggerProvider=Um.ProxyLogger=Um.NoopLoggerProvider=Um.NOOP_LOGGER_PROVIDER=Um.NoopLogger=Um.NOOP_LOGGER=Um.SeverityNumber=void 0;var aso=hRr();Object.defineProperty(Um,"SeverityNumber",{enumerable:!0,get:function(){return aso.SeverityNumber}});var bRr=UDe();Object.defineProperty(Um,"NOOP_LOGGER",{enumerable:!0,get:function(){return bRr.NOOP_LOGGER}});Object.defineProperty(Um,"NoopLogger",{enumerable:!0,get:function(){return bRr.NoopLogger}});var CRr=qDe();Object.defineProperty(Um,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return CRr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(Um,"NoopLoggerProvider",{enumerable:!0,get:function(){return CRr.NoopLoggerProvider}});var cso=q3t();Object.defineProperty(Um,"ProxyLogger",{enumerable:!0,get:function(){return cso.ProxyLogger}});var lso=G3t();Object.defineProperty(Um,"ProxyLoggerProvider",{enumerable:!0,get:function(){return lso.ProxyLoggerProvider}});var uso=vRr();Um.logs=uso.LogsAPI.getInstance()});var epe=w(fB=>{"use strict";Object.defineProperty(fB,"__esModule",{value:!0});fB.isTracingSuppressed=fB.unsuppressTracing=fB.suppressTracing=void 0;var dso=(Kt(),yt(ar)),V3t=(0,dso.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function fso(t){return t.setValue(V3t,!0)}fB.suppressTracing=fso;function pso(t){return t.deleteValue(V3t)}fB.unsuppressTracing=pso;function hso(t){return t.getValue(V3t)===!0}fB.isTracingSuppressed=hso});var $3t=w(A2=>{"use strict";Object.defineProperty(A2,"__esModule",{value:!0});A2.BAGGAGE_MAX_TOTAL_LENGTH=A2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=A2.BAGGAGE_MAX_NAME_VALUE_PAIRS=A2.BAGGAGE_HEADER=A2.BAGGAGE_ITEMS_SEPARATOR=A2.BAGGAGE_PROPERTIES_SEPARATOR=A2.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;A2.BAGGAGE_KEY_PAIR_SEPARATOR="=";A2.BAGGAGE_PROPERTIES_SEPARATOR=";";A2.BAGGAGE_ITEMS_SEPARATOR=",";A2.BAGGAGE_HEADER="baggage";A2.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;A2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;A2.BAGGAGE_MAX_TOTAL_LENGTH=8192});var W3t=w(mS=>{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});mS.parseKeyPairsIntoRecord=mS.parsePairKeyValue=mS.getKeyPairs=mS.serializeKeyPairs=void 0;var mso=(Kt(),yt(ar)),DF=$3t();function gso(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?DF.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>DF.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}mS.serializeKeyPairs=gso;function Aso(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=DF.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}mS.getKeyPairs=Aso;function xRr(t){let e=t.split(DF.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(DF.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim()),s;return e.length>0&&(s=(0,mso.baggageEntryMetadataFromString)(e.join(DF.BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}mS.parsePairKeyValue=xRr;function yso(t){let e={};return typeof t=="string"&&t.length>0&&t.split(DF.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=xRr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}mS.parseKeyPairsIntoRecord=yso});var SRr=w(zDe=>{"use strict";Object.defineProperty(zDe,"__esModule",{value:!0});zDe.W3CBaggagePropagator=void 0;var z3t=(Kt(),yt(ar)),Eso=epe(),RF=$3t(),Y3t=W3t(),K3t=class{inject(e,r,n){let i=z3t.propagation.getBaggage(e);if(!i||(0,Eso.isTracingSuppressed)(e))return;let o=(0,Y3t.getKeyPairs)(i).filter(a=>a.length<=RF.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,RF.BAGGAGE_MAX_NAME_VALUE_PAIRS),s=(0,Y3t.serializeKeyPairs)(o);s.length>0&&n.set(r,RF.BAGGAGE_HEADER,s)}extract(e,r,n){let i=n.get(r,RF.BAGGAGE_HEADER),o=Array.isArray(i)?i.join(RF.BAGGAGE_ITEMS_SEPARATOR):i;if(!o)return e;let s={};return o.length===0||(o.split(RF.BAGGAGE_ITEMS_SEPARATOR).forEach(c=>{let u=(0,Y3t.parsePairKeyValue)(c);if(u){let d={value:u.value};u.metadata&&(d.metadata=u.metadata),s[u.key]=d}}),Object.entries(s).length===0)?e:z3t.propagation.setBaggage(e,z3t.propagation.createBaggage(s))}fields(){return[RF.BAGGAGE_HEADER]}};zDe.W3CBaggagePropagator=K3t});var wRr=w(YDe=>{"use strict";Object.defineProperty(YDe,"__esModule",{value:!0});YDe.AnchoredClock=void 0;var J3t=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};YDe.AnchoredClock=J3t});var BRr=w(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0});pB.isAttributeValue=pB.isAttributeKey=pB.sanitizeAttributes=void 0;var TRr=(Kt(),yt(ar));function vso(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!IRr(r)){TRr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!DRr(n)){TRr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}pB.sanitizeAttributes=vso;function IRr(t){return typeof t=="string"&&t!==""}pB.isAttributeKey=IRr;function DRr(t){return t==null?!0:Array.isArray(t)?bso(t):RRr(typeof t)}pB.isAttributeValue=DRr;function bso(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(RRr(n)){e=n;continue}return!1}return!1}}return!0}function RRr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var X3t=w(KDe=>{"use strict";Object.defineProperty(KDe,"__esModule",{value:!0});KDe.loggingErrorHandler=void 0;var Cso=(Kt(),yt(ar));function _so(){return t=>{Cso.diag.error(xso(t))}}KDe.loggingErrorHandler=_so;function xso(t){return typeof t=="string"?t:JSON.stringify(Sso(t))}function Sso(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let i=r[n];i&&(e[n]=String(i))}),r=Object.getPrototypeOf(r);return e}});var ORr=w(NK=>{"use strict";Object.defineProperty(NK,"__esModule",{value:!0});NK.globalErrorHandler=NK.setGlobalErrorHandler=void 0;var wso=X3t(),NRr=(0,wso.loggingErrorHandler)();function Tso(t){NRr=t}NK.setGlobalErrorHandler=Tso;function Iso(t){try{NRr(t)}catch{}}NK.globalErrorHandler=Iso});var LRr=w(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.getStringListFromEnv=gS.getBooleanFromEnv=gS.getStringFromEnv=gS.getNumberFromEnv=void 0;var kRr=(Kt(),yt(ar)),PRr=Ae("util");function Dso(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){kRr.diag.warn(`Unknown value ${(0,PRr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}gS.getNumberFromEnv=Dso;function MRr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}gS.getStringFromEnv=MRr;function Rso(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||kRr.diag.warn(`Unknown value ${(0,PRr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}gS.getBooleanFromEnv=Rso;function Bso(t){return MRr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}gS.getStringListFromEnv=Bso});var FRr=w(JDe=>{"use strict";Object.defineProperty(JDe,"__esModule",{value:!0});JDe._globalThis=void 0;JDe._globalThis=typeof globalThis=="object"?globalThis:global});var URr=w(XDe=>{"use strict";Object.defineProperty(XDe,"__esModule",{value:!0});XDe.otperformance=void 0;var Nso=Ae("perf_hooks");XDe.otperformance=Nso.performance});var QRr=w(ZDe=>{"use strict";Object.defineProperty(ZDe,"__esModule",{value:!0});ZDe.VERSION=void 0;ZDe.VERSION="2.2.0"});var qRr=w(eRe=>{"use strict";Object.defineProperty(eRe,"__esModule",{value:!0});eRe.ATTR_PROCESS_RUNTIME_NAME=void 0;eRe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var HRr=w(rRe=>{"use strict";Object.defineProperty(rRe,"__esModule",{value:!0});rRe.SDK_INFO=void 0;var Oso=QRr(),tRe=(Nh(),yt(c2)),kso=qRr();rRe.SDK_INFO={[tRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[kso.ATTR_PROCESS_RUNTIME_NAME]:"node",[tRe.ATTR_TELEMETRY_SDK_LANGUAGE]:tRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[tRe.ATTR_TELEMETRY_SDK_VERSION]:Oso.VERSION}});var GRr=w(y2=>{"use strict";Object.defineProperty(y2,"__esModule",{value:!0});y2.SDK_INFO=y2.otperformance=y2._globalThis=y2.getStringListFromEnv=y2.getNumberFromEnv=y2.getBooleanFromEnv=y2.getStringFromEnv=void 0;var nRe=LRr();Object.defineProperty(y2,"getStringFromEnv",{enumerable:!0,get:function(){return nRe.getStringFromEnv}});Object.defineProperty(y2,"getBooleanFromEnv",{enumerable:!0,get:function(){return nRe.getBooleanFromEnv}});Object.defineProperty(y2,"getNumberFromEnv",{enumerable:!0,get:function(){return nRe.getNumberFromEnv}});Object.defineProperty(y2,"getStringListFromEnv",{enumerable:!0,get:function(){return nRe.getStringListFromEnv}});var Pso=FRr();Object.defineProperty(y2,"_globalThis",{enumerable:!0,get:function(){return Pso._globalThis}});var Mso=URr();Object.defineProperty(y2,"otperformance",{enumerable:!0,get:function(){return Mso.otperformance}});var Lso=HRr();Object.defineProperty(y2,"SDK_INFO",{enumerable:!0,get:function(){return Lso.SDK_INFO}})});var Z3t=w(E2=>{"use strict";Object.defineProperty(E2,"__esModule",{value:!0});E2.getStringListFromEnv=E2.getNumberFromEnv=E2.getStringFromEnv=E2.getBooleanFromEnv=E2.otperformance=E2._globalThis=E2.SDK_INFO=void 0;var BF=GRr();Object.defineProperty(E2,"SDK_INFO",{enumerable:!0,get:function(){return BF.SDK_INFO}});Object.defineProperty(E2,"_globalThis",{enumerable:!0,get:function(){return BF._globalThis}});Object.defineProperty(E2,"otperformance",{enumerable:!0,get:function(){return BF.otperformance}});Object.defineProperty(E2,"getBooleanFromEnv",{enumerable:!0,get:function(){return BF.getBooleanFromEnv}});Object.defineProperty(E2,"getStringFromEnv",{enumerable:!0,get:function(){return BF.getStringFromEnv}});Object.defineProperty(E2,"getNumberFromEnv",{enumerable:!0,get:function(){return BF.getNumberFromEnv}});Object.defineProperty(E2,"getStringListFromEnv",{enumerable:!0,get:function(){return BF.getStringListFromEnv}})});var WRr=w(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.addHrTimes=hu.isTimeInput=hu.isTimeInputHrTime=hu.hrTimeToMicroseconds=hu.hrTimeToMilliseconds=hu.hrTimeToNanoseconds=hu.hrTimeToTimeStamp=hu.hrTimeDuration=hu.timeInputToHrTime=hu.hrTime=hu.getTimeOrigin=hu.millisToHrTime=void 0;var eyt=Z3t(),jRr=9,Fso=6,Uso=Math.pow(10,Fso),iRe=Math.pow(10,jRr);function tpe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Uso);return[r,n]}hu.millisToHrTime=tpe;function tyt(){let t=eyt.otperformance.timeOrigin;if(typeof t!="number"){let e=eyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}hu.getTimeOrigin=tyt;function VRr(t){let e=tpe(tyt()),r=tpe(typeof t=="number"?t:eyt.otperformance.now());return $Rr(e,r)}hu.hrTime=VRr;function Qso(t){if(ryt(t))return t;if(typeof t=="number")return t<tyt()?VRr(t):tpe(t);if(t instanceof Date)return tpe(t.getTime());throw TypeError("Invalid input type")}hu.timeInputToHrTime=Qso;function qso(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=iRe),[r,n]}hu.hrTimeDuration=qso;function Hso(t){let e=jRr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}hu.hrTimeToTimeStamp=Hso;function Gso(t){return t[0]*iRe+t[1]}hu.hrTimeToNanoseconds=Gso;function jso(t){return t[0]*1e3+t[1]/1e6}hu.hrTimeToMilliseconds=jso;function Vso(t){return t[0]*1e6+t[1]/1e3}hu.hrTimeToMicroseconds=Vso;function ryt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}hu.isTimeInputHrTime=ryt;function $so(t){return ryt(t)||typeof t=="number"||t instanceof Date}hu.isTimeInput=$so;function $Rr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=iRe&&(r[1]-=iRe,r[0]+=1),r}hu.addHrTimes=$Rr});var zRr=w(oRe=>{"use strict";Object.defineProperty(oRe,"__esModule",{value:!0});oRe.unrefTimer=void 0;function Wso(t){typeof t!="number"&&t.unref()}oRe.unrefTimer=Wso});var YRr=w(rpe=>{"use strict";Object.defineProperty(rpe,"__esModule",{value:!0});rpe.ExportResultCode=void 0;var zso;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(zso=rpe.ExportResultCode||(rpe.ExportResultCode={}))});var JRr=w(sRe=>{"use strict";Object.defineProperty(sRe,"__esModule",{value:!0});sRe.CompositePropagator=void 0;var KRr=(Kt(),yt(ar)),nyt=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let i of this._propagators)try{i.inject(e,r,n)}catch(o){KRr.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${o.message}`)}}extract(e,r,n){return this._propagators.reduce((i,o)=>{try{return o.extract(i,r,n)}catch(s){KRr.diag.warn(`Failed to extract with ${o.constructor.name}. Err: ${s.message}`)}return i},e)}fields(){return this._fields.slice()}};sRe.CompositePropagator=nyt});var XRr=w(OK=>{"use strict";Object.defineProperty(OK,"__esModule",{value:!0});OK.validateValue=OK.validateKey=void 0;var iyt="[_0-9a-z-*/]",Yso=`[a-z]${iyt}{0,255}`,Kso=`[a-z0-9]${iyt}{0,240}@[a-z]${iyt}{0,13}`,Jso=new RegExp(`^(?:${Yso}|${Kso})$`),Xso=/^[ -~]{0,255}[!-~]$/,Zso=/,|=/;function eao(t){return Jso.test(t)}OK.validateKey=eao;function tao(t){return Xso.test(t)&&!Zso.test(t)}OK.validateValue=tao});var syt=w(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0});aRe.TraceState=void 0;var ZRr=XRr(),eBr=32,rao=512,tBr=",",rBr="=",oyt=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+rBr+this.get(r)),e),[]).join(tBr)}_parse(e){e.length>rao||(this._internalState=e.split(tBr).reverse().reduce((r,n)=>{let i=n.trim(),o=i.indexOf(rBr);if(o!==-1){let s=i.slice(0,o),a=i.slice(o+1,n.length);(0,ZRr.validateKey)(s)&&(0,ZRr.validateValue)(a)&&r.set(s,a)}return r},new Map),this._internalState.size>eBr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,eBr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};aRe.TraceState=oyt});var iBr=w(v2=>{"use strict";Object.defineProperty(v2,"__esModule",{value:!0});v2.W3CTraceContextPropagator=v2.parseTraceParent=v2.TRACE_STATE_HEADER=v2.TRACE_PARENT_HEADER=void 0;var cRe=(Kt(),yt(ar)),nao=epe(),iao=syt();v2.TRACE_PARENT_HEADER="traceparent";v2.TRACE_STATE_HEADER="tracestate";var oao="00",sao="(?!ff)[\\da-f]{2}",aao="(?![0]{32})[\\da-f]{32}",cao="(?![0]{16})[\\da-f]{16}",lao="[\\da-f]{2}",uao=new RegExp(`^\\s?(${sao})-(${aao})-(${cao})-(${lao})(-.*)?\\s?$`);function nBr(t){let e=uao.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}v2.parseTraceParent=nBr;var ayt=class{inject(e,r,n){let i=cRe.trace.getSpanContext(e);if(!i||(0,nao.isTracingSuppressed)(e)||!(0,cRe.isSpanContextValid)(i))return;let o=`${oao}-${i.traceId}-${i.spanId}-0${Number(i.traceFlags||cRe.TraceFlags.NONE).toString(16)}`;n.set(r,v2.TRACE_PARENT_HEADER,o),i.traceState&&n.set(r,v2.TRACE_STATE_HEADER,i.traceState.serialize())}extract(e,r,n){let i=n.get(r,v2.TRACE_PARENT_HEADER);if(!i)return e;let o=Array.isArray(i)?i[0]:i;if(typeof o!="string")return e;let s=nBr(o);if(!s)return e;s.isRemote=!0;let a=n.get(r,v2.TRACE_STATE_HEADER);if(a){let c=Array.isArray(a)?a.join(","):a;s.traceState=new iao.TraceState(typeof c=="string"?c:void 0)}return cRe.trace.setSpanContext(e,s)}fields(){return[v2.TRACE_PARENT_HEADER,v2.TRACE_STATE_HEADER]}};v2.W3CTraceContextPropagator=ayt});var oBr=w(ZC=>{"use strict";Object.defineProperty(ZC,"__esModule",{value:!0});ZC.getRPCMetadata=ZC.deleteRPCMetadata=ZC.setRPCMetadata=ZC.RPCType=void 0;var dao=(Kt(),yt(ar)),cyt=(0,dao.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),fao;(function(t){t.HTTP="http"})(fao=ZC.RPCType||(ZC.RPCType={}));function pao(t,e){return t.setValue(cyt,e)}ZC.setRPCMetadata=pao;function hao(t){return t.deleteValue(cyt)}ZC.deleteRPCMetadata=hao;function mao(t){return t.getValue(cyt)}ZC.getRPCMetadata=mao});var uBr=w(lRe=>{"use strict";Object.defineProperty(lRe,"__esModule",{value:!0});lRe.isPlainObject=void 0;var gao="[object Object]",Aao="[object Null]",yao="[object Undefined]",Eao=Function.prototype,sBr=Eao.toString,vao=sBr.call(Object),bao=Object.getPrototypeOf,aBr=Object.prototype,cBr=aBr.hasOwnProperty,NF=Symbol?Symbol.toStringTag:void 0,lBr=aBr.toString;function Cao(t){if(!_ao(t)||xao(t)!==gao)return!1;let e=bao(t);if(e===null)return!0;let r=cBr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&sBr.call(r)===vao}lRe.isPlainObject=Cao;function _ao(t){return t!=null&&typeof t=="object"}function xao(t){return t==null?t===void 0?yao:Aao:NF&&NF in Object(t)?Sao(t):wao(t)}function Sao(t){let e=cBr.call(t,NF),r=t[NF],n=!1;try{t[NF]=void 0,n=!0}catch{}let i=lBr.call(t);return n&&(e?t[NF]=r:delete t[NF]),i}function wao(t){return lBr.call(t)}});var mBr=w(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.merge=void 0;var dBr=uBr(),Tao=20;function Iao(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=pBr(e,t.shift(),0,r);return e}fRe.merge=Iao;function lyt(t){return dRe(t)?t.slice():t}function pBr(t,e,r=0,n){let i;if(!(r>Tao)){if(r++,uRe(t)||uRe(e)||hBr(e))i=lyt(e);else if(dRe(t)){if(i=t.slice(),dRe(e))for(let o=0,s=e.length;o<s;o++)i.push(lyt(e[o]));else if(npe(e)){let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s];i[c]=lyt(e[c])}}}else if(npe(t))if(npe(e)){if(!Dao(t,e))return e;i=Object.assign({},t);let o=Object.keys(e);for(let s=0,a=o.length;s<a;s++){let c=o[s],u=e[c];if(uRe(u))typeof u>"u"?delete i[c]:i[c]=u;else{let d=i[c],f=u;if(fBr(t,c,n)||fBr(e,c,n))delete i[c];else{if(npe(d)&&npe(f)){let p=n.get(d)||[],h=n.get(f)||[];p.push({obj:t,key:c}),h.push({obj:e,key:c}),n.set(d,p),n.set(f,h)}i[c]=pBr(i[c],u,r,n)}}}}else i=e;return i}}function fBr(t,e,r){let n=r.get(t[e])||[];for(let i=0,o=n.length;i<o;i++){let s=n[i];if(s.key===e&&s.obj===t)return!0}return!1}function dRe(t){return Array.isArray(t)}function hBr(t){return typeof t=="function"}function npe(t){return!uRe(t)&&!dRe(t)&&!hBr(t)&&typeof t=="object"}function uRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Dao(t,e){return!(!(0,dBr.isPlainObject)(t)||!(0,dBr.isPlainObject)(e))}});var gBr=w(kK=>{"use strict";Object.defineProperty(kK,"__esModule",{value:!0});kK.callWithTimeout=kK.TimeoutError=void 0;var pRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};kK.TimeoutError=pRe;function Rao(t,e){let r,n=new Promise(function(o,s){r=setTimeout(function(){s(new pRe("Operation timed out."))},e)});return Promise.race([t,n]).then(i=>(clearTimeout(r),i),i=>{throw clearTimeout(r),i})}kK.callWithTimeout=Rao});var yBr=w(PK=>{"use strict";Object.defineProperty(PK,"__esModule",{value:!0});PK.isUrlIgnored=PK.urlMatches=void 0;function ABr(t,e){return typeof e=="string"?t===e:!!t.match(e)}PK.urlMatches=ABr;function Bao(t,e){if(!e)return!1;for(let r of e)if(ABr(t,r))return!0;return!1}PK.isUrlIgnored=Bao});var EBr=w(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.Deferred=void 0;var uyt=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};hRe.Deferred=uyt});var vBr=w(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.BindOnceFuture=void 0;var Nao=EBr(),dyt=class{_callback;_that;_isCalled=!1;_deferred=new Nao.Deferred;constructor(e,r){this._callback=e,this._that=r}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(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};mRe.BindOnceFuture=dyt});var CBr=w(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.diagLogLevelFromString=void 0;var pT=(Kt(),yt(ar)),bBr={ALL:pT.DiagLogLevel.ALL,VERBOSE:pT.DiagLogLevel.VERBOSE,DEBUG:pT.DiagLogLevel.DEBUG,INFO:pT.DiagLogLevel.INFO,WARN:pT.DiagLogLevel.WARN,ERROR:pT.DiagLogLevel.ERROR,NONE:pT.DiagLogLevel.NONE};function Oao(t){if(t==null)return;let e=bBr[t.toUpperCase()];return e??(pT.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(bBr)}, using default`),pT.DiagLogLevel.INFO)}gRe.diagLogLevelFromString=Oao});var xBr=w(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe._export=void 0;var _Br=(Kt(),yt(ar)),kao=epe();function Pao(t,e){return new Promise(r=>{_Br.context.with((0,kao.suppressTracing)(_Br.context.active()),()=>{t.export(e,n=>{r(n)})})})}ARe._export=Pao});var hT=w(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.internal=Lr.diagLogLevelFromString=Lr.BindOnceFuture=Lr.urlMatches=Lr.isUrlIgnored=Lr.callWithTimeout=Lr.TimeoutError=Lr.merge=Lr.TraceState=Lr.unsuppressTracing=Lr.suppressTracing=Lr.isTracingSuppressed=Lr.setRPCMetadata=Lr.getRPCMetadata=Lr.deleteRPCMetadata=Lr.RPCType=Lr.parseTraceParent=Lr.W3CTraceContextPropagator=Lr.TRACE_STATE_HEADER=Lr.TRACE_PARENT_HEADER=Lr.CompositePropagator=Lr.otperformance=Lr.getStringListFromEnv=Lr.getNumberFromEnv=Lr.getBooleanFromEnv=Lr.getStringFromEnv=Lr._globalThis=Lr.SDK_INFO=Lr.parseKeyPairsIntoRecord=Lr.ExportResultCode=Lr.unrefTimer=Lr.timeInputToHrTime=Lr.millisToHrTime=Lr.isTimeInputHrTime=Lr.isTimeInput=Lr.hrTimeToTimeStamp=Lr.hrTimeToNanoseconds=Lr.hrTimeToMilliseconds=Lr.hrTimeToMicroseconds=Lr.hrTimeDuration=Lr.hrTime=Lr.getTimeOrigin=Lr.addHrTimes=Lr.loggingErrorHandler=Lr.setGlobalErrorHandler=Lr.globalErrorHandler=Lr.sanitizeAttributes=Lr.isAttributeValue=Lr.AnchoredClock=Lr.W3CBaggagePropagator=void 0;var Mao=SRr();Object.defineProperty(Lr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Mao.W3CBaggagePropagator}});var Lao=wRr();Object.defineProperty(Lr,"AnchoredClock",{enumerable:!0,get:function(){return Lao.AnchoredClock}});var SBr=BRr();Object.defineProperty(Lr,"isAttributeValue",{enumerable:!0,get:function(){return SBr.isAttributeValue}});Object.defineProperty(Lr,"sanitizeAttributes",{enumerable:!0,get:function(){return SBr.sanitizeAttributes}});var wBr=ORr();Object.defineProperty(Lr,"globalErrorHandler",{enumerable:!0,get:function(){return wBr.globalErrorHandler}});Object.defineProperty(Lr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return wBr.setGlobalErrorHandler}});var Fao=X3t();Object.defineProperty(Lr,"loggingErrorHandler",{enumerable:!0,get:function(){return Fao.loggingErrorHandler}});var Vv=WRr();Object.defineProperty(Lr,"addHrTimes",{enumerable:!0,get:function(){return Vv.addHrTimes}});Object.defineProperty(Lr,"getTimeOrigin",{enumerable:!0,get:function(){return Vv.getTimeOrigin}});Object.defineProperty(Lr,"hrTime",{enumerable:!0,get:function(){return Vv.hrTime}});Object.defineProperty(Lr,"hrTimeDuration",{enumerable:!0,get:function(){return Vv.hrTimeDuration}});Object.defineProperty(Lr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return Vv.hrTimeToMicroseconds}});Object.defineProperty(Lr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return Vv.hrTimeToMilliseconds}});Object.defineProperty(Lr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return Vv.hrTimeToNanoseconds}});Object.defineProperty(Lr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return Vv.hrTimeToTimeStamp}});Object.defineProperty(Lr,"isTimeInput",{enumerable:!0,get:function(){return Vv.isTimeInput}});Object.defineProperty(Lr,"isTimeInputHrTime",{enumerable:!0,get:function(){return Vv.isTimeInputHrTime}});Object.defineProperty(Lr,"millisToHrTime",{enumerable:!0,get:function(){return Vv.millisToHrTime}});Object.defineProperty(Lr,"timeInputToHrTime",{enumerable:!0,get:function(){return Vv.timeInputToHrTime}});var Uao=zRr();Object.defineProperty(Lr,"unrefTimer",{enumerable:!0,get:function(){return Uao.unrefTimer}});var Qao=YRr();Object.defineProperty(Lr,"ExportResultCode",{enumerable:!0,get:function(){return Qao.ExportResultCode}});var qao=W3t();Object.defineProperty(Lr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return qao.parseKeyPairsIntoRecord}});var OF=Z3t();Object.defineProperty(Lr,"SDK_INFO",{enumerable:!0,get:function(){return OF.SDK_INFO}});Object.defineProperty(Lr,"_globalThis",{enumerable:!0,get:function(){return OF._globalThis}});Object.defineProperty(Lr,"getStringFromEnv",{enumerable:!0,get:function(){return OF.getStringFromEnv}});Object.defineProperty(Lr,"getBooleanFromEnv",{enumerable:!0,get:function(){return OF.getBooleanFromEnv}});Object.defineProperty(Lr,"getNumberFromEnv",{enumerable:!0,get:function(){return OF.getNumberFromEnv}});Object.defineProperty(Lr,"getStringListFromEnv",{enumerable:!0,get:function(){return OF.getStringListFromEnv}});Object.defineProperty(Lr,"otperformance",{enumerable:!0,get:function(){return OF.otperformance}});var Hao=JRr();Object.defineProperty(Lr,"CompositePropagator",{enumerable:!0,get:function(){return Hao.CompositePropagator}});var yRe=iBr();Object.defineProperty(Lr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return yRe.TRACE_PARENT_HEADER}});Object.defineProperty(Lr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return yRe.TRACE_STATE_HEADER}});Object.defineProperty(Lr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return yRe.W3CTraceContextPropagator}});Object.defineProperty(Lr,"parseTraceParent",{enumerable:!0,get:function(){return yRe.parseTraceParent}});var ERe=oBr();Object.defineProperty(Lr,"RPCType",{enumerable:!0,get:function(){return ERe.RPCType}});Object.defineProperty(Lr,"deleteRPCMetadata",{enumerable:!0,get:function(){return ERe.deleteRPCMetadata}});Object.defineProperty(Lr,"getRPCMetadata",{enumerable:!0,get:function(){return ERe.getRPCMetadata}});Object.defineProperty(Lr,"setRPCMetadata",{enumerable:!0,get:function(){return ERe.setRPCMetadata}});var fyt=epe();Object.defineProperty(Lr,"isTracingSuppressed",{enumerable:!0,get:function(){return fyt.isTracingSuppressed}});Object.defineProperty(Lr,"suppressTracing",{enumerable:!0,get:function(){return fyt.suppressTracing}});Object.defineProperty(Lr,"unsuppressTracing",{enumerable:!0,get:function(){return fyt.unsuppressTracing}});var Gao=syt();Object.defineProperty(Lr,"TraceState",{enumerable:!0,get:function(){return Gao.TraceState}});var jao=mBr();Object.defineProperty(Lr,"merge",{enumerable:!0,get:function(){return jao.merge}});var TBr=gBr();Object.defineProperty(Lr,"TimeoutError",{enumerable:!0,get:function(){return TBr.TimeoutError}});Object.defineProperty(Lr,"callWithTimeout",{enumerable:!0,get:function(){return TBr.callWithTimeout}});var IBr=yBr();Object.defineProperty(Lr,"isUrlIgnored",{enumerable:!0,get:function(){return IBr.isUrlIgnored}});Object.defineProperty(Lr,"urlMatches",{enumerable:!0,get:function(){return IBr.urlMatches}});var Vao=vBr();Object.defineProperty(Lr,"BindOnceFuture",{enumerable:!0,get:function(){return Vao.BindOnceFuture}});var $ao=CBr();Object.defineProperty(Lr,"diagLogLevelFromString",{enumerable:!0,get:function(){return $ao.diagLogLevelFromString}});var Wao=xBr();Lr.internal={_export:Wao._export}});var DBr=w(bRe=>{"use strict";Object.defineProperty(bRe,"__esModule",{value:!0});bRe.LogRecordImpl=void 0;var kF=(Kt(),yt(ar)),vRe=hT(),pyt=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,n){let{timestamp:i,observedTimestamp:o,eventName:s,severityNumber:a,severityText:c,body:u,attributes:d={},context:f}=n,p=Date.now();if(this.hrTime=(0,vRe.timeInputToHrTime)(i??p),this.hrTimeObserved=(0,vRe.timeInputToHrTime)(o??p),f){let h=kF.trace.getSpanContext(f);h&&kF.isSpanContextValid(h)&&(this.spanContext=h)}this.severityNumber=a,this.severityText=c,this.body=u,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=s,this.setAttributes(d)}setAttribute(e,r){return this._isLogRecordReadonly()?this:r===null?this:e.length===0?(kF.diag.warn(`Invalid attribute key: ${e}`),this):!(0,vRe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(kF.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&kF.diag.warn("Dropping extra attributes."),this):((0,vRe.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let r=this._logRecordLimits.attributeValueLengthLimit;return r<=0?(kF.diag.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(n=>typeof n=="string"?this._truncateToLimitUtil(n,r):n):e}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_isLogRecordReadonly(){return this._isReadonly&&kF.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};bRe.LogRecordImpl=pyt});var RBr=w(CRe=>{"use strict";Object.defineProperty(CRe,"__esModule",{value:!0});CRe.Logger=void 0;var zao=(Kt(),yt(ar)),Yao=DBr(),hyt=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||zao.context.active(),n=new Yao.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};CRe.Logger=hyt});var BBr=w(LK=>{"use strict";Object.defineProperty(LK,"__esModule",{value:!0});LK.reconfigureLimits=LK.loadDefaultConfig=void 0;var MK=hT();function Kao(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}LK.loadDefaultConfig=Kao;function Jao(t){return{attributeCountLimit:t.attributeCountLimit??(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??(0,MK.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:t.attributeValueLengthLimit??(0,MK.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??(0,MK.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}LK.reconfigureLimits=Jao});var gyt=w(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.NoopLogRecordProcessor=void 0;var myt=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};_Re.NoopLogRecordProcessor=myt});var NBr=w(xRe=>{"use strict";Object.defineProperty(xRe,"__esModule",{value:!0});xRe.MultiLogRecordProcessor=void 0;var Xao=hT(),Ayt=class{processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>(0,Xao.callWithTimeout)(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(n=>n.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};xRe.MultiLogRecordProcessor=Ayt});var OBr=w(SRe=>{"use strict";Object.defineProperty(SRe,"__esModule",{value:!0});SRe.LoggerProviderSharedState=void 0;var Zao=gyt(),eco=NBr(),yyt=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,n,i){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=n,this.processors=i,i.length>0?(this.registeredLogRecordProcessors=i,this.activeProcessor=new eco.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Zao.NoopLogRecordProcessor}};SRe.LoggerProviderSharedState=yyt});var MBr=w(PF=>{"use strict";Object.defineProperty(PF,"__esModule",{value:!0});PF.LoggerProvider=PF.DEFAULT_LOGGER_NAME=void 0;var wRe=(Kt(),yt(ar)),tco=_Rr(),rco=U3t(),kBr=hT(),nco=RBr(),PBr=BBr(),ico=OBr();PF.DEFAULT_LOGGER_NAME="unknown";var Eyt=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,kBr.merge)({},(0,PBr.loadDefaultConfig)(),e),n=e.resource??(0,rco.defaultResource)();this._sharedState=new ico.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,PBr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new kBr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return wRe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),tco.NOOP_LOGGER;e||wRe.diag.warn("Logger requested without instrumentation scope name.");let i=e||PF.DEFAULT_LOGGER_NAME,o=`${i}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(o)||this._sharedState.loggers.set(o,new nco.Logger({name:i,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(o)}forceFlush(){return this._shutdownOnce.isCalled?(wRe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(wRe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};PF.LoggerProvider=Eyt});var FBr=w(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0});TRe.ConsoleLogRecordExporter=void 0;var LBr=hT(),vyt=class{export(e,r){this._sendLogRecords(e,r)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,LBr.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,r){for(let n of e)console.dir(this._exportInfo(n),{depth:3});r?.({code:LBr.ExportResultCode.SUCCESS})}};TRe.ConsoleLogRecordExporter=vyt});var UBr=w(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.SimpleLogRecordProcessor=void 0;var FK=hT(),byt=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new FK.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let r=()=>FK.internal._export(this._exporter,[e]).then(n=>{n.code!==FK.ExportResultCode.SUCCESS&&(0,FK.globalErrorHandler)(n.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${n})`))}).catch(FK.globalErrorHandler);if(e.resource.asyncAttributesPending){let n=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(n),r()),FK.globalErrorHandler);n!=null&&this._unresolvedExports.add(n)}else r()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}};IRe.SimpleLogRecordProcessor=byt});var qBr=w(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe.InMemoryLogRecordExporter=void 0;var QBr=hT(),Cyt=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:QBr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:QBr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};DRe.InMemoryLogRecordExporter=Cyt});var HBr=w(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe.BatchLogRecordProcessorBase=void 0;var oco=(Kt(),yt(ar)),$v=hT(),_yt=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,$v.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,$v.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,$v.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,$v.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new $v.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(oco.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,r)=>{let n=[],i=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let o=0;o<i;o++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(r)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,r)=>{(0,$v.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(r)})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().then(()=>{this._isExporting=!1,this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(r=>{this._isExporting=!1,(0,$v.globalErrorHandler)(r)})};if(this._finishedLogRecords.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let r=()=>$v.internal._export(this._exporter,e).then(i=>{i.code!==$v.ExportResultCode.SUCCESS&&(0,$v.globalErrorHandler)(i.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${i})`))}).catch($v.globalErrorHandler),n=e.map(i=>i.resource).filter(i=>i.asyncAttributesPending);return n.length===0?r():Promise.all(n.map(i=>i.waitForAsyncAttributes?.())).then(r,$v.globalErrorHandler)}};RRe.BatchLogRecordProcessorBase=_yt});var GBr=w(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.BatchLogRecordProcessor=void 0;var sco=HBr(),xyt=class extends sco.BatchLogRecordProcessorBase{onShutdown(){}};BRe.BatchLogRecordProcessor=xyt});var jBr=w(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe.BatchLogRecordProcessor=void 0;var aco=GBr();Object.defineProperty(NRe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return aco.BatchLogRecordProcessor}})});var VBr=w(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe.BatchLogRecordProcessor=void 0;var cco=jBr();Object.defineProperty(ORe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return cco.BatchLogRecordProcessor}})});var $Br=w(w3=>{"use strict";Object.defineProperty(w3,"__esModule",{value:!0});w3.BatchLogRecordProcessor=w3.InMemoryLogRecordExporter=w3.SimpleLogRecordProcessor=w3.ConsoleLogRecordExporter=w3.NoopLogRecordProcessor=w3.LoggerProvider=void 0;var lco=MBr();Object.defineProperty(w3,"LoggerProvider",{enumerable:!0,get:function(){return lco.LoggerProvider}});var uco=gyt();Object.defineProperty(w3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return uco.NoopLogRecordProcessor}});var dco=FBr();Object.defineProperty(w3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return dco.ConsoleLogRecordExporter}});var fco=UBr();Object.defineProperty(w3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return fco.SimpleLogRecordProcessor}});var pco=qBr();Object.defineProperty(w3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return pco.InMemoryLogRecordExporter}});var hco=VBr();Object.defineProperty(w3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return hco.BatchLogRecordProcessor}})});var Ph,WBr,ipe,zBr,ope,spe,YBr,KBr,JBr,XBr,ZBr,eNr,tNr,rNr,nNr,iNr,oNr,sNr,aNr,cNr,lNr,uNr,dNr,fNr,pNr,hNr,mNr,gNr,ANr,yNr,ENr,ape=Z(()=>{"use strict";Ph="iflow-cli",WBr="iflow_cli.user_prompt",ipe="iflow_cli.tool_call",zBr="iflow_cli.api_request",ope="iflow_cli.api_error",spe="iflow_cli.api_response",YBr="iflow_cli.config",KBr="iflow_cli.flash_fallback",JBr="iflow_cli.next_speaker_check",XBr="iflow_cli.slash_command",ZBr="iflow_cli.cli_response",eNr="iflow_cli.tool.call.count",tNr="iflow_cli.tool.call.latency",rNr="iflow_cli.mcp.tool.call.count",nNr="iflow_cli.mcp.tool.call.latency",iNr="iflow_cli.builtin.tool.call.count",oNr="iflow_cli.builtin.tool.call.latency",sNr="gen_ai.client.operation",aNr="gen_ai.client.operation.duration",cNr="gen_ai.client.token.usage",lNr="iflow_cli.session.count",uNr="iflow_cli.file.operation.count",dNr="iflow_cli.user_request.count",fNr="iflow_cli.user_request.latency",pNr="iflow_cli.user_experience.success",hNr="iflow_cli.user.identity",mNr="iflow_cli.scheduler.lock.error",gNr="iflow_cli.mcp.connect.count",ANr="iflow_cli.loop.detection.count",yNr="iflow_cli.paste.operation.count",ENr="iflow_cli.paste.operation.latency"});import mco from"os";function vNr(){try{let t=mco.networkInterfaces();for(let e of Object.keys(t)){let r=t[e];if(r){for(let n of r)if(n.family==="IPv4"&&!n.internal)return n.address}}return"127.0.0.1"}catch{return"127.0.0.1"}}var bNr=Z(()=>{"use strict"});var UK,QK,qK,HK,GK,jK,VK,$K,WK,zK,e5,t5,CNr=Z(()=>{"use strict";UK="iflow_cli.cpu.usage_percentage",QK="iflow_cli.cpu.user_percentage",qK="iflow_cli.cpu.system_percentage",HK="iflow_cli.cpu.cores",GK="iflow_cli.memory.heap_used",jK="iflow_cli.memory.heap_total",VK="iflow_cli.memory.rss",$K="iflow_cli.memory.external",WK="iflow_cli.memory.system_usage_percentage",zK="iflow_cli.memory.process_usage_percentage",e5={[UK]:"CPU usage percentage",[QK]:"CPU user time percentage",[qK]:"CPU system time percentage",[HK]:"Number of CPU cores",[GK]:"Heap memory used in bytes",[jK]:"Heap memory total in bytes",[VK]:"Resident Set Size in bytes",[$K]:"External memory in bytes",[WK]:"System memory usage percentage",[zK]:"Process memory usage percentage relative to Node.js limits"},t5={[UK]:"percent",[QK]:"percent",[qK]:"percent",[HK]:"cores",[GK]:"bytes",[jK]:"bytes",[VK]:"bytes",[$K]:"bytes",[WK]:"percent",[zK]:"percent"}});import*as r5 from"os";var kRe,_Nr=Z(()=>{"use strict";CNr();kRe=class{meter;options;lastCpuMeasurement;lastMeasureTime;cpuCores;totalSystemMemory;nodeJSMemoryLimit;cpuUsageGauge;cpuUserGauge;cpuSystemGauge;cpuCoresGauge;memoryHeapUsedGauge;memoryHeapTotalGauge;memoryRssGauge;memoryExternalGauge;memorySystemUsageGauge;memoryProcessUsageGauge;constructor(e,r={}){this.meter=e,this.options={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...r},this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=Date.now(),this.cpuCores=r5.cpus().length,this.totalSystemMemory=r5.totalmem(),this.nodeJSMemoryLimit=this.getNodeJSMemoryLimit(),this.initializeMetrics()}getCurrentCpuMetrics(){try{let e=process.cpuUsage(this.lastCpuMeasurement),r=Date.now(),n=r-this.lastMeasureTime;if(this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=r,n<=0)return{usage:0,user:0,system:0,cores:this.cpuCores};let i=Math.max(0,e.user+e.system),o=Math.max(0,e.user),s=Math.max(0,e.system),a=i/(n*1e3)*100,c=o/(n*1e3)*100,u=s/(n*1e3)*100,d=Number.isFinite(a)?Math.min(100,Math.max(0,a)):0,f=Number.isFinite(c)?Math.min(100,Math.max(0,c)):0,p=Number.isFinite(u)?Math.min(100,Math.max(0,u)):0;return{usage:d,user:f,system:p,cores:this.cpuCores}}catch{return{usage:0,user:0,system:0,cores:this.cpuCores}}}getCurrentMemoryMetrics(){try{let e=process.memoryUsage(),r=r5.freemem(),i=(this.totalSystemMemory-r)/this.totalSystemMemory*100,o=e.rss/this.nodeJSMemoryLimit*100;return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external,systemUsage:Math.min(100,Math.max(0,i)),processUsage:Math.min(100,Math.max(0,o))}}catch{return{heapUsed:0,heapTotal:0,rss:0,external:0,systemUsage:0,processUsage:0}}}initializeMetrics(){let e=r5.platform(),r=r5.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(UK,{description:e5[UK],unit:t5[UK]}),this.cpuUserGauge=this.meter.createObservableGauge(QK,{description:e5[QK],unit:t5[QK]}),this.cpuSystemGauge=this.meter.createObservableGauge(qK,{description:e5[qK],unit:t5[qK]}),this.cpuCoresGauge=this.meter.createObservableGauge(HK,{description:e5[HK],unit:t5[HK]}),this.cpuUsageGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.usage,{platform:e,arch:r,node_version:n})}),this.cpuUserGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.user,{platform:e,arch:r,node_version:n})}),this.cpuSystemGauge.addCallback(i=>{let o=this.getCurrentCpuMetrics();i.observe(o.system,{platform:e,arch:r,node_version:n})}),this.cpuCoresGauge?.addCallback(i=>{i.observe(this.cpuCores,{platform:e,arch:r})})),this.options.enableMemoryMetrics&&(this.memoryHeapUsedGauge=this.meter.createObservableGauge(GK,{description:e5[GK],unit:t5[GK]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(jK,{description:e5[jK],unit:t5[jK]}),this.memoryRssGauge=this.meter.createObservableGauge(VK,{description:e5[VK],unit:t5[VK]}),this.memoryExternalGauge=this.meter.createObservableGauge($K,{description:e5[$K],unit:t5[$K]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(WK,{description:e5[WK],unit:t5[WK]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(zK,{description:e5[zK],unit:t5[zK]}),this.memoryHeapUsedGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.heapUsed,{platform:e,arch:r,node_version:n})}),this.memoryHeapTotalGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.heapTotal,{platform:e,arch:r,node_version:n})}),this.memoryRssGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.rss,{platform:e,arch:r,node_version:n})}),this.memoryExternalGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.external,{platform:e,arch:r,node_version:n})}),this.memorySystemUsageGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.systemUsage,{platform:e,arch:r,node_version:n})}),this.memoryProcessUsageGauge.addCallback(i=>{let o=this.getCurrentMemoryMetrics();i.observe(o.processUsage,{platform:e,arch:r,node_version:n,memory_limit_mb:Math.round(this.nodeJSMemoryLimit/(1024*1024)).toString()})}))}getNodeJSMemoryLimit(){let e=process.execArgv.find(i=>i.startsWith("--max-old-space-size="))?.split("=")[1];if(e){let i=parseInt(e,10);if(!isNaN(i)&&i>0)return i*1024*1024}let r=process.execArgv.find(i=>i.startsWith("--max_old_space_size="))?.split("=")[1];if(r){let i=parseInt(r,10);if(!isNaN(i)&&i>0)return i*1024*1024}let n=r5.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function xNr(t,e={}){if(PRe)return PRe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return PRe=new kRe(t,r),PRe}var PRe,SNr=Z(()=>{"use strict";_Nr();PRe=null});import*as YK from"os";import*as MRe from"fs";function Jp(t){let e="0.3.24",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},i=YK.platform(),o=n[i]||i,s="unknown";try{if(i==="darwin")s=YK.release();else if(i==="linux")try{if(MRe.existsSync("/etc/os-release")){let h=MRe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);h&&(s=h[1])}}catch{s=YK.release()}else i==="win32"&&(s=YK.release())}catch{s="unknown"}let a={name:"Node.js",version:process.version,architecture:process.arch},c=t.getModel()||"unknown",u=t.getUsageMode(),d=!1,f=t.getContentGeneratorConfig?.();if(f){let p=f.authType,h=f.baseUrl||"";(p===zt.LOGIN_WITH_IFLOW||p===zt.IFLOW||p===zt.OPENAI_COMPATIBLE&&h.includes("apis.iflow.cn"))&&(d=!0)}return{app_name:Ph,tenant__:"gen_ai",version:e,platform:o,os_model:s,runtime_name:a.name,runtime_version:a.version,runtime_architecture:a.architecture,model_name:c,is_iflow_open_user:String(d),ip:vNr(),iflow_env:r,usage_mode:u}}function wNr(){return Syt||(Syt=Hue.getMeter(Ph)),Syt}function TNr(){if(Xg)return;let t=wNr();if(t){try{xNr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}wyt=t.createHistogram(eNr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Tyt=t.createHistogram(tNr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),Iyt=t.createHistogram(rNr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Dyt=t.createHistogram(nNr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),Ryt=t.createHistogram(iNr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:Ll.INT}),Byt=t.createHistogram(oNr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:Ll.INT}),cpe=t.createHistogram(sNr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:Ll.INT}),lpe=t.createHistogram(aNr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:Ll.INT}),Nyt=t.createHistogram(cNr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:Ll.INT}),Oyt=t.createHistogram(uNr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:Ll.INT}),kyt=t.createHistogram(dNr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:Ll.INT}),Pyt=t.createHistogram(fNr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:Ll.INT}),Myt=t.createHistogram(pNr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:Ll.INT}),Lyt=t.createHistogram(hNr,{description:"User identity for tracking unique installations.",unit:"count",valueType:Ll.INT}),Fyt=t.createHistogram(mNr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:Ll.INT}),Uyt=t.createHistogram(gNr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:Ll.INT}),Qyt=t.createHistogram(ANr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:Ll.INT}),qyt=t.createHistogram(yNr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:Ll.INT}),Hyt=t.createHistogram(ENr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:Ll.INT}),Xg=!0}}function LRe(t){let e=wNr();if(!e||!Xg)return;e.createHistogram(lNr,{description:"Count of CLI sessions started.",unit:"count",valueType:Ll.INT}).record(1,Jp(t))}function INr(t,e,r,n,i,o){if(!wyt||!Tyt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};wyt.record(1,s),Tyt.record(r,{...Jp(t),function_name:e??"unknown",tool_type:o??"unknown"})}function DNr(t,e,r,n,i,o){if(!Iyt||!Dyt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};o&&(s.execution_context=o),Iyt.record(1,s),Dyt.record(r,{...Jp(t),function_name:e??"unknown",execution_context:o??"unknown"})}function RNr(t,e,r,n,i,o){if(!Ryt||!Byt||!Xg)return;let s={...Jp(t),function_name:e??"unknown",success:String(n),decision:i??"unknown"};o&&(s.execution_context=o),Ryt.record(1,s),Byt.record(r,{...Jp(t),function_name:e??"unknown",execution_context:o??"unknown"})}function KK(t,e,r,n){!Nyt||!Xg||Nyt.record(r,{...Jp(t),model:e??"unknown",type:n??"unknown"})}function BNr(t,e,r,n,i,o,s,a){if(!cpe||!lpe||!Xg)return;let c={...Jp(t),model:e??"unknown",status_code:String(n??(i?"error":"ok"))};s!==void 0&&(c.http_status_code=String(s)),a!==void 0&&(c.business_code=String(a)),o&&(c.finish_reason=o),cpe.record(1,c);let u={...Jp(t),model:e??"unknown",http_status_code:String(s??200),finish_reason:o??"unknown"};a!=null&&(u.business_code=String(a)),lpe.record(r,u)}function NNr(t,e,r,n,i,o,s){if(!cpe||!lpe||!Xg)return;let a={...Jp(t),model:e??"unknown",status_code:String(n??"error"),error:i??"unknown"};o!==void 0&&(a.http_status_code=String(o)),s!==void 0&&(a.business_code=String(s)),cpe.record(1,a);let c={...Jp(t),model:e??"unknown",http_status_code:String(o??0),error:i??"unknown"};s!=null&&(c.business_code=String(s)),lpe.record(r,c)}function MF(t,e,r,n,i){if(!Oyt||!Xg)return;let o={...Jp(t),operation:e};r!==void 0&&(o.lines=String(r)),n!==void 0&&(o.mimetype=n),i!==void 0&&(o.extension=i),Oyt.record(1,o)}function ONr(t,e,r,n,i){if(!kyt||!Pyt||!Xg)return;let o={...Jp(t),prompt_id:e,success:String(n)};i&&(o.error=i),kyt.record(1,o),Pyt.record(r,o)}function Gyt(t,e,r=!1,n=!1,i){if(!Myt||!Xg)return;let o={...Jp(t),success:String(e),had_retries:String(r),had_fixes:String(n)};i&&(o.final_error=i),Myt.record(1,o)}function kNr(t,e){if(!Lyt||!Xg)return;let r={...Jp(t),user_id:e};Lyt.record(1,r)}function PNr(t,e,r){if(!Fyt||!Xg)return;let n={...Jp(t),running_calls_count:String(e)};r.forEach((i,o)=>{n[`call_${o}_name`]=i.name,n[`call_${o}_status`]=i.status}),Fyt.record(1,n)}function jyt(t,e,r,n,i){if(!Uyt||!Xg)return;let o={...Jp(t),server_name:e,success:String(r)};n&&(o.error_type=n),i&&(o.transport_type=i),Uyt.record(1,o)}function MNr(t,e,r){if(!Qyt||!Xg)return;let n={...Jp(t),loop_type:e,prompt_id:r};Qyt.record(1,n)}function FRe(t,e,r,n,i="text",o,s){if(!qyt||!Hyt||!Xg)return;let a={};try{a=Jp(t)}catch{a={app_name:Ph,tenant__:"gen_ai",version:"unknown",platform:s||"unknown",os_model:"unknown",runtime_name:"Node.js",runtime_version:process.version,runtime_architecture:process.arch,model_name:"unknown",is_iflow_open_user:"false",ip:"unknown",iflow_env:"test",usage_mode:"unknown"}}let c={...a,success:String(n),paste_type:i};o&&(c.error_type=o),s&&(c.platform_specific=s),qyt.record(1,c);let u={...a,paste_type:i,text_length_range:String(r),performance_ratio:gco(e,r)};Hyt.record(e,u)}function gco(t,e){if(e===0)return"no-text";let r=t/e;return r<=.1?"excellent":r<=.5?"good":r<=1?"normal":r<=2?"slow":"very-slow"}var mT,Syt,wyt,Tyt,Iyt,Dyt,Ryt,Byt,cpe,lpe,Nyt,Oyt,kyt,Pyt,Myt,Lyt,Fyt,Uyt,Qyt,qyt,Hyt,Xg,Wv=Z(()=>{"use strict";Kt();bNr();ape();iE();SNr();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(mT||(mT={}));Xg=!1});var Io,yn,Do,Ro,Id=Z(()=>{"use strict";Io=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,i,o,s,a=!0,c=!1,u=[]){this.name=e,this.displayName=r,this.description=n,this.icon=i,this.kind=o,this.parameterSchema=s,this.isOutputMarkdown=a,this.canUpdateOutput=c,this.aliases=u}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(yn||(yn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(Do||(Do={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(Ro||(Ro={}))});function Aco(t){switch(t){case yn.ProceedOnce:case yn.ProceedAlways:case yn.ProceedAlwaysServer:case yn.ProceedAlwaysTool:return zv.ACCEPT;case yn.ModifyWithEditor:return zv.MODIFY;case yn.Cancel:default:return zv.REJECT}}var zv,JK,XK,ZK,eJ,tJ,b2,rJ,nJ,Yv,iJ,URe,oJ,QRe,hB=Z(()=>{"use strict";Id();iE();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(zv||(zv={}));JK=class{"event.name";"event.timestamp";model;embedding_model;sandbox_enabled;core_tools_enabled;approval_mode;api_key_enabled;vertex_ai_enabled;debug_enabled;mcp_servers;telemetry_enabled;telemetry_log_user_prompts_enabled;file_filtering_respect_git_ignore;constructor(e){let r=e.getContentGeneratorConfig(),n=e.getMcpServers(),i=!1,o=!1;r&&r.authType&&(i=r.authType===zt.IFLOW,o=r.authType===zt.AONE),this["event.name"]="cli_config",this.model=e.getModel(),this.embedding_model=e.getEmbeddingModel(),this.sandbox_enabled=typeof e.getSandbox()=="string"||!!e.getSandbox(),this.core_tools_enabled=(e.getCoreTools()??[]).join(","),this.approval_mode=e.getApprovalMode(),this.api_key_enabled=i||o,this.vertex_ai_enabled=o,this.debug_enabled=e.getDebugMode(),this.mcp_servers=n?Object.keys(n).join(","):"",this.telemetry_enabled=e.getTelemetryEnabled(),this.telemetry_log_user_prompts_enabled=e.getTelemetryLogPromptsEnabled(),this.file_filtering_respect_git_ignore=e.getFileFilteringRespectGitIgnore()}},XK=class{"event.name";"event.timestamp";session_id;constructor(e){this["event.name"]="end_session",this["event.timestamp"]=new Date().toISOString(),this.session_id=e?.getSessionId()}},ZK=class{"event.name";"event.timestamp";prompt_length;prompt_id;auth_type;prompt;constructor(e,r,n,i){this["event.name"]="user_prompt",this["event.timestamp"]=new Date().toISOString(),this.prompt_length=e,this.prompt_id=r,this.auth_type=n,this.prompt=i}},eJ=class{"event.name";"event.timestamp";function_name;function_args;duration_ms;success;decision;error;error_type;prompt_id;server_name;response_text;constructor(e){this["event.name"]="tool_call",this["event.timestamp"]=new Date().toISOString(),this.function_name=e.request.name,this.function_args=JSON.stringify(e.request.args),this.duration_ms=e.durationMs??0,this.success=e.status==="success",this.decision=e.outcome?Aco(e.outcome):void 0,this.error=e.response.error?.message,this.error_type=e.response.errorType,this.prompt_id=e.request.prompt_id,this.response_text=JSON.stringify(e.response,null,2),"tool"in e&&e.tool&&"serverName"in e.tool&&(this.server_name=e.tool.serverName)}},tJ=class{"event.name";"event.timestamp";model;prompt_id;request_text;base_url;openai_request;constructor(e,r,n,i,o){this["event.name"]="api_request",this["event.timestamp"]=new Date().toISOString(),this.model=r,this.prompt_id=i,this.request_text=o,this.base_url=e,this.openai_request=n}},b2=class{"event.name";"event.timestamp";model;error;error_type;status_code;http_status_code;business_code;duration_ms;prompt_id;auth_type;constructor(e,r,n,i,o,s,a,c,u){this["event.name"]="api_error",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.error=r,this.error_type=s,this.status_code=a,this.http_status_code=c,this.business_code=u,this.duration_ms=n,this.prompt_id=i,this.auth_type=o}},rJ=class{"event.name";"event.timestamp";model;status_code;http_status_code;business_code;duration_ms;error;input_token_count;output_token_count;cached_content_token_count;thoughts_token_count;tool_token_count;total_token_count;response_text;prompt_id;auth_type;finish_reason;constructor(e,r,n,i,o,s,a,c,u,d){this["event.name"]="api_response",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.duration_ms=r,this.status_code=200,this.http_status_code=u||200,this.business_code=d,this.input_token_count=o?.promptTokenCount??0,this.output_token_count=o?.candidatesTokenCount??0,this.cached_content_token_count=o?.cachedContentTokenCount??0,this.thoughts_token_count=o?.thoughtsTokenCount??0,this.tool_token_count=o?.toolUsePromptTokenCount??0,this.total_token_count=o?.totalTokenCount??0,this.response_text=s,this.error=a,this.prompt_id=n,this.auth_type=i,this.finish_reason=c}},nJ=class{"event.name";"event.timestamp";auth_type;constructor(e){this["event.name"]="flash_fallback",this["event.timestamp"]=new Date().toISOString(),this.auth_type=e}};(function(t){t.CONSECUTIVE_IDENTICAL_TOOL_CALLS="consecutive_identical_tool_calls",t.CHANTING_IDENTICAL_SENTENCES="chanting_identical_sentences",t.LLM_DETECTED_LOOP="llm_detected_loop"})(Yv||(Yv={}));iJ=class{"event.name";"event.timestamp";loop_type;prompt_id;constructor(e,r){this["event.name"]="loop_detected",this["event.timestamp"]=new Date().toISOString(),this.loop_type=e,this.prompt_id=r}},URe=class{"event.name";"event.timestamp";prompt_id;finish_reason;result;constructor(e,r,n){this["event.name"]="next_speaker_check",this["event.timestamp"]=new Date().toISOString(),this.prompt_id=e,this.finish_reason=r,this.result=n}},oJ=class{"event.name";"event.timestamp";command;subcommand;constructor(e,r){this["event.name"]="slash_command",this["event.timestamp"]=new Date().toISOString(),this.command=e,this.subcommand=r}},QRe=class{"event.name";"event.timestamp";model;constructor(e){this["event.name"]="malformed_json_response",this["event.timestamp"]=new Date().toISOString(),this.model=e}}});var Yn,LNr=Z(()=>{"use strict";(function(t){t[t.IFLOW_CLI_KEY_UNKNOWN=0]="IFLOW_CLI_KEY_UNKNOWN",t[t.IFLOW_CLI_START_SESSION_MODEL=1]="IFLOW_CLI_START_SESSION_MODEL",t[t.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL=2]="IFLOW_CLI_START_SESSION_EMBEDDING_MODEL",t[t.IFLOW_CLI_START_SESSION_SANDBOX=3]="IFLOW_CLI_START_SESSION_SANDBOX",t[t.IFLOW_CLI_START_SESSION_CORE_TOOLS=4]="IFLOW_CLI_START_SESSION_CORE_TOOLS",t[t.IFLOW_CLI_START_SESSION_APPROVAL_MODE=5]="IFLOW_CLI_START_SESSION_APPROVAL_MODE",t[t.IFLOW_CLI_START_SESSION_API_KEY_ENABLED=6]="IFLOW_CLI_START_SESSION_API_KEY_ENABLED",t[t.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED=7]="IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.IFLOW_CLI_START_SESSION_MCP_SERVERS=9]="IFLOW_CLI_START_SESSION_MCP_SERVERS",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED=10]="IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE=12]="IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.IFLOW_CLI_USER_PROMPT_LENGTH=13]="IFLOW_CLI_USER_PROMPT_LENGTH",t[t.IFLOW_CLI_TOOL_CALL_NAME=14]="IFLOW_CLI_TOOL_CALL_NAME",t[t.IFLOW_CLI_TOOL_CALL_DECISION=15]="IFLOW_CLI_TOOL_CALL_DECISION",t[t.IFLOW_CLI_TOOL_CALL_SUCCESS=16]="IFLOW_CLI_TOOL_CALL_SUCCESS",t[t.IFLOW_CLI_TOOL_CALL_DURATION_MS=17]="IFLOW_CLI_TOOL_CALL_DURATION_MS",t[t.IFLOW_CLI_TOOL_ERROR_MESSAGE=18]="IFLOW_CLI_TOOL_ERROR_MESSAGE",t[t.IFLOW_CLI_TOOL_CALL_ERROR_TYPE=19]="IFLOW_CLI_TOOL_CALL_ERROR_TYPE",t[t.IFLOW_CLI_API_REQUEST_MODEL=20]="IFLOW_CLI_API_REQUEST_MODEL",t[t.IFLOW_CLI_API_RESPONSE_MODEL=21]="IFLOW_CLI_API_RESPONSE_MODEL",t[t.IFLOW_CLI_API_RESPONSE_STATUS_CODE=22]="IFLOW_CLI_API_RESPONSE_STATUS_CODE",t[t.IFLOW_CLI_API_RESPONSE_DURATION_MS=23]="IFLOW_CLI_API_RESPONSE_DURATION_MS",t[t.IFLOW_CLI_API_ERROR_MESSAGE=24]="IFLOW_CLI_API_ERROR_MESSAGE",t[t.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.IFLOW_CLI_API_ERROR_MODEL=30]="IFLOW_CLI_API_ERROR_MODEL",t[t.IFLOW_CLI_API_ERROR_TYPE=31]="IFLOW_CLI_API_ERROR_TYPE",t[t.IFLOW_CLI_API_ERROR_STATUS_CODE=32]="IFLOW_CLI_API_ERROR_STATUS_CODE",t[t.IFLOW_CLI_API_ERROR_DURATION_MS=33]="IFLOW_CLI_API_ERROR_DURATION_MS",t[t.IFLOW_CLI_END_SESSION_ID=34]="IFLOW_CLI_END_SESSION_ID",t[t.IFLOW_CLI_PROMPT_ID=35]="IFLOW_CLI_PROMPT_ID",t[t.IFLOW_CLI_AUTH_TYPE=36]="IFLOW_CLI_AUTH_TYPE",t[t.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT=37]="IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.IFLOW_CLI_SURFACE=39]="IFLOW_CLI_SURFACE",t[t.IFLOW_CLI_SESSION_ID=40]="IFLOW_CLI_SESSION_ID",t[t.IFLOW_CLI_LOOP_DETECTED_TYPE=38]="IFLOW_CLI_LOOP_DETECTED_TYPE",t[t.IFLOW_CLI_SLASH_COMMAND_NAME=41]="IFLOW_CLI_SLASH_COMMAND_NAME",t[t.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND=42]="IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.IFLOW_CLI_RESPONSE_FINISH_REASON=43]="IFLOW_CLI_RESPONSE_FINISH_REASON",t[t.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.IFLOW_CLI_RESPONSE_TYPE=46]="IFLOW_CLI_RESPONSE_TYPE",t[t.IFLOW_CLI_RESPONSE_LENGTH=47]="IFLOW_CLI_RESPONSE_LENGTH",t[t.IFLOW_CLI_RESPONSE_SUCCESS=48]="IFLOW_CLI_RESPONSE_SUCCESS",t[t.IFLOW_CLI_ERROR_MESSAGE=49]="IFLOW_CLI_ERROR_MESSAGE"})(Yn||(Yn={}))});function LF(t,e){let r=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(r.has(i))return"[Circular]";r.add(i)}return i},e)}var qRe=Z(()=>{"use strict";});import AS,{dirname as yco,join as Vyt}from"node:path";import HRe from"os";import*as FNr from"crypto";import{fileURLToPath as Eco}from"node:url";import vco from"node:fs";import{execSync as bco}from"node:child_process";function yS(t){let e=HRe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function gc(t,e=35){if(t.length<=e)return t;let n=AS.parse(t).root,i=AS.sep,s=t.substring(n.length).split(i).filter(h=>h!=="");if(s.length<=1){let h=Math.floor((e-3)/2);if(h<=0)return t.substring(0,e-3)+"...";let m=t.substring(0,h),g=t.substring(t.length-h);return`${m}...${g}`}let a=s[0],c=s[s.length-1],u=n+a,d=[],f=i.length+c.length;for(let h=s.length-2;h>=0;h--){let m=s[h],g=f+i.length+m.length;if(g<=e)d.unshift(m),f=g;else break}let p=d.join(i)+i+c;return f>e?p:(p=u+i+p,p.length>e?"..."+p.substring(p.length-e-3):p)}function Dd(t,e){let r=AS.resolve(t),n=AS.resolve(e);return AS.relative(n,r)||"."}function sJ(t){let e="";for(let r=0;r<t.length;r++)t[r]===" "&&(r===0||t[r-1]!=="\\")?e+="\\ ":e+=t[r];return e}function gT(t){return t.replace(/\\(.)/g,"$1")}function GRe(t){return FNr.createHash("sha256").update(t).digest("hex")}function V1(t){let e=GRe(t);return AS.join(HRe.homedir(),Qm,Cco,e)}function jRe(){return AS.join(HRe.homedir(),Qm,UNr)}function VRe(t){return AS.join(t,Qm,UNr)}function $Re(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=yco(Eco(import.meta.url)),e=[Vyt(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),Vyt(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),Vyt(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(vco.existsSync(r))return process.platform==="darwin"&&QNr(r),r}catch{}return e[0]}function QNr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{bco(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function upe(t,e){let n=HRe.platform()==="win32"?AS.win32:AS,i=n.relative(t,e);return!i.startsWith(`..${n.sep}`)&&i!==".."&&!n.isAbsolute(i)}var Qm,$yt,Cco,UNr,Rd=Z(()=>{"use strict";Qm=".iflow",$yt="google_accounts.json",Cco="tmp",UNr="commands"});import _co from"node:path";import{promises as sMa,existsSync as qNr,readFileSync as HNr}from"node:fs";import*as GNr from"os";function jNr(){return _co.join(GNr.homedir(),Qm,$yt)}function VNr(){try{let t=jNr();if(qNr(t)){let e=HNr(t,"utf-8").trim();return e?JSON.parse(e).active:null}return null}catch(t){return console.debug("Error reading cached Google Account:",t),null}}function $Nr(){try{let t=jNr();if(!qNr(t))return 0;let e=HNr(t,"utf-8").trim();if(!e)return 0;let r=JSON.parse(e),n=r.old.length;return r.active&&n++,n}catch(t){return console.debug("Error reading lifetime Google Accounts:",t),0}}var WNr=Z(()=>{"use strict";Rd();});import*as zNr from"os";import*as AT from"fs";import*as Yyt from"path";import{randomUUID as xco}from"crypto";function wco(){AT.existsSync(Wyt)||AT.mkdirSync(Wyt,{recursive:!0})}function Tco(){return AT.existsSync(zyt)&&AT.readFileSync(zyt,"utf-8").trim()||null}function Ico(t){AT.writeFileSync(zyt,t,"utf-8")}function WRe(){try{wco();let t=Tco();return t||(t=xco(),Ico(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var Sco,Wyt,zyt,Kyt=Z(()=>{"use strict";Rd();Sco=zNr.homedir()??"",Wyt=Yyt.join(Sco,Qm),zyt=Yyt.join(Wyt,"installation_id")});var YNr,Dco,Rco,Bco,Nco,Oco,kco,Pco,Mco,Lco,Fco,Uco,Qco,qco,Mh,dpe=Z(()=>{"use strict";YNr=Te(qct(),1);hB();LNr();qRe();WNr();Kyt();Dco="start_session",Rco="new_prompt",Bco="tool_call",Nco="api_request",Oco="api_response",kco="api_error",Pco="end_session",Mco="flash_fallback",Lco="loop_detected",Fco="next_speaker_check",Uco="slash_command",Qco="malformed_json_response",qco="cli_response",Mh=class t{static instance;config;events=[];last_flush_time=Date.now();flush_interval_ms=1e3*60;constructor(e){this.config=e}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}enqueueLogEvent(e){this.events.push([{event_time_ms:Date.now(),source_extension_json:LF(e)}])}createLogEvent(e,r){let n=VNr(),i=$Nr();r.push({iflow_cli_key:Yn.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT,value:i.toString()});let o={console_type:"IFLOW_CLI",application:102,event_name:e,event_metadata:[r]};return n?o.client_email=n:o.client_install_id=WRe(),o}flushIfNeeded(){Date.now()-this.last_flush_time<this.flush_interval_ms||this.flushToClearcut().catch(e=>{console.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){return this.config?.getDebugMode()&&console.log("Telemetry disabled - not sending log events to Clearcut."),this.events.length=0,this.last_flush_time=Date.now(),Promise.resolve({})}decodeLogResponse(e){if(e.length<1||e.readUInt8(0)!==8)return;let r=BigInt(0),n=!0;for(let o=1;n&&o<e.length;o++){let s=e.readUInt8(o);r|=BigInt(s&127)<<BigInt(7*(o-1)),n=(s&128)!==0}return n?void 0:{nextRequestWaitMs:Number(r)}}handleLogEvent(e,r,n=!1){this.enqueueLogEvent(this.createLogEvent(e,r)),n?this.flushToClearcut().catch(i=>{console.debug("Error flushing to Clearcut:",i)}):this.flushIfNeeded()}logStartSessionEvent(e){let r=process.env.SURFACE||"SURFACE_NOT_SET",n=[{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_MODEL,value:e.model},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{iflow_cli_key:Yn.IFLOW_CLI_SURFACE,value:r}];this.handleLogEvent(Dco,n,!0)}logNewPromptEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Rco,r)}logToolCallEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Yn.IFLOW_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)}];this.handleLogEvent(Bco,r)}logApiRequestEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)}];this.handleLogEvent(Nco,r)}logApiResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.input_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.output_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.cached_content_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.thoughts_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.tool_token_count)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Oco,r)}logApiErrorEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Yn.IFLOW_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(kco,r)}logFlashFallbackEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Mco,r,!0)}logLoopDetectedEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];this.handleLogEvent(Lco,r)}logNextSpeakerCheck(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{iflow_cli_key:Yn.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)},{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Fco,r)}logSlashCommandEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({iflow_cli_key:Yn.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),this.handleLogEvent(Uco,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(Qco,r)}logCliResponseEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_TYPE,value:JSON.stringify(e.response_type)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_LENGTH,value:JSON.stringify(e.response_length)},{iflow_cli_key:Yn.IFLOW_CLI_RESPONSE_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Yn.IFLOW_CLI_ERROR_MESSAGE,value:JSON.stringify(e.error)}];this.handleLogEvent(qco,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Yn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Pco,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new YNr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new XK(this.config);this.logEndSessionEvent(e)}}});import*as KNr from"node:fs";var FF,JNr,fpe,zRe,YRe,KRe,XNr=Z(()=>{"use strict";FF=Te(si(),1),JNr=Te(Bx(),1);fpe=class{writeStream;constructor(e){this.writeStream=KNr.createWriteStream(e,{flags:"a"})}serialize(e){let r=new WeakSet;return JSON.stringify(e,(i,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular]";r.add(o)}return o},2)+`
|
|
486
486
|
`}shutdown(){return new Promise(e=>{this.writeStream.end(e)})}},zRe=class extends fpe{export(e,r){let n=e.map(i=>this.serialize(i)).join("");this.writeStream.write(n,i=>{r({code:i?FF.ExportResultCode.FAILED:FF.ExportResultCode.SUCCESS,error:i||void 0})})}},YRe=class extends fpe{export(e,r){let n=e.map(i=>this.serialize(i)).join("");this.writeStream.write(n,i=>{r({code:i?FF.ExportResultCode.FAILED:FF.ExportResultCode.SUCCESS,error:i||void 0})})}},KRe=class extends fpe{export(e,r){let n=this.serialize(e);this.writeStream.write(n,i=>{r({code:i?FF.ExportResultCode.FAILED:FF.ExportResultCode.SUCCESS,error:i||void 0})})}getPreferredAggregationTemporality(){return JNr.AggregationTemporality.CUMULATIVE}async forceFlush(){return Promise.resolve()}}});function C2(){return aJ}function Hco(t){if(!t)return;let e=t.replace(/^["']|["']$/g,"");try{let r=new URL(e),i=r.port==="4318"||r.protocol==="http:"||r.protocol==="https:"?"http":"grpc";return{url:i==="grpc"?r.origin:e,protocol:i}}catch(r){_f.error("Invalid OTLP endpoint URL provided:",e,r);return}}function eBe(t){if(aJ)return;let e=(0,XRe.defaultResource)().merge((0,XRe.resourceFromAttributes)({[Wdt]:Ph,[zdt]:process.version,"session.id":t.getSessionId()})),r=t.getTelemetryOtlpEndpoint(),n=Hco(r),i=!!n,o=t.getTelemetryOutfile(),s=[];i&&s.push(new ZNr.OTLPTraceExporter({url:`${n.url}/v1/traces`})),o&&s.push(new zRe(o));let a=[];i&&n&&a.push(new tOr.OTLPLogExporter({url:`${n.url}/v1/logs`})),o&&a.push(new YRe(o));let c=[];i&&c.push(new jIe({exporter:new eOr.OTLPMetricExporter({url:`${n.url}/v1/metrics`,temporalityPreference:ZRe.AggregationTemporality.DELTA}),exportIntervalMillis:2e4})),o&&c.push(new ZRe.PeriodicExportingMetricReader({exporter:new KRe(o),exportIntervalMillis:1e4}));let u={resource:e,serviceName:Ph,logRecordProcessors:[],spanProcessors:[],metricReaders:[]};s.forEach(d=>{u.spanProcessors.push(new nOr.BatchSpanProcessor(d,{exportTimeoutMillis:1e4}))}),a.forEach(d=>{u.logRecordProcessors.push(new iOr.BatchLogRecordProcessor(d,{exportTimeoutMillis:1e4}))}),c.forEach(d=>{u.metricReaders.push(d)}),JRe=new rOr.NodeSDK({...u});try{JRe.start(),aJ=!0,TNr()}catch(d){console.error("Error starting OpenTelemetry SDK:",d)}process.on("SIGTERM",cJ),process.on("SIGINT",cJ)}async function oOr(){if(aJ)try{let{trace:t}=await Promise.resolve().then(()=>(Kt(),ar)),e=t.getTracerProvider();"forceFlush"in e&&await e.forceFlush();let{metrics:r}=await Promise.resolve().then(()=>(Kt(),ar)),n=r.getMeterProvider();"forceFlush"in n&&await n.forceFlush()}catch(t){process.env.DEBUG&&console.error("Error flushing telemetry:",t)}}async function cJ(){if(!(!aJ||!JRe))try{Mh.getInstance()?.shutdown(),await JRe.shutdown()}catch(t){console.error("Error shutting down SDK:",t)}finally{aJ=!1}}var ZNr,eOr,tOr,rOr,XRe,nOr,iOr,ZRe,JRe,aJ,tBe=Z(()=>{"use strict";Kt();ZNr=Te(nht(),1),eOr=Te(lht(),1),tOr=Te(dht(),1),rOr=Te(OIr(),1);PIr();Nh();XRe=Te(U3t(),1),nOr=Te(E9e(),1),iOr=Te($Br(),1),ZRe=Te(Bx(),1);ape();Wv();dpe();XNr();process.env.DEBUG?_f.setLogger(new Mue,Vp.DEBUG):_f.setLogger(new Mue,Vp.NONE);aJ=!1});var sOr={};qs(sOr,{TraceContext:()=>yT});var yT,Jyt=Z(()=>{"use strict";Kt();tBe();yT=class{static rootSpan=null;static tracer=U1.getTracer("iflow-cli-tracer");static spanLock=null;static startRootSpan(e="iflow_cli_request",r=!1){return this.rootSpan&&r&&(this.rootSpan.end(),this.rootSpan=null),this.rootSpan||(this.rootSpan=this.tracer.startSpan(e)),this.rootSpan}static async withRootSpan(e,r){let n=r?this.startRootSpan(r):this.getRootSpan();return n?s2.with(U1.setSpan(s2.active(),n),async()=>{try{return await e()}catch(i){throw n.recordException(i),n.setStatus({code:xv.ERROR,message:i.message}),i}}):e()}static startChildSpan(e){return this.tracer.startSpan(e)}static async withChildSpan(e,r,n){let i=this.startChildSpan(e);return n&&i.setAttributes(n),s2.with(U1.setSpan(s2.active(),i),async()=>{try{let o=await r();return i.setStatus({code:xv.OK}),o}catch(o){throw i.recordException(o),i.setStatus({code:xv.ERROR,message:o.message}),o}finally{i.end()}})}static getRootSpan(){return this.rootSpan}static async endRootSpan(){this.spanLock&&await this.spanLock,this.spanLock=(async()=>{if(this.rootSpan){let e=this.rootSpan;this.rootSpan=null,e.end();try{await oOr()}catch{}}})(),await this.spanLock,this.spanLock=null}static getActiveSpan(){return U1.getActiveSpan()}static setSpanAttributes(e){let r=this.getActiveSpan();r&&r.setAttributes(e)}static addSpanEvent(e,r){let n=this.getActiveSpan();n&&n.addEvent(e,r)}}});function ppe(){let t=U1.getActiveSpan();if(t){let r=t.spanContext();if(r&&r.traceId&&r.spanId){let i=r.traceId,o=r.spanId,s=(r.traceFlags||0).toString(16).padStart(2,"0");return`00-${i}-${o}-${s}`}}return qF.getCurrentSession()?.traceparent}function hpe(t){let e=ppe();return e?{...t,traceparent:e}:t}function Xyt(){return ppe()}async function UF(t,e,r){let n=U1.getTracer("iflow-cli"),{TraceContext:i}=await Promise.resolve().then(()=>(Jyt(),sOr)),o=i.getRootSpan(),s;if(o){let a=U1.setSpan(s2.active(),o);s=s2.with(a,()=>n.startSpan(t,{attributes:e}))}else s=n.startSpan(t,{attributes:e});try{return await s2.with(U1.setSpan(s2.active(),s),r)}catch(a){throw s.recordException(a),s.setStatus({code:xv.ERROR,message:a instanceof Error?a.message:"Unknown error"}),a}finally{s.end()}}var QF=Z(()=>{"use strict";Kt();rBe();});var nBe,qF,rBe=Z(()=>{"use strict";udt();ddt();QF();nBe=class{currentSession=null;async startSession(e,r,n,i){let{model:o,tool:s}=i||{},a="iflow",c="cli",u=B_e(),d=Rz(),f=`${a}.${c}.${n}.${u}`,p=Agr(u,d),h=Date.now();this.currentSession={traceId:u,parent_observation_id:d,conversationId:n,sessionId:e,userId:r,pid:a,sceneId:c,sam:f,traceparent:p,startTime:h,model:o,tool:s};let m={gmkey:"AI",gokey:this.stringifyGokey({pid:a,sam:f,trace_id:u,observation_id:d,model:o,tool:s,sessionId:e,user_id:r})};return await Bue("/aitrack.lifecycle.run_started",m),this.currentSession}async endSession(){if(!this.currentSession)return;let{pid:e,sam:r,traceId:n,parent_observation_id:i,model:o,tool:s,sessionId:a,userId:c,startTime:u}=this.currentSession,d=Date.now()-u,f=Rz(),p={gmkey:"AI",gokey:this.stringifyGokey({pid:e,sam:r,trace_id:n,observation_id:f,parent_observation_id:i,duration:d,model:o,tool:s,sessionId:a,user_id:c})};await Bue("/aitrack.lifecycle.run_finished",p),this.currentSession=null}async recordError(e){if(!this.currentSession)throw new Error("No active session to record error");let{pid:r,sam:n,traceId:i,parent_observation_id:o,model:s,tool:a,sessionId:c,userId:u}=this.currentSession,d=Rz(),f="",p="";e instanceof Error?(f=e.cause?`${e.message}:${e.cause.message}`:e.message,p=e.cause?e.cause.stack||"":e.stack||""):f=String(e);let h=ppe(),m=i;if(h){let A=h.split("-");A.length>=2&&(m=A[1])}let g={gmkey:"AI",gokey:this.stringifyGokey({pid:r,sam:n,trace_id:m,observation_id:d,parent_observation_id:o,error_msg:`${f}
|
|
487
|
-
${p.slice(0,500)}`,model:s,tool:a,sessionId:c,cliVer:"0.3.24
|
|
487
|
+
${p.slice(0,500)}`,model:s,tool:a,sessionId:c,cliVer:"0.3.24",user_id:u})};await Bue("/aitrack.lifecycle.run_error",g)}getCurrentSession(){return this.currentSession}stringifyGokey(e){return Object.entries(e).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`).join("&")}},qF=new nBe});var aOr=w((MMa,Gco)=>{Gco.exports={name:"systeminformation",version:"5.27.11",description:"Advanced, lightweight system and OS information library",license:"MIT",author:"Sebastian Hildebrandt <hildebrandt@plus-innovations.com> (https://plus-innovations.com)",homepage:"https://systeminformation.io",main:"./lib/index.js",type:"commonjs",bin:{systeminformation:"lib/cli.js"},types:"./lib/index.d.ts",scripts:{test:"node ./test/test.js",testDeno:"deno run -A ./test/test.js"},files:["lib/"],keywords:["system information","sysinfo","monitor","monitoring","os","linux","osx","windows","freebsd","openbsd","netbsd","cpu","cpuload","physical cores","logical cores","processor","cores","threads","socket type","memory","file system","fsstats","diskio","block devices","netstats","network","network interfaces","network connections","network stats","iface","printer","processes","users","internet","battery","docker","docker stats","docker processes","graphics","graphic card","graphic controller","gpu","display","smart","disk layout","usb","audio","bluetooth","wifi","wifinetworks","virtual box","virtualbox","vm","backend","hardware","BIOS","chassis"],repository:{type:"git",url:"git+https://github.com/sebhildebrandt/systeminformation.git"},funding:{type:"Buy me a coffee",url:"https://www.buymeacoffee.com/systeminfo"},os:["darwin","linux","win32","freebsd","openbsd","netbsd","sunos","android"],engines:{node:">=8.0.0"}}});var Xp=w(Ii=>{"use strict";var uJ=Ae("os"),o5=Ae("fs"),jco=Ae("path"),oEt=Ae("child_process").spawn,Vco=Ae("child_process").exec,dJ=Ae("child_process").execSync,$co=Ae("util"),GF=process.platform,sEt=GF==="linux"||GF==="android",uOr=GF==="darwin",aBe=GF==="win32",dOr=GF==="freebsd",fOr=GF==="openbsd",pOr=GF==="netbsd",Zyt=0,HF="",n5="",mB=null,i5=null,aEt=process.env.WINDIR||"C:\\Windows",Lh,lJ="",mpe=[],cEt=!1,oBe="",Wco="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",tEt="--###START###--",cOr="--ERROR--",sBe="--###ENDCMD###--",rEt="--##ID##--",gpe={windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},cBe={maxBuffer:1024*2e4,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function zco(t){let e=parseInt(t,10);return isNaN(e)&&(e=0),e}function Yco(t){let e=!1,r="",n="";for(let i of t)i>="0"&&i<="9"||e?(e=!0,r+=i):n+=i;return[n,r]}var iBe=new String,nEt=new String().replace,iEt=new String().toLowerCase,hOr=new String().toString,mOr=new String().substr,gOr=new String().substring,AOr=new String().trim,yOr=new String().startsWith,EOr=Math.min;function Kco(t){return t&&{}.toString.call(t)==="[object Function]"}function Jco(t){let e=[],r={};for(let n=0;n<t.length;n++){let i=Object.keys(t[n]);i.sort(function(s,a){return s-a});let o="";for(let s=0;s<i.length;s++)o+=JSON.stringify(i[s]),o+=JSON.stringify(t[n][i[s]]);({}).hasOwnProperty.call(r,o)||(e.push(t[n]),r[o]=!0)}return e}function Xco(t,e){return t.sort(function(r,n){let i="",o="";return e.forEach(function(s){i=i+r[s],o=o+n[s]}),i<o?-1:i>o?1:0})}function Zco(){return Zyt===0&&(Zyt=uJ.cpus().length),Zyt}function gB(t,e,r,n,i){r=r||":",e=e.toLowerCase(),n=n||!1,i=i||!1;let o="";return t.some(s=>{let a=s.toLowerCase().replace(/\t/g,"");if(n&&(a=a.trim()),a.startsWith(e)&&(!i||a.match(e+r)||a.match(e+" "+r))){let c=n?s.trim().split(r):s.split(r);if(c.length>=2)return c.shift(),o=c.join(r).trim(),!0}}),o}function elo(t,e){return e=e||16,t.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],e))})}function tlo(t){let e="",r=0;return t.split("").forEach(n=>{n>="0"&&n<="9"?r===1&&r++:(r===0&&r++,r===1&&(e+=n))}),e}function rlo(t,e){e=e||"",t=t.toUpperCase();let r=0,n=0,i=tlo(t),o=t.split(i);if(o.length>=2){o[2]&&(o[1]+=o[2]);let s=o[1]&&o[1].toLowerCase().indexOf("pm")>-1||o[1].toLowerCase().indexOf("p.m.")>-1||o[1].toLowerCase().indexOf("p. m.")>-1||o[1].toLowerCase().indexOf("n")>-1||o[1].toLowerCase().indexOf("ch")>-1||o[1].toLowerCase().indexOf("\xF6s")>-1||e&&o[1].toLowerCase().indexOf(e)>-1;return r=parseInt(o[0],10),n=parseInt(o[1],10),r=s&&r<12?r+12:r,("0"+r).substr(-2)+":"+("0"+n).substr(-2)}}function nlo(t,e){let r={date:"",time:""};e=e||{};let n=(e.dateFormat||"").toLowerCase(),i=e.pmDesignator||"",o=t.split(" ");if(o[0]){if(o[0].indexOf("/")>=0){let s=o[0].split("/");s.length===3&&(s[0].length===4?r.date=s[0]+"-"+("0"+s[1]).substr(-2)+"-"+("0"+s[2]).substr(-2):s[2].length===2?(n.indexOf("/d/")>-1||n.indexOf("/dd/")>-1,r.date="20"+s[2]+"-"+("0"+s[1]).substr(-2)+"-"+("0"+s[0]).substr(-2)):(t.toLowerCase().indexOf("pm")>-1||t.toLowerCase().indexOf("p.m.")>-1||t.toLowerCase().indexOf("p. m.")>-1||t.toLowerCase().indexOf("am")>-1||t.toLowerCase().indexOf("a.m.")>-1||t.toLowerCase().indexOf("a. m.")>-1||n.indexOf("/d/")>-1||n.indexOf("/dd/")>-1)&&n.indexOf("dd/")!==0?r.date=s[2]+"-"+("0"+s[0]).substr(-2)+"-"+("0"+s[1]).substr(-2):r.date=s[2]+"-"+("0"+s[1]).substr(-2)+"-"+("0"+s[0]).substr(-2))}if(o[0].indexOf(".")>=0){let s=o[0].split(".");s.length===3&&(n.indexOf(".d.")>-1||n.indexOf(".dd.")>-1?r.date=s[2]+"-"+("0"+s[0]).substr(-2)+"-"+("0"+s[1]).substr(-2):r.date=s[2]+"-"+("0"+s[1]).substr(-2)+"-"+("0"+s[0]).substr(-2))}if(o[0].indexOf("-")>=0){let s=o[0].split("-");s.length===3&&(r.date=s[0]+"-"+("0"+s[1]).substr(-2)+"-"+("0"+s[2]).substr(-2))}}if(o[1]){o.shift();let s=o.join(" ");r.time=rlo(s,i)}return r}function ilo(t,e){let r=e>0,n=1,i=0,o=0,s=[];for(let c=0;c<t.length;c++)n<=e?(/\s/.test(t[c])&&!r&&(o=c-1,s.push({from:i,to:o+1,cap:t.substring(i,o+1)}),i=o+2,n++),r=t[c]===" "):(!/\s/.test(t[c])&&r&&(o=c-1,i<o&&s.push({from:i,to:o,cap:t.substring(i,o)}),i=o+1,n++),r=t[c]===" ");o=5e3,s.push({from:i,to:o,cap:t.substring(i,o)});let a=s.length;for(let c=0;c<a;c++)s[c].cap.replace(/\s/g,"").length===0&&c+1<a&&(s[c].to=s[c+1].to,s[c].cap=s[c].cap+s[c+1].cap,s.splice(c+1,1),a=a-1);return s}function olo(t,e,r){for(let n=0;n<t.length;n++)if(t[n][e]===r)return n;return-1}function slo(){if(oBe="powershell.exe",aBe){let t=`${aEt}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;o5.existsSync(t)&&(oBe=t)}}function vOr(){if(uJ.type()==="Windows_NT"&&!HF&&(HF=aEt+"\\system32\\wbem\\wmic.exe",!o5.existsSync(HF)))try{let t=dJ("WHERE WMIC",gpe).toString().split(`\r
|
|
488
488
|
`);t&&t.length?HF=t[0]:HF="wmic"}catch{HF="wmic"}return HF}function alo(t){return new Promise(e=>{process.nextTick(()=>{try{bOr(vOr()+" "+t).then(r=>{e(r,"")})}catch(r){e("",r)}})})}function clo(){return aBe?`"${process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"`:"vboxmanage"}function eEt(t){let e="",r,n="";if(t.indexOf(tEt)>=0){r=t.split(tEt);let o=r[1].split(rEt);e=o[0],o.length>1&&(t=o.slice(1).join(rEt))}t.indexOf(sBe)>=0&&(r=t.split(sBe),n=r[0]);let i=-1;for(let o=0;o<mpe.length;o++)mpe[o].id===e&&(i=o,mpe[o].callback(n));i>=0&&mpe.splice(i,1)}function llo(){Lh||(Lh=oEt(oBe,["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-Command","-"],{stdio:"pipe",windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})}),Lh&&Lh.pid&&(cEt=!0,Lh.stdout.on("data",function(t){lJ=lJ+t.toString("utf8"),t.indexOf(sBe)>=0&&(eEt(lJ),lJ="")}),Lh.stderr.on("data",function(){eEt(lJ+cOr)}),Lh.on("error",function(){eEt(lJ+cOr)}),Lh.on("close",function(){Lh&&Lh.kill()})))}function ulo(){try{Lh&&(Lh.stdin.write("exit"+uJ.EOL),Lh.stdin.end(),cEt=!1)}catch{Lh&&Lh.kill()}Lh=null}function bOr(t){if(cEt){let e=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function n(i){r(i)}mpe.push({id:e,cmd:t,callback:n,start:new Date});try{Lh&&Lh.pid&&Lh.stdin.write(Wco+"echo "+tEt+e+rEt+"; "+uJ.EOL+t+uJ.EOL+"echo "+sBe+uJ.EOL)}catch{r("")}})})}else{let e="";return new Promise(r=>{process.nextTick(()=>{try{let n=oEt(oBe,["-NoProfile","-NoLogo","-InputFormat","Text","-ExecutionPolicy","Unrestricted","-Command",t],{stdio:"pipe",windowsHide:!0,maxBuffer:2048e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})});n&&!n.pid&&n.on("error",function(){r(e)}),n&&n.pid?(n.stdout.on("data",function(i){e=e+i.toString("utf8")}),n.stderr.on("data",function(){n.kill(),r(e)}),n.on("close",function(){n.kill(),r(e)}),n.on("error",function(){n.kill(),r(e)})):r(e)}catch{r(e)}})})}}function dlo(t,e,r){let n="";return r=r||{},new Promise(i=>{process.nextTick(()=>{try{let o=oEt(t,e,r);o&&!o.pid&&o.on("error",function(){i(n)}),o&&o.pid?(o.stdout.on("data",function(s){n+=s.toString()}),o.on("close",function(){o.kill(),i(n)}),o.on("error",function(){o.kill(),i(n)})):i(n)}catch{i(n)}})})}function flo(){if(aBe){if(!n5)try{let r=dJ("chcp",gpe).toString().split(`\r
|
|
489
489
|
`)[0].split(":");n5=r.length>1?r[1].replace(".","").trim():""}catch{n5="437"}return n5}if(sEt||uOr||dOr||fOr||pOr){if(!n5)try{let r=dJ("echo $LANG",cBe).toString().split(`\r
|
|
490
490
|
`)[0].split(".");n5=r.length>1?r[1].trim():"",n5||(n5="UTF-8")}catch{n5="UTF-8"}return n5}}function plo(){if(mB!==null)return mB;if(mB=!1,aBe)try{let t=dJ("WHERE smartctl 2>nul",gpe).toString().split(`\r
|
|
@@ -934,7 +934,7 @@ ${JSON.stringify(e,null,2)}`;try{let i=APr.dirname(this.logFilePath);await gPr.m
|
|
|
934
934
|
[${new Date().toISOString()}]
|
|
935
935
|
${n}
|
|
936
936
|
${"=".repeat(80)}
|
|
937
|
-
`;await gPr.appendFile(this.logFilePath,s,"utf-8")}catch(i){console.debug(R.t("openaiContentGenerator.errors.failedWriteDebugLog"),i)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);I3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return UF("model_call",n,async()=>this.generateContentInternal(e,r))}async generateContentInternal(e,r){let n=wT.api;n.start("OpenAI-GenerateContent-Total");let i=!1;try{if((this.authType===zt.LOGIN_WITH_IFLOW||this.authType===zt.IFLOW)&&await Tz()){this.authType===zt.LOGIN_WITH_IFLOW&&await w_e();let{getCachedApiKey:T}=await Promise.resolve().then(()=>(xR(),tdt)),B=await T();B&&(this.apiKey=B)}let o=await this.convertToOpenAIMessages(e),s=uPr(o);if(this.config){let O=this.config.getConversationId();if(O)try{await zEt(this.config,O,{model:this.modelName,tool:s})}catch(T){this.logTelemetryFailure("Telemetry initialization failed",T)}}let a=this.convertToOpenAITools(e.config?.tools),c={model:this.modelName,messages:o},u=!1;this.config?.getTemperature()!==void 0&&this.config.getTemperature()!==-1?(c.temperature=this.config.getTemperature(),u=!0):e.config?.temperature!==void 0&&(this.config?.getTemperature()===void 0||this.config.getTemperature()!==-1)&&(c.temperature=e.config.temperature,u=!0),u||(this.config?.getTopP()!==void 0&&this.config.getTopP()!==-1?c.top_p=this.config.getTopP():e.config?.topP!==void 0&&(this.config?.getTopP()===void 0||this.config.getTopP()!==-1)&&(c.top_p=e.config.topP));let d=this.config?.getContentGeneratorConfig?.();d?.thinking&&d.thinking.maxTokens>0?(eNe.configureThinkingRequest(this.modelName,c,d.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),d.thinking=null):eNe.configureNonThinkingRequest(this.modelName,c);let f=await this.calculateInputTokens(e),p=e4t(this.modelName,f),h="global";h==="aone"&&(c.max_tokens=p),c.max_new_tokens=p,e.config?.stopSequences&&e.config.stopSequences.length>0&&(c.stop=e.config.stopSequences),a&&a.length>0&&(c.tools=a),await this.logToPromptFile(c,"INPUT REQUEST");let m=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl;["offline-whale-wave.alibaba-inc.com","whale.wave.vipserver.offline","whale-wave.alibaba-inc.com","pre-whale-wave.alibaba-inc.com","internal-offline-whale-wave.alibaba-inc.com","internal-whale-wave.alibaba-inc.com"].some(O=>m.includes(O))&&(c.extend_fields={sessionId:this.config?.getSessionId()||""});let A=Date.now(),y=Xyt(),E={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"user-agent":"iFlow-Cli","session-id":this.config?.getSessionId()||"","conversation-id":this.config?.getConversationId()||""};y&&(E={...E,traceparent:y}),h==="aone"&&(E={...E,"X-Client-Type":"iflow-cli","X-Client-Version":"0.3.24-beta.0"}),VBe(this.config,new tJ(this.baseUrl,this.modelName,JSON.stringify(c),r,JSON.stringify(e.contents)));let v=await fetch(`${m}/chat/completions`,{signal:e.config?.abortSignal,method:"POST",headers:E,body:JSON.stringify(c)}),C=Date.now()-A;if(!v.ok){let O=await v.text();if(this.config)try{await qBe(this.config,new Error(O)),D3(this.config,new b2(this.modelName,O,C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",v.status,v.status,void 0))}catch(T){this.logTelemetryFailure("Telemetry error recording failed",T)}throw v.status===511?(this.config&&D3(this.config,new b2(this.modelName,"Content length exceeded",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(R.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:y||v.headers.get("eagleeye-traceid")}))):v.status===514?(this.config&&D3(this.config,new b2(this.modelName,"model_error",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(R.t("openaiContentGenerator.errors.modelError",{traceId:y||v.headers.get("eagleeye-traceid")}))):v.status===429?(this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(R.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(R.t("openaiContentGenerator.errors.httpError",{status:v.status,body:O,traceId:y||v.headers.get("eagleeye-traceid")}))}let S;try{S=await v.json()}catch(O){throw I3(O),new Error(R.t("openaiContentGenerator.errors.responseFormatError",{traceId:y||v.headers.get("eagleeye-traceid")}))}if(S.error_code&&(S.error_code===511||S.error_code===413))throw this.config&&D3(this.config,new b2(this.modelName,"Content length exceeded",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",S.error_code,200,S.error_code)),new Error(R.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:y||v.headers.get("eagleeye-traceid")}));if(S.error_code&&S.error_code===514)throw this.config&&D3(this.config,new b2(this.modelName,"model_error",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(R.t("openaiContentGenerator.errors.modelError",{traceId:y||v.headers.get("eagleeye-traceid")}));if(S.status&&S.status==="439"||S.error_code&&S.error_code===439)throw this.config&&D3(this.config,new b2(this.modelName,"API token expired",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(R.t("openaiContentGenerator.errors.apiTokenExpired"));if(S.msg&&(S.msg.includes("invalid apiKey")||S.msg.includes("Invalid apiKey")))throw new Error(R.t("openaiContentGenerator.errors.invalidApiKey"));if(S.status&&(S.status==="434"||S.status===434))throw this.config&&D3(this.config,new b2(this.modelName,"Invalid API key",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(R.t("openaiContentGenerator.errors.invalidApiKey"));if(S.status&&(S.status==="435"||S.status===435))throw this.config&&D3(this.config,new b2(this.modelName,"Model Not Support",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(R.t("openaiContentGenerator.errors.modelNotSupport"));if(S.status&&S.status==="429"||S.error_code&&(S.error_code===429||S.error_code===8211))throw this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",S.error_code||S.status||429,200,S.error_code||S.status||429)),new Error(R.t("openaiContentGenerator.errors.modelRateLimitReached"));if(S.status&&S.status==="449"||S.error_code&&S.error_code===449)throw this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(R.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(R.t("openaiContentGenerator.errors.userCancel"));if(!S||!S.choices||!Array.isArray(S.choices)||S.choices.length===0){let O=y||v.headers.get("eagleeye-traceid");throw new Error(R.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:O}))}await this.logToPromptFile(S,"API RESPONSE"),S.usage&&(this.lastUsageMetadata={total_tokens:S.usage.total_tokens,prompt_tokens:S.usage.prompt_tokens,completion_tokens:S.usage.completion_tokens});let{response:D,hadJsonFixes:I}=await this.convertFromOpenAIResponse(S);if(i=I,this.config)try{let O=S.choices[0]?.finish_reason;WBe(this.config,new rJ(this.modelName,C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,S.usage?{promptTokenCount:S.usage.prompt_tokens||0,candidatesTokenCount:S.usage.completion_tokens||0,totalTokenCount:S.usage.total_tokens||0,cachedContentTokenCount:0,thoughtsTokenCount:0,toolUsePromptTokenCount:0}:void 0,JSON.stringify(S,null,2),void 0,O,200,void 0)),await Fpe(this.config),Gyt(this.config,!0,!1,i)}catch(O){this.logTelemetryFailure("Telemetry cleanup failed",O)}return D}catch(o){if(I3(o),this.config&&!(o instanceof Error&&o.message==="user cancel")&&(await qBe(this.config,o instanceof Error?o:new Error(String(o))),Gyt(this.config,!1,!1,i,o instanceof Error?o.message:String(o))),o instanceof Error&&o.cause?.name?.includes("InvalidArgumentError"))throw new Error(R.t("openaiContentGenerator.errors.apiKeyError"));if(o instanceof Error&&o.message&&["iFlow Login expired","Your iFlow Login expired","Your API Token has expired","platform rate limit","platform concurrency limit","Your input has exceeded","the network is unavailable","\u60A8\u7684 iFlow \u767B\u5F55\u5DF2\u8FC7\u671F","\u767B\u5F55\u5DF2\u8FC7\u671F","API Token \u5DF2\u8FC7\u671F","API Token\u5DF2\u8FC7\u671F","\u5E73\u53F0\u901F\u7387\u9650\u5236","\u5E73\u53F0\u5E76\u53D1\u9650\u5236","\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6","\u60A8\u7684\u8F93\u5165\u5DF2\u8D85\u51FA","\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"].some(c=>o.message.includes(c)))throw new Error(o.message);let s="";throw o instanceof Error?s=o.cause?`${o.message}:${o.cause.message}`:o.message:s=String(o),new Error(R.t("openaiContentGenerator.errors.generateDataError",{error:s}),{cause:o})}finally{n.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e,r){let n=await this.generateContent(e,r);async function*i(){yield n}return i()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let i=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(i.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,i=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!i.ok){let s=await i.text();throw new Error(`HTTP error! status: ${i.status}, body: ${s}`)}return{embeddings:[{values:(await i.json()).data[0].embedding}]}}catch(r){throw I3(r),new Error(R.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}async convertToOpenAIMessages(e){let r=[],n=new Set,i=new Map;if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o)if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];for(let c of a){if(c.functionCall){let u=c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(u)}if(c.functionResponse){let u=c.functionResponse.id||c.functionResponse.name||"",d=c.functionResponse.response?.output??(c.functionResponse.response?JSON.stringify(c.functionResponse.response):"");i.set(u,{role:"tool",tool_call_id:u,content:d})}}}for(let[s]of i)n.has(s)||i.delete(s)}if(e.config?.systemInstruction){let o=this.extractSystemInstruction(e.config.systemInstruction);o&&r.push({role:"system",content:o})}if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o){if(typeof s=="string"){r.push({role:"user",content:s});continue}if(typeof s=="object"&&s!==null&&"text"in s&&s.text){r.push({role:"user",content:s.text});continue}if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];if(s.role==="model"){let c={role:"assistant",content:"",tool_calls:[]};for(let u of a)if("text"in u&&u.text&&(c.content=u.text),u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;c.tool_calls.push({id:d,function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})},type:"function"})}if((c.content||c.tool_calls.length>0)&&(c.tool_calls.length===0&&delete c.tool_calls,r.push(c),c.tool_calls&&c.tool_calls.length>0))for(let u of c.tool_calls){let d=i.get(u.id);d?r.push(d):r.push({role:"tool",tool_call_id:u.id,content:R.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let c=[];for(let u of a)if("text"in u&&u.text)c.push({type:"text",text:u.text});else if(u.inlineData){let d=u.inlineData;if(d.mimeType&&d.mimeType.startsWith("image/")){let f=this.authType===zt.IFLOW||this.authType===zt.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"),p=this.authType===zt.AONE||this.authType===zt.LOGIN_WITH_AONE;if(!f&&!p&&ST.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+d.mimeType+";base64,"+d.data}}]});else try{if(!d.data)throw new Error(R.t("openaiContentGenerator.errors.imageDataMissing"));let h=await this.multimodalHelper.generateImageDescription(d.data,d.mimeType);c.push({type:"text",text:`[Image Description]: ${h}`})}catch(h){I3(h),c.push({type:"text",text:R.t("openaiContentGenerator.errors.imageContentCannotParse",{error:h instanceof Error?h.message:String(h)})})}}}c.length>0&&r.push({role:"user",content:c})}}}}return r}createGeminiResponse(){let e=new Iz;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),i=n.candidates?.[0],o=!1;if(!r||!r.message)return{response:n,hadJsonFixes:o};if(r.message.reasoning_content&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.reasoning&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning}),r.message.content&&r.message.content.trim()&&i?.content?.parts&&i.content.parts.push({text:r.message.content}),r.message.tool_calls&&Array.isArray(r.message.tool_calls))for(let s of r.message.tool_calls){let a;try{a=JSON.parse(s.function.arguments)}catch(c){if(I3(c),this.baseUrl==="https://apis.iflow.cn/v1")try{a=await this.fixInvalidJsonWithQwen(s.function.arguments),o=!0}catch(u){I3(u),console.error("Failed to fix JSON",u),a={}}else a={}}i?.content?.parts?.push({functionCall:{id:s.id,name:s.function.name,args:a}})}return i&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(i.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},{response:n,hadJsonFixes:o}}async fixInvalidJsonWithQwen(e){let r=`
|
|
937
|
+
`;await gPr.appendFile(this.logFilePath,s,"utf-8")}catch(i){console.debug(R.t("openaiContentGenerator.errors.failedWriteDebugLog"),i)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);I3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return UF("model_call",n,async()=>this.generateContentInternal(e,r))}async generateContentInternal(e,r){let n=wT.api;n.start("OpenAI-GenerateContent-Total");let i=!1;try{if((this.authType===zt.LOGIN_WITH_IFLOW||this.authType===zt.IFLOW)&&await Tz()){this.authType===zt.LOGIN_WITH_IFLOW&&await w_e();let{getCachedApiKey:T}=await Promise.resolve().then(()=>(xR(),tdt)),B=await T();B&&(this.apiKey=B)}let o=await this.convertToOpenAIMessages(e),s=uPr(o);if(this.config){let O=this.config.getConversationId();if(O)try{await zEt(this.config,O,{model:this.modelName,tool:s})}catch(T){this.logTelemetryFailure("Telemetry initialization failed",T)}}let a=this.convertToOpenAITools(e.config?.tools),c={model:this.modelName,messages:o},u=!1;this.config?.getTemperature()!==void 0&&this.config.getTemperature()!==-1?(c.temperature=this.config.getTemperature(),u=!0):e.config?.temperature!==void 0&&(this.config?.getTemperature()===void 0||this.config.getTemperature()!==-1)&&(c.temperature=e.config.temperature,u=!0),u||(this.config?.getTopP()!==void 0&&this.config.getTopP()!==-1?c.top_p=this.config.getTopP():e.config?.topP!==void 0&&(this.config?.getTopP()===void 0||this.config.getTopP()!==-1)&&(c.top_p=e.config.topP));let d=this.config?.getContentGeneratorConfig?.();d?.thinking&&d.thinking.maxTokens>0?(eNe.configureThinkingRequest(this.modelName,c,d.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),d.thinking=null):eNe.configureNonThinkingRequest(this.modelName,c);let f=await this.calculateInputTokens(e),p=e4t(this.modelName,f),h="global";h==="aone"&&(c.max_tokens=p),c.max_new_tokens=p,e.config?.stopSequences&&e.config.stopSequences.length>0&&(c.stop=e.config.stopSequences),a&&a.length>0&&(c.tools=a),await this.logToPromptFile(c,"INPUT REQUEST");let m=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl;["offline-whale-wave.alibaba-inc.com","whale.wave.vipserver.offline","whale-wave.alibaba-inc.com","pre-whale-wave.alibaba-inc.com","internal-offline-whale-wave.alibaba-inc.com","internal-whale-wave.alibaba-inc.com"].some(O=>m.includes(O))&&(c.extend_fields={sessionId:this.config?.getSessionId()||""});let A=Date.now(),y=Xyt(),E={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"user-agent":"iFlow-Cli","session-id":this.config?.getSessionId()||"","conversation-id":this.config?.getConversationId()||""};y&&(E={...E,traceparent:y}),h==="aone"&&(E={...E,"X-Client-Type":"iflow-cli","X-Client-Version":"0.3.24"}),VBe(this.config,new tJ(this.baseUrl,this.modelName,JSON.stringify(c),r,JSON.stringify(e.contents)));let v=await fetch(`${m}/chat/completions`,{signal:e.config?.abortSignal,method:"POST",headers:E,body:JSON.stringify(c)}),C=Date.now()-A;if(!v.ok){let O=await v.text();if(this.config)try{await qBe(this.config,new Error(O)),D3(this.config,new b2(this.modelName,O,C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",v.status,v.status,void 0))}catch(T){this.logTelemetryFailure("Telemetry error recording failed",T)}throw v.status===511?(this.config&&D3(this.config,new b2(this.modelName,"Content length exceeded",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(R.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:y||v.headers.get("eagleeye-traceid")}))):v.status===514?(this.config&&D3(this.config,new b2(this.modelName,"model_error",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(R.t("openaiContentGenerator.errors.modelError",{traceId:y||v.headers.get("eagleeye-traceid")}))):v.status===429?(this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(R.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(R.t("openaiContentGenerator.errors.httpError",{status:v.status,body:O,traceId:y||v.headers.get("eagleeye-traceid")}))}let S;try{S=await v.json()}catch(O){throw I3(O),new Error(R.t("openaiContentGenerator.errors.responseFormatError",{traceId:y||v.headers.get("eagleeye-traceid")}))}if(S.error_code&&(S.error_code===511||S.error_code===413))throw this.config&&D3(this.config,new b2(this.modelName,"Content length exceeded",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",S.error_code,200,S.error_code)),new Error(R.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:y||v.headers.get("eagleeye-traceid")}));if(S.error_code&&S.error_code===514)throw this.config&&D3(this.config,new b2(this.modelName,"model_error",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(R.t("openaiContentGenerator.errors.modelError",{traceId:y||v.headers.get("eagleeye-traceid")}));if(S.status&&S.status==="439"||S.error_code&&S.error_code===439)throw this.config&&D3(this.config,new b2(this.modelName,"API token expired",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(R.t("openaiContentGenerator.errors.apiTokenExpired"));if(S.msg&&(S.msg.includes("invalid apiKey")||S.msg.includes("Invalid apiKey")))throw new Error(R.t("openaiContentGenerator.errors.invalidApiKey"));if(S.status&&(S.status==="434"||S.status===434))throw this.config&&D3(this.config,new b2(this.modelName,"Invalid API key",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(R.t("openaiContentGenerator.errors.invalidApiKey"));if(S.status&&(S.status==="435"||S.status===435))throw this.config&&D3(this.config,new b2(this.modelName,"Model Not Support",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(R.t("openaiContentGenerator.errors.modelNotSupport"));if(S.status&&S.status==="429"||S.error_code&&(S.error_code===429||S.error_code===8211))throw this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",S.error_code||S.status||429,200,S.error_code||S.status||429)),new Error(R.t("openaiContentGenerator.errors.modelRateLimitReached"));if(S.status&&S.status==="449"||S.error_code&&S.error_code===449)throw this.config&&D3(this.config,new b2(this.modelName,"Rate limit reached",C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(R.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(R.t("openaiContentGenerator.errors.userCancel"));if(!S||!S.choices||!Array.isArray(S.choices)||S.choices.length===0){let O=y||v.headers.get("eagleeye-traceid");throw new Error(R.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:O}))}await this.logToPromptFile(S,"API RESPONSE"),S.usage&&(this.lastUsageMetadata={total_tokens:S.usage.total_tokens,prompt_tokens:S.usage.prompt_tokens,completion_tokens:S.usage.completion_tokens});let{response:D,hadJsonFixes:I}=await this.convertFromOpenAIResponse(S);if(i=I,this.config)try{let O=S.choices[0]?.finish_reason;WBe(this.config,new rJ(this.modelName,C,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,S.usage?{promptTokenCount:S.usage.prompt_tokens||0,candidatesTokenCount:S.usage.completion_tokens||0,totalTokenCount:S.usage.total_tokens||0,cachedContentTokenCount:0,thoughtsTokenCount:0,toolUsePromptTokenCount:0}:void 0,JSON.stringify(S,null,2),void 0,O,200,void 0)),await Fpe(this.config),Gyt(this.config,!0,!1,i)}catch(O){this.logTelemetryFailure("Telemetry cleanup failed",O)}return D}catch(o){if(I3(o),this.config&&!(o instanceof Error&&o.message==="user cancel")&&(await qBe(this.config,o instanceof Error?o:new Error(String(o))),Gyt(this.config,!1,!1,i,o instanceof Error?o.message:String(o))),o instanceof Error&&o.cause?.name?.includes("InvalidArgumentError"))throw new Error(R.t("openaiContentGenerator.errors.apiKeyError"));if(o instanceof Error&&o.message&&["iFlow Login expired","Your iFlow Login expired","Your API Token has expired","platform rate limit","platform concurrency limit","Your input has exceeded","the network is unavailable","\u60A8\u7684 iFlow \u767B\u5F55\u5DF2\u8FC7\u671F","\u767B\u5F55\u5DF2\u8FC7\u671F","API Token \u5DF2\u8FC7\u671F","API Token\u5DF2\u8FC7\u671F","\u5E73\u53F0\u901F\u7387\u9650\u5236","\u5E73\u53F0\u5E76\u53D1\u9650\u5236","\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6","\u60A8\u7684\u8F93\u5165\u5DF2\u8D85\u51FA","\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"].some(c=>o.message.includes(c)))throw new Error(o.message);let s="";throw o instanceof Error?s=o.cause?`${o.message}:${o.cause.message}`:o.message:s=String(o),new Error(R.t("openaiContentGenerator.errors.generateDataError",{error:s}),{cause:o})}finally{n.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e,r){let n=await this.generateContent(e,r);async function*i(){yield n}return i()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let i=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(i.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,i=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!i.ok){let s=await i.text();throw new Error(`HTTP error! status: ${i.status}, body: ${s}`)}return{embeddings:[{values:(await i.json()).data[0].embedding}]}}catch(r){throw I3(r),new Error(R.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}async convertToOpenAIMessages(e){let r=[],n=new Set,i=new Map;if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o)if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];for(let c of a){if(c.functionCall){let u=c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(u)}if(c.functionResponse){let u=c.functionResponse.id||c.functionResponse.name||"",d=c.functionResponse.response?.output??(c.functionResponse.response?JSON.stringify(c.functionResponse.response):"");i.set(u,{role:"tool",tool_call_id:u,content:d})}}}for(let[s]of i)n.has(s)||i.delete(s)}if(e.config?.systemInstruction){let o=this.extractSystemInstruction(e.config.systemInstruction);o&&r.push({role:"system",content:o})}if(e.contents){let o=Array.isArray(e.contents)?e.contents:[e.contents];for(let s of o){if(typeof s=="string"){r.push({role:"user",content:s});continue}if(typeof s=="object"&&s!==null&&"text"in s&&s.text){r.push({role:"user",content:s.text});continue}if(typeof s=="object"&&s!==null&&"parts"in s&&s.parts){let a=Array.isArray(s.parts)?s.parts:[s.parts];if(s.role==="model"){let c={role:"assistant",content:"",tool_calls:[]};for(let u of a)if("text"in u&&u.text&&(c.content=u.text),u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;c.tool_calls.push({id:d,function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})},type:"function"})}if((c.content||c.tool_calls.length>0)&&(c.tool_calls.length===0&&delete c.tool_calls,r.push(c),c.tool_calls&&c.tool_calls.length>0))for(let u of c.tool_calls){let d=i.get(u.id);d?r.push(d):r.push({role:"tool",tool_call_id:u.id,content:R.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let c=[];for(let u of a)if("text"in u&&u.text)c.push({type:"text",text:u.text});else if(u.inlineData){let d=u.inlineData;if(d.mimeType&&d.mimeType.startsWith("image/")){let f=this.authType===zt.IFLOW||this.authType===zt.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"),p=this.authType===zt.AONE||this.authType===zt.LOGIN_WITH_AONE;if(!f&&!p&&ST.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+d.mimeType+";base64,"+d.data}}]});else try{if(!d.data)throw new Error(R.t("openaiContentGenerator.errors.imageDataMissing"));let h=await this.multimodalHelper.generateImageDescription(d.data,d.mimeType);c.push({type:"text",text:`[Image Description]: ${h}`})}catch(h){I3(h),c.push({type:"text",text:R.t("openaiContentGenerator.errors.imageContentCannotParse",{error:h instanceof Error?h.message:String(h)})})}}}c.length>0&&r.push({role:"user",content:c})}}}}return r}createGeminiResponse(){let e=new Iz;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),i=n.candidates?.[0],o=!1;if(!r||!r.message)return{response:n,hadJsonFixes:o};if(r.message.reasoning_content&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.reasoning&&i?.content?.parts&&i.content.parts.push({thought:!0,text:r.message.reasoning}),r.message.content&&r.message.content.trim()&&i?.content?.parts&&i.content.parts.push({text:r.message.content}),r.message.tool_calls&&Array.isArray(r.message.tool_calls))for(let s of r.message.tool_calls){let a;try{a=JSON.parse(s.function.arguments)}catch(c){if(I3(c),this.baseUrl==="https://apis.iflow.cn/v1")try{a=await this.fixInvalidJsonWithQwen(s.function.arguments),o=!0}catch(u){I3(u),console.error("Failed to fix JSON",u),a={}}else a={}}i?.content?.parts?.push({functionCall:{id:s.id,name:s.function.name,args:a}})}return i&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(i.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},{response:n,hadJsonFixes:o}}async fixInvalidJsonWithQwen(e){let r=`
|
|
938
938
|
\u4F60\u662F\u4E00\u4E2Ajson\u683C\u5F0F\u4F18\u5316\u4E13\u5BB6\uFF0C\u4F60\u7684\u5DE5\u4F5C\u662F\u5C06\u4E00\u4E32\u6587\u672C\uFF0C\u6839\u636Ejson schema\u7684\u5B9A\u4E49\u8F93\u51FA\u6210\u4E00\u4E2Avalid\u7684json
|
|
939
939
|
\u8FD9\u4E2A\u662F\u9519\u8BEF\u7684json\u683C\u5F0F\uFF1A
|
|
940
940
|
${e}
|
|
@@ -947,7 +947,7 @@ Otherwise navigate to:
|
|
|
947
947
|
|
|
948
948
|
${e}
|
|
949
949
|
|
|
950
|
-
`);try{(await i2(e)).on("error",o=>{throw new Error(`BROWSER_LAUNCH_FAILED: Failed to open browser automatically: ${o.message}. Please navigate to the URL manually.`)})}catch(i){throw new Error(`BROWSER_LAUNCH_FAILED: An unexpected error occurred while trying to open the browser: ${i}. Please navigate to the URL manually.`)}console.log("Waiting for authentication...");let n=0;for(;n<r.maxRetries;){await qPr(r.pollInterval);let i=await HPr(t,r);if(i.isSuccess()){let o=i.getPrivateToken();return await TT.savePrivateToken(o),console.log("Aone authentication successful!"),!0}i.getError()&&console.log(`Waiting for authentication... (${n+1}/${r.maxRetries})`),n++}throw new Error("Authentication timeout. Please try again.")}async function cNe(t=new MJ){return await TT.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await GPr(t)}async function _S(){return await TT.loadPrivateToken()}async function lNe(){await TT.clearPrivateToken(),console.log("Aone authentication cleared.")}async function zpo(){return await TT.hasValidToken()}async function Ypo(t=new MJ){return await lNe(),await cNe(t)}var uNe=Z(()=>{"use strict";l4t();G9();FPr();UPr();QPr();});async function u4t(t,e,r,n){if(e===zt.LOGIN_WITH_IFLOW){let i=await yL(e,r),o=await NC();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new ZF({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||Gpe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===zt.LOGIN_WITH_AONE){if(!await cNe())throw new Error("Aone authentication failed. Please try again.");let o=await _S();if(!o)throw new Error("No Aone private token found. Please re-authenticate.");let s=r.getContentGeneratorConfig(),a=Buffer.from(o,"utf8").toString("base64");return new ZF({model:r.getModel(),apiKey:a,baseUrl:s?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:s?.multimodalModelName,config:r})}if(e===zt.CLOUD_SHELL){let i=await yL(e,r),o=await hgr(i);return new V9(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var d4t=Z(()=>{"use strict";iE();xR();mgr();D_e();r4t();u5();uNe();});function Kpo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function xS(t){let e=Kpo(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function Wpe(){return xS("apiKey")}function zpe(){return xS("baseUrl")||xS("url")}function Ype(){return xS("modelName")||xS("model")}function jPr(t){let e=xS(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function VPr(t){let e=xS(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function $Pr(t){let e=xS(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function dNe(){return!!(Wpe()||zpe()||Ype())}function f4t(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep","debugKeystrokeLogging","pasteFromClipboard"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout","temperature","topP"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=xS(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=jPr(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=VPr(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=$Pr(o);s!==void 0&&(t[o]=s)}),t}function Jpo(){return{apiKey:Wpe(),baseUrl:zpe(),model:Ype()}}var p4t=Z(()=>{"use strict";});async function h4t(t,e,r){await Tz()&&(await T_e()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=Wpe(),o=zpe(),s=Ype(),a=r?.apiKey||i,c=r?.baseUrl||o||Xpo[e],u=r?.modelName||t.getModel()||s||yE,d={model:u,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===zt.CLOUD_SHELL?d:e===zt.LOGIN_WITH_IFLOW?(d.baseUrl=c||Gpe,d.multimodalModelName="qwen3-vl-plus",a&&(d.apiKey=a),d):([...EE,zt.OPENAI_COMPATIBLE].includes(e)&&a&&(d.apiKey=a,d.baseUrl=c,d.model=u),d)}async function m4t(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.3.24
|
|
950
|
+
`);try{(await i2(e)).on("error",o=>{throw new Error(`BROWSER_LAUNCH_FAILED: Failed to open browser automatically: ${o.message}. Please navigate to the URL manually.`)})}catch(i){throw new Error(`BROWSER_LAUNCH_FAILED: An unexpected error occurred while trying to open the browser: ${i}. Please navigate to the URL manually.`)}console.log("Waiting for authentication...");let n=0;for(;n<r.maxRetries;){await qPr(r.pollInterval);let i=await HPr(t,r);if(i.isSuccess()){let o=i.getPrivateToken();return await TT.savePrivateToken(o),console.log("Aone authentication successful!"),!0}i.getError()&&console.log(`Waiting for authentication... (${n+1}/${r.maxRetries})`),n++}throw new Error("Authentication timeout. Please try again.")}async function cNe(t=new MJ){return await TT.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await GPr(t)}async function _S(){return await TT.loadPrivateToken()}async function lNe(){await TT.clearPrivateToken(),console.log("Aone authentication cleared.")}async function zpo(){return await TT.hasValidToken()}async function Ypo(t=new MJ){return await lNe(),await cNe(t)}var uNe=Z(()=>{"use strict";l4t();G9();FPr();UPr();QPr();});async function u4t(t,e,r,n){if(e===zt.LOGIN_WITH_IFLOW){let i=await yL(e,r),o=await NC();if(!o)throw new Error("No API key found. Please re-authenticate.");let s=r.getContentGeneratorConfig();return new ZF({model:r.getModel(),apiKey:o,baseUrl:s?.baseUrl||Gpe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===zt.LOGIN_WITH_AONE){if(!await cNe())throw new Error("Aone authentication failed. Please try again.");let o=await _S();if(!o)throw new Error("No Aone private token found. Please re-authenticate.");let s=r.getContentGeneratorConfig(),a=Buffer.from(o,"utf8").toString("base64");return new ZF({model:r.getModel(),apiKey:a,baseUrl:s?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:s?.multimodalModelName,config:r})}if(e===zt.CLOUD_SHELL){let i=await yL(e,r),o=await hgr(i);return new V9(i,o.projectId,t,n,o.userTier)}throw new Error(`Unsupported authType: ${e}`)}var d4t=Z(()=>{"use strict";iE();xR();mgr();D_e();r4t();u5();uNe();});function Kpo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function xS(t){let e=Kpo(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let i=`iflow_${t}`;if(process.env[i])return process.env[i];let o=`iflow_${e}`;if(process.env[o])return process.env[o]}function Wpe(){return xS("apiKey")}function zpe(){return xS("baseUrl")||xS("url")}function Ype(){return xS("modelName")||xS("model")}function jPr(t){let e=xS(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function VPr(t){let e=xS(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function $Pr(t){let e=xS(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function dNe(){return!!(Wpe()||zpe()||Ype())}function f4t(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep","debugKeystrokeLogging","pasteFromClipboard"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout","temperature","topP"],i=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(o=>{let s=xS(o);s!==void 0&&(t[o]=s)}),r.forEach(o=>{let s=jPr(o);s!==void 0&&(t[o]=s)}),n.forEach(o=>{let s=VPr(o);s!==void 0&&(t[o]=s)}),i.forEach(o=>{let s=$Pr(o);s!==void 0&&(t[o]=s)}),t}function Jpo(){return{apiKey:Wpe(),baseUrl:zpe(),model:Ype()}}var p4t=Z(()=>{"use strict";});async function h4t(t,e,r){await Tz()&&(await T_e()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted."));let i=Wpe(),o=zpe(),s=Ype(),a=r?.apiKey||i,c=r?.baseUrl||o||Xpo[e],u=r?.modelName||t.getModel()||s||yE,d={model:u,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===zt.CLOUD_SHELL?d:e===zt.LOGIN_WITH_IFLOW?(d.baseUrl=c||Gpe,d.multimodalModelName="qwen3-vl-plus",a&&(d.apiKey=a),d):([...EE,zt.OPENAI_COMPATIBLE].includes(e)&&a&&(d.apiKey=a,d.baseUrl=c,d.model=u),d)}async function m4t(t,e,r){let i={headers:{"User-Agent":`iFlowCLI/0.3.24 (${process.platform}; ${process.arch})`}};if(t.authType&&[...EE,zt.IDEA_LAB].includes(t.authType)||t.authType===zt.OPENAI_COMPATIBLE)return new ZF({...t,config:e});if(t.authType===zt.LOGIN_WITH_IFLOW||t.authType===zt.LOGIN_WITH_AONE||t.authType===zt.CLOUD_SHELL)return u4t(i,t.authType,e,r);throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var zt,EE,Xpo,iE=Z(()=>{"use strict";d4t();u5();r4t();p4t();xR();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.LOGIN_WITH_AONE="oauth-aone",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.AONE="aone",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})(zt||(zt={}));EE=[zt.IFLOW,zt.AONE],Xpo={[zt.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[zt.IFLOW]:Gpe,[zt.AONE]:yPr}});var fNe,WPr=Z(()=>{"use strict";fNe=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,i)=>n.name.localeCompare(i.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var sn,vE=Z(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed",t.HOOK_BLOCKED="hook_blocked"})(sn||(sn={}))});function Zpo(t){return{text:t.text}}function eho(t,e){return[{text:R.t("mcpTool.messages.mediaDataProvided",{toolName:e,type:t.type,mimeType:t.mimeType})},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function tho(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:R.t("mcpTool.messages.embeddedResourceProvided",{toolName:e,mimeType:n})},{inlineData:{mimeType:n,data:r.blob}}]}return null}function rho(t){return{text:R.t("mcpTool.messages.resourceLink",{title:t.title||t.name,uri:t.uri})}}function nho(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(o=>{switch(o.type){case"text":return Zpo(o);case"image":case"audio":return eho(o,n);case"resource":return tho(o,n);case"resource_link":return rho(o);default:return null}}).filter(o=>o!==null):[{text:R.t("mcpTool.errors.parseResponseFailed")}]}function iho(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return R.t("mcpTool.display.image",{mimeType:n.mimeType});case"audio":return R.t("mcpTool.display.audio",{mimeType:n.mimeType});case"resource_link":return R.t("mcpTool.display.resourceLink",{title:n.title||n.name,uri:n.uri});case"resource":return n.resource?.text?n.resource.text:R.t("mcpTool.display.embeddedResource",{mimeType:n.resource?.mimeType||R.t("mcpTool.display.unknownType")});default:return R.t("mcpTool.display.unknownContentType",{type:n.type})}}).join(`
|
|
951
951
|
`):"```json\n"+JSON.stringify(t,null,2)+"\n```"}function zPr(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"_");return e.length>63&&(e=e.slice(0,28)+"___"+e.slice(-32)),e}var e0,Kpe=Z(()=>{"use strict";qRe();vE();Id();Mc();di();e0=class t extends Io{mcpTool;serverName;serverToolName;parameterSchemaJson;timeout;trust;static allowlist=new Set;constructor(e,r,n,i,o,s,a,c){super(c??zPr(n),`${n} (${r} MCP Server)`,i,Do.Hammer,Ro.Other,{type:lr.OBJECT},!0,!1),this.mcpTool=e,this.serverName=r,this.serverToolName=n,this.parameterSchemaJson=o,this.timeout=s,this.trust=a}asFullyQualifiedTool(){return new t(this.mcpTool,this.serverName,this.serverToolName,this.description,this.parameterSchemaJson,this.timeout,this.trust,`${this.serverName}__${this.serverToolName}`)}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchemaJson}}async shouldConfirmExecute(e,r){let n=this.serverName,i=`${this.serverName}.${this.serverToolName}`;return this.trust||t.allowlist.has(n)||t.allowlist.has(i)?!1:{type:"mcp",title:R.t("mcpTool.messages.confirmExecution"),serverName:this.serverName,toolName:this.serverToolName,toolDisplayName:this.name,onConfirm:async s=>{s===yn.ProceedAlwaysServer?t.allowlist.add(n):s===yn.ProceedAlwaysTool&&t.allowlist.add(i)}}}isMCPToolError(e){let n=e?.[0]?.functionResponse?.response;if(n){let i=n?.error,o=i?.isError;if(i&&(o===!0||o==="true"))return!0}return!1}async execute(e){let{callId:r,...n}=e,i=[{name:this.serverToolName,args:n}],o=await this.mcpTool.callTool(i);if(this.isMCPToolError(o)){let a=`MCP tool '${this.serverToolName}' reported tool error for function call: ${LF(i[0])} with response: ${LF(o)}`;return{llmContent:a,returnDisplay:R.t("mcpTool.errors.toolReportedError",{toolName:this.serverToolName}),error:{message:a,type:sn.MCP_TOOL_ERROR}}}return{llmContent:nho(o),returnDisplay:iho(o)}}}});var KPr=w((wUa,YPr)=>{"use strict";YPr.exports=function(e){return e.map(function(r){return r===""?"''":r&&typeof r=="object"?r.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var nMr=w((TUa,rMr)=>{"use strict";var tMr="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",JPr=new RegExp("^"+tMr+"$"),XPr="|&;()<> \\t",oho='"((\\\\"|[^"])*?)"',sho="'((\\\\'|[^'])*?)'",aho=/^#$/,ZPr="'",eMr='"',g4t="$",eU="",cho=4294967296;for(A4t=0;A4t<4;A4t++)eU+=(cho*Math.random()).toString(16);var A4t,lho=new RegExp("^"+eU);function uho(t,e){for(var r=e.lastIndex,n=[],i;i=e.exec(t);)n.push(i),e.lastIndex===i.index&&(e.lastIndex+=1);return e.lastIndex=r,n}function dho(t,e,r){var n=typeof t=="function"?t(r):t[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+eU+JSON.stringify(n)+eU:e+n}function fho(t,e,r){r||(r={});var n=r.escape||"\\",i="(\\"+n+`['"`+XPr+`]|[^\\s'"`+XPr+"])+",o=new RegExp(["("+tMr+")","("+i+"|"+oho+"|"+sho+")+"].join("|"),"g"),s=uho(t,o);if(s.length===0)return[];e||(e={});var a=!1;return s.map(function(c){var u=c[0];if(!u||a)return;if(JPr.test(u))return{op:u};var d=!1,f=!1,p="",h=!1,m;function g(){m+=1;var E,v,C=u.charAt(m);if(C==="{"){if(m+=1,u.charAt(m)==="}")throw new Error("Bad substitution: "+u.slice(m-2,m+1));if(E=u.indexOf("}",m),E<0)throw new Error("Bad substitution: "+u.slice(m));v=u.slice(m,E),m=E}else if(/[*@#?$!_-]/.test(C))v=C,m+=1;else{var S=u.slice(m);E=S.match(/[^\w\d_]/),E?(v=S.slice(0,E.index),m+=E.index-1):(v=S,m=u.length)}return dho(e,"",v)}for(m=0;m<u.length;m++){var A=u.charAt(m);if(h=h||!d&&(A==="*"||A==="?"),f)p+=A,f=!1;else if(d)A===d?d=!1:d==ZPr?p+=A:A===n?(m+=1,A=u.charAt(m),A===eMr||A===n||A===g4t?p+=A:p+=n+A):A===g4t?p+=g():p+=A;else if(A===eMr||A===ZPr)d=A;else{if(JPr.test(A))return{op:u};if(aho.test(A)){a=!0;var y={comment:t.slice(c.index+m+1)};return p.length?[p,y]:[y]}else A===n?f=!0:A===g4t?p+=g():p+=A}}return h?{op:"glob",pattern:p}:p}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}rMr.exports=function(e,r,n){var i=fho(e,r,n);return typeof r!="function"?i:i.reduce(function(o,s){if(typeof s=="object")return o.concat(s);var a=s.split(RegExp("("+eU+".*?"+eU+")","g"));return a.length===1?o.concat(a[0]):o.concat(a.filter(Boolean).map(function(c){return lho.test(c)?JSON.parse(c.split(eU)[1]):c}))},[])}});var pNe=w(y4t=>{"use strict";y4t.quote=KPr();y4t.parse=nMr()});var Js,E4t,kn,SS,Jpe=Z(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Js||(Js={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(E4t||(E4t={}));kn=Js.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),SS=t=>{switch(typeof t){case"undefined":return kn.undefined;case"string":return kn.string;case"number":return Number.isNaN(t)?kn.nan:kn.number;case"boolean":return kn.boolean;case"function":return kn.function;case"bigint":return kn.bigint;case"symbol":return kn.symbol;case"object":return Array.isArray(t)?kn.array:t===null?kn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?kn.promise:typeof Map<"u"&&t instanceof Map?kn.map:typeof Set<"u"&&t instanceof Set?kn.set:typeof Date<"u"&&t instanceof Date?kn.date:kn.object;default:return kn.unknown}}});var jr,pho,R3,hNe=Z(()=>{Jpe();jr=Js.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"]),pho=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),R3=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}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,Js.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};R3.create=t=>new R3(t)});var hho,IT,v4t=Z(()=>{hNe();Jpe();hho=(t,e)=>{let r;switch(t.code){case jr.invalid_type:t.received===kn.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case jr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Js.jsonStringifyReplacer)}`;break;case jr.unrecognized_keys:r=`Unrecognized key(s) in object: ${Js.joinValues(t.keys,", ")}`;break;case jr.invalid_union:r="Invalid input";break;case jr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Js.joinValues(t.options)}`;break;case jr.invalid_enum_value:r=`Invalid enum value. Expected ${Js.joinValues(t.options)}, received '${t.received}'`;break;case jr.invalid_arguments:r="Invalid function arguments";break;case jr.invalid_return_type:r="Invalid function return type";break;case jr.invalid_date:r="Invalid date";break;case jr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Js.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case jr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case jr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case jr.custom:r="Invalid input";break;case jr.invalid_intersection_types:r="Intersection results could not be merged";break;case jr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case jr.not_finite:r="Number must be finite";break;default:r=e.defaultError,Js.assertNever(t)}return{message:r}},IT=hho});function mho(t){iMr=t}function LJ(){return iMr}var iMr,mNe=Z(()=>{v4t();iMr=IT});function En(t,e){let r=LJ(),n=Xpe({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===IT?void 0:IT].filter(i=>!!i)});t.common.issues.push(n)}var Xpe,gho,t0,$i,tU,x2,gNe,ANe,$B,FJ,b4t=Z(()=>{mNe();v4t();Xpe=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},gho=[];t0=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return $i;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return $i;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},$i=Object.freeze({status:"aborted"}),tU=t=>({status:"dirty",value:t}),x2=t=>({status:"valid",value:t}),gNe=t=>t.status==="aborted",ANe=t=>t.status==="dirty",$B=t=>t.status==="valid",FJ=t=>typeof Promise<"u"&&t instanceof Promise});var oMr=Z(()=>{});var mi,sMr=Z(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(mi||(mi={}))});function ss(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}function uMr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Oho(t){return new RegExp(`^${uMr(t)}$`)}function dMr(t){let e=`${lMr}T${uMr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function kho(t,e){return!!((e==="v4"||!e)&&who.test(t)||(e==="v6"||!e)&&Iho.test(t))}function Pho(t,e){if(!Cho.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Mho(t,e){return!!((e==="v4"||!e)&&Tho.test(t)||(e==="v6"||!e)&&Dho.test(t))}function Lho(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function UJ(t){if(t instanceof B3){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=cb.create(UJ(n))}return new B3({...t._def,shape:()=>e})}else return t instanceof BT?new BT({...t._def,type:UJ(t.element)}):t instanceof cb?cb.create(UJ(t.unwrap())):t instanceof TS?TS.create(UJ(t.unwrap())):t instanceof wS?wS.create(t.items.map(e=>UJ(e))):t}function _4t(t,e){let r=SS(t),n=SS(e);if(t===e)return{valid:!0,data:t};if(r===kn.object&&n===kn.object){let i=Js.objectKeys(e),o=Js.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let c=_4t(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===kn.array&&n===kn.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],c=_4t(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===kn.date&&n===kn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function fMr(t,e){return new fU({values:t,typeName:Zi.ZodEnum,...ss(e)})}function cMr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function pMr(t,e={},r){return t?zB.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=cMr(e,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=cMr(e,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):zB.create()}var lb,aMr,Cs,Aho,yho,Eho,vho,bho,Cho,_ho,xho,Sho,C4t,who,Tho,Iho,Dho,Rho,Bho,lMr,Nho,WB,rU,nU,iU,oU,QJ,sU,aU,zB,RT,d5,qJ,BT,B3,cU,DT,yNe,lU,wS,ENe,HJ,GJ,vNe,uU,dU,fU,pU,YB,ub,cb,TS,hU,mU,jJ,Fho,Zpe,ehe,gU,Uho,Zi,Qho,hMr,mMr,qho,Hho,gMr,Gho,jho,Vho,$ho,Who,zho,Yho,Kho,Jho,Xho,Zho,emo,tmo,rmo,nmo,imo,omo,smo,amo,cmo,lmo,umo,dmo,fmo,pmo,hmo,mmo,gmo,Amo,ymo,Emo,vmo,bmo,Cmo,AMr=Z(()=>{hNe();mNe();sMr();b4t();Jpe();lb=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}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}},aMr=(t,e)=>{if($B(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 r=new R3(t.common.issues);return this._error=r,this._error}}};Cs=class{get description(){return this._def.description}_getType(e){return SS(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:SS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new t0,ctx:{common:e.parent.common,data:e.data,parsedType:SS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(FJ(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)},i=this._parseSync({data:e,path:n.path,parent:n});return aMr(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return $B(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>$B(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(FJ(i)?i:Promise.resolve(i));return aMr(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:jr.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ub({schema:this,typeName:Zi.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:r=>this["~validate"](r)}}optional(){return cb.create(this,this._def)}nullable(){return TS.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return BT.create(this)}promise(){return YB.create(this,this._def)}or(e){return cU.create([this,e],this._def)}and(e){return lU.create(this,e,this._def)}transform(e){return new ub({...ss(this._def),schema:this,typeName:Zi.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new hU({...ss(this._def),innerType:this,defaultValue:r,typeName:Zi.ZodDefault})}brand(){return new Zpe({typeName:Zi.ZodBranded,type:this,...ss(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new mU({...ss(this._def),innerType:this,catchValue:r,typeName:Zi.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ehe.create(this,e)}readonly(){return gU.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Aho=/^c[^\s-]{8,}$/i,yho=/^[0-9a-z]+$/,Eho=/^[0-9A-HJKMNP-TV-Z]{26}$/i,vho=/^[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,bho=/^[a-z0-9_-]{21}$/i,Cho=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_ho=/^[-+]?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)?)??$/,xho=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Sho="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",who=/^(?:(?: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])$/,Tho=/^(?:(?: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])$/,Iho=/^(([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]))$/,Dho=/^(([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])$/,Rho=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Bho=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lMr="((\\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])))",Nho=new RegExp(`^${lMr}$`);WB=class t extends Cs{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==kn.string){let o=this._getOrReturnCtx(e);return En(o,{code:jr.invalid_type,expected:kn.string,received:o.parsedType}),$i}let n=new t0,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),En(i,{code:jr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),En(i,{code:jr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?En(i,{code:jr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&En(i,{code:jr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")xho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"email",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")C4t||(C4t=new RegExp(Sho,"u")),C4t.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"emoji",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")vho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"uuid",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")bho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"nanoid",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Aho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"cuid",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")yho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"cuid2",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Eho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"ulid",code:jr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),En(i,{validation:"url",code:jr.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"regex",code:jr.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?dMr(o).test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Nho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Oho(o).test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{code:jr.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?_ho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"duration",code:jr.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?kho(e.data,o.version)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"ip",code:jr.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Pho(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"jwt",code:jr.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Mho(e.data,o.version)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"cidr",code:jr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Rho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"base64",code:jr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Bho.test(e.data)||(i=this._getOrReturnCtx(e,i),En(i,{validation:"base64url",code:jr.invalid_string,message:o.message}),n.dirty()):Js.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:jr.invalid_string,...mi.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...mi.errToObj(e)})}url(e){return this._addCheck({kind:"url",...mi.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...mi.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...mi.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...mi.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...mi.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...mi.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...mi.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...mi.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...mi.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...mi.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...mi.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...mi.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,...mi.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,...mi.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...mi.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...mi.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...mi.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...mi.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...mi.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...mi.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...mi.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...mi.errToObj(r)})}nonempty(e){return this.min(1,mi.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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};WB.create=t=>new WB({checks:[],typeName:Zi.ZodString,coerce:t?.coerce??!1,...ss(t)});rU=class t extends Cs{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)!==kn.number){let o=this._getOrReturnCtx(e);return En(o,{code:jr.invalid_type,expected:kn.number,received:o.parsedType}),$i}let n,i=new t0;for(let o of this._def.checks)o.kind==="int"?Js.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:jr.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Lho(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:jr.not_finite,message:o.message}),i.dirty()):Js.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,mi.toString(r))}gt(e,r){return this.setLimit("min",e,!1,mi.toString(r))}lte(e,r){return this.setLimit("max",e,!0,mi.toString(r))}lt(e,r){return this.setLimit("max",e,!1,mi.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:mi.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:mi.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:mi.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:mi.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:mi.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:mi.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:mi.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:mi.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:mi.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:mi.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Js.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};rU.create=t=>new rU({checks:[],typeName:Zi.ZodNumber,coerce:t?.coerce||!1,...ss(t)});nU=class t extends Cs{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)!==kn.bigint)return this._getInvalidInput(e);let n,i=new t0;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),En(n,{code:jr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Js.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return En(r,{code:jr.invalid_type,expected:kn.bigint,received:r.parsedType}),$i}gte(e,r){return this.setLimit("min",e,!0,mi.toString(r))}gt(e,r){return this.setLimit("min",e,!1,mi.toString(r))}lte(e,r){return this.setLimit("max",e,!0,mi.toString(r))}lt(e,r){return this.setLimit("max",e,!1,mi.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:mi.toString(i)}]})}_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:mi.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:mi.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:mi.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:mi.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:mi.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};nU.create=t=>new nU({checks:[],typeName:Zi.ZodBigInt,coerce:t?.coerce??!1,...ss(t)});iU=class extends Cs{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==kn.boolean){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.boolean,received:n.parsedType}),$i}return x2(e.data)}};iU.create=t=>new iU({typeName:Zi.ZodBoolean,coerce:t?.coerce||!1,...ss(t)});oU=class t extends Cs{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==kn.date){let o=this._getOrReturnCtx(e);return En(o,{code:jr.invalid_type,expected:kn.date,received:o.parsedType}),$i}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return En(o,{code:jr.invalid_date}),$i}let n=new t0,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),En(i,{code:jr.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),En(i,{code:jr.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Js.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:mi.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:mi.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};oU.create=t=>new oU({checks:[],coerce:t?.coerce||!1,typeName:Zi.ZodDate,...ss(t)});QJ=class extends Cs{_parse(e){if(this._getType(e)!==kn.symbol){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.symbol,received:n.parsedType}),$i}return x2(e.data)}};QJ.create=t=>new QJ({typeName:Zi.ZodSymbol,...ss(t)});sU=class extends Cs{_parse(e){if(this._getType(e)!==kn.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.undefined,received:n.parsedType}),$i}return x2(e.data)}};sU.create=t=>new sU({typeName:Zi.ZodUndefined,...ss(t)});aU=class extends Cs{_parse(e){if(this._getType(e)!==kn.null){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.null,received:n.parsedType}),$i}return x2(e.data)}};aU.create=t=>new aU({typeName:Zi.ZodNull,...ss(t)});zB=class extends Cs{constructor(){super(...arguments),this._any=!0}_parse(e){return x2(e.data)}};zB.create=t=>new zB({typeName:Zi.ZodAny,...ss(t)});RT=class extends Cs{constructor(){super(...arguments),this._unknown=!0}_parse(e){return x2(e.data)}};RT.create=t=>new RT({typeName:Zi.ZodUnknown,...ss(t)});d5=class extends Cs{_parse(e){let r=this._getOrReturnCtx(e);return En(r,{code:jr.invalid_type,expected:kn.never,received:r.parsedType}),$i}};d5.create=t=>new d5({typeName:Zi.ZodNever,...ss(t)});qJ=class extends Cs{_parse(e){if(this._getType(e)!==kn.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.void,received:n.parsedType}),$i}return x2(e.data)}};qJ.create=t=>new qJ({typeName:Zi.ZodVoid,...ss(t)});BT=class t extends Cs{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==kn.array)return En(r,{code:jr.invalid_type,expected:kn.array,received:r.parsedType}),$i;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(En(r,{code:s?jr.too_big:jr.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(En(r,{code:jr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(En(r,{code:jr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new lb(r,s,r.path,a)))).then(s=>t0.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new lb(r,s,r.path,a)));return t0.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:mi.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:mi.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:mi.toString(r)}})}nonempty(e){return this.min(1,e)}};BT.create=(t,e)=>new BT({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Zi.ZodArray,...ss(e)});B3=class t extends Cs{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(),r=Js.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==kn.object){let u=this._getOrReturnCtx(e);return En(u,{code:jr.invalid_type,expected:kn.object,received:u.parsedType}),$i}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof d5&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new lb(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof d5){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(En(i,{code:jr.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let f=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new lb(i,f,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let f=await d.key,p=await d.value;u.push({key:f,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>t0.mergeObjectSync(n,u)):t0.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return mi.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:mi.errToObj(e).message??i}:{message:i}}}:{}})}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:Zi.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Js.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Js.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return UJ(this)}partial(e){let r={};for(let n of Js.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Js.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof cb;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return fMr(Js.objectKeys(this.shape))}};B3.create=(t,e)=>new B3({shape:()=>t,unknownKeys:"strip",catchall:d5.create(),typeName:Zi.ZodObject,...ss(e)});B3.strictCreate=(t,e)=>new B3({shape:()=>t,unknownKeys:"strict",catchall:d5.create(),typeName:Zi.ZodObject,...ss(e)});B3.lazycreate=(t,e)=>new B3({shape:t,unknownKeys:"strip",catchall:d5.create(),typeName:Zi.ZodObject,...ss(e)});cU=class extends Cs{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(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 r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new R3(a.ctx.common.issues));return En(r,{code:jr.invalid_union,unionErrors:s}),$i}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new R3(c));return En(r,{code:jr.invalid_union,unionErrors:a}),$i}}get options(){return this._def.options}};cU.create=(t,e)=>new cU({options:t,typeName:Zi.ZodUnion,...ss(e)});DT=t=>t instanceof uU?DT(t.schema):t instanceof ub?DT(t.innerType()):t instanceof dU?[t.value]:t instanceof fU?t.options:t instanceof pU?Js.objectValues(t.enum):t instanceof hU?DT(t._def.innerType):t instanceof sU?[void 0]:t instanceof aU?[null]:t instanceof cb?[void 0,...DT(t.unwrap())]:t instanceof TS?[null,...DT(t.unwrap())]:t instanceof Zpe||t instanceof gU?DT(t.unwrap()):t instanceof mU?DT(t._def.innerType):[],yNe=class t extends Cs{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==kn.object)return En(r,{code:jr.invalid_type,expected:kn.object,received:r.parsedType}),$i;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(En(r,{code:jr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),$i)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=DT(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:Zi.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ss(n)})}};lU=class extends Cs{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(gNe(o)||gNe(s))return $i;let a=_4t(o.value,s.value);return a.valid?((ANe(o)||ANe(s))&&r.dirty(),{status:r.value,value:a.data}):(En(n,{code:jr.invalid_intersection_types}),$i)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lU.create=(t,e,r)=>new lU({left:t,right:e,typeName:Zi.ZodIntersection,...ss(r)});wS=class t extends Cs{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==kn.array)return En(n,{code:jr.invalid_type,expected:kn.array,received:n.parsedType}),$i;if(n.data.length<this._def.items.length)return En(n,{code:jr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$i;!this._def.rest&&n.data.length>this._def.items.length&&(En(n,{code:jr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new lb(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>t0.mergeArray(r,s)):t0.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};wS.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wS({items:t,typeName:Zi.ZodTuple,rest:null,...ss(e)})};ENe=class t extends Cs{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==kn.object)return En(n,{code:jr.invalid_type,expected:kn.object,received:n.parsedType}),$i;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new lb(n,a,n.path,a)),value:s._parse(new lb(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?t0.mergeObjectAsync(r,i):t0.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Cs?new t({keyType:e,valueType:r,typeName:Zi.ZodRecord,...ss(n)}):new t({keyType:WB.create(),valueType:e,typeName:Zi.ZodRecord,...ss(r)})}},HJ=class extends Cs{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==kn.map)return En(n,{code:jr.invalid_type,expected:kn.map,received:n.parsedType}),$i;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new lb(n,a,n.path,[u,"key"])),value:o._parse(new lb(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return $i;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return $i;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};HJ.create=(t,e,r)=>new HJ({valueType:e,keyType:t,typeName:Zi.ZodMap,...ss(r)});GJ=class t extends Cs{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==kn.set)return En(n,{code:jr.invalid_type,expected:kn.set,received:n.parsedType}),$i;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(En(n,{code:jr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(En(n,{code:jr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return $i;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new lb(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:mi.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:mi.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};GJ.create=(t,e)=>new GJ({valueType:t,minSize:null,maxSize:null,typeName:Zi.ZodSet,...ss(e)});vNe=class t extends Cs{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==kn.function)return En(r,{code:jr.invalid_type,expected:kn.function,received:r.parsedType}),$i;function n(a,c){return Xpe({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,LJ(),IT].filter(u=>!!u),issueData:{code:jr.invalid_arguments,argumentsError:c}})}function i(a,c){return Xpe({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,LJ(),IT].filter(u=>!!u),issueData:{code:jr.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof YB){let a=this;return x2(async function(...c){let u=new R3([]),d=await a._def.args.parseAsync(c,o).catch(h=>{throw u.addIssue(n(c,h)),u}),f=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(f,o).catch(h=>{throw u.addIssue(i(f,h)),u})})}else{let a=this;return x2(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new R3([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),f=a._def.returns.safeParse(d,o);if(!f.success)throw new R3([i(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:wS.create(e).rest(RT.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,r,n){return new t({args:e||wS.create([]).rest(RT.create()),returns:r||RT.create(),typeName:Zi.ZodFunction,...ss(n)})}},uU=class extends Cs{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};uU.create=(t,e)=>new uU({getter:t,typeName:Zi.ZodLazy,...ss(e)});dU=class extends Cs{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return En(r,{received:r.data,code:jr.invalid_literal,expected:this._def.value}),$i}return{status:"valid",value:e.data}}get value(){return this._def.value}};dU.create=(t,e)=>new dU({value:t,typeName:Zi.ZodLiteral,...ss(e)});fU=class t extends Cs{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{expected:Js.joinValues(n),received:r.parsedType,code:jr.invalid_type}),$i}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{received:r.data,code:jr.invalid_enum_value,options:n}),$i}return x2(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};fU.create=fMr;pU=class extends Cs{_parse(e){let r=Js.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==kn.string&&n.parsedType!==kn.number){let i=Js.objectValues(r);return En(n,{expected:Js.joinValues(i),received:n.parsedType,code:jr.invalid_type}),$i}if(this._cache||(this._cache=new Set(Js.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Js.objectValues(r);return En(n,{received:n.data,code:jr.invalid_enum_value,options:i}),$i}return x2(e.data)}get enum(){return this._def.values}};pU.create=(t,e)=>new pU({values:t,typeName:Zi.ZodNativeEnum,...ss(e)});YB=class extends Cs{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==kn.promise&&r.common.async===!1)return En(r,{code:jr.invalid_type,expected:kn.promise,received:r.parsedType}),$i;let n=r.parsedType===kn.promise?r.data:Promise.resolve(r.data);return x2(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};YB.create=(t,e)=>new YB({type:t,typeName:Zi.ZodPromise,...ss(e)});ub=class extends Cs{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Zi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{En(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return $i;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?$i:c.status==="dirty"?tU(c.value):r.value==="dirty"?tU(c.value):c});{if(r.value==="aborted")return $i;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?$i:a.status==="dirty"?tU(a.value):r.value==="dirty"?tU(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?$i:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?$i:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!$B(s))return $i;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>$B(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):$i);Js.assertNever(i)}};ub.create=(t,e,r)=>new ub({schema:t,typeName:Zi.ZodEffects,effect:e,...ss(r)});ub.createWithPreprocess=(t,e,r)=>new ub({schema:e,effect:{type:"preprocess",transform:t},typeName:Zi.ZodEffects,...ss(r)});cb=class extends Cs{_parse(e){return this._getType(e)===kn.undefined?x2(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};cb.create=(t,e)=>new cb({innerType:t,typeName:Zi.ZodOptional,...ss(e)});TS=class extends Cs{_parse(e){return this._getType(e)===kn.null?x2(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};TS.create=(t,e)=>new TS({innerType:t,typeName:Zi.ZodNullable,...ss(e)});hU=class extends Cs{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===kn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};hU.create=(t,e)=>new hU({innerType:t,typeName:Zi.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ss(e)});mU=class extends Cs{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return FJ(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new R3(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new R3(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};mU.create=(t,e)=>new mU({innerType:t,typeName:Zi.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ss(e)});jJ=class extends Cs{_parse(e){if(this._getType(e)!==kn.nan){let n=this._getOrReturnCtx(e);return En(n,{code:jr.invalid_type,expected:kn.nan,received:n.parsedType}),$i}return{status:"valid",value:e.data}}};jJ.create=t=>new jJ({typeName:Zi.ZodNaN,...ss(t)});Fho=Symbol("zod_brand"),Zpe=class extends Cs{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ehe=class t extends Cs{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?$i:o.status==="dirty"?(r.dirty(),tU(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?$i:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Zi.ZodPipeline})}},gU=class extends Cs{_parse(e){let r=this._def.innerType._parse(e),n=i=>($B(i)&&(i.value=Object.freeze(i.value)),i);return FJ(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};gU.create=(t,e)=>new gU({innerType:t,typeName:Zi.ZodReadonly,...ss(e)});Uho={object:B3.lazycreate};(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"})(Zi||(Zi={}));Qho=(t,e={message:`Input not instance of ${t.name}`})=>pMr(r=>r instanceof t,e),hMr=WB.create,mMr=rU.create,qho=jJ.create,Hho=nU.create,gMr=iU.create,Gho=oU.create,jho=QJ.create,Vho=sU.create,$ho=aU.create,Who=zB.create,zho=RT.create,Yho=d5.create,Kho=qJ.create,Jho=BT.create,Xho=B3.create,Zho=B3.strictCreate,emo=cU.create,tmo=yNe.create,rmo=lU.create,nmo=wS.create,imo=ENe.create,omo=HJ.create,smo=GJ.create,amo=vNe.create,cmo=uU.create,lmo=dU.create,umo=fU.create,dmo=pU.create,fmo=YB.create,pmo=ub.create,hmo=cb.create,mmo=TS.create,gmo=ub.createWithPreprocess,Amo=ehe.create,ymo=()=>hMr().optional(),Emo=()=>mMr().optional(),vmo=()=>gMr().optional(),bmo={string:(t=>WB.create({...t,coerce:!0})),number:(t=>rU.create({...t,coerce:!0})),boolean:(t=>iU.create({...t,coerce:!0})),bigint:(t=>nU.create({...t,coerce:!0})),date:(t=>oU.create({...t,coerce:!0}))},Cmo=$i});var oe={};qs(oe,{BRAND:()=>Fho,DIRTY:()=>tU,EMPTY_PATH:()=>gho,INVALID:()=>$i,NEVER:()=>Cmo,OK:()=>x2,ParseStatus:()=>t0,Schema:()=>Cs,ZodAny:()=>zB,ZodArray:()=>BT,ZodBigInt:()=>nU,ZodBoolean:()=>iU,ZodBranded:()=>Zpe,ZodCatch:()=>mU,ZodDate:()=>oU,ZodDefault:()=>hU,ZodDiscriminatedUnion:()=>yNe,ZodEffects:()=>ub,ZodEnum:()=>fU,ZodError:()=>R3,ZodFirstPartyTypeKind:()=>Zi,ZodFunction:()=>vNe,ZodIntersection:()=>lU,ZodIssueCode:()=>jr,ZodLazy:()=>uU,ZodLiteral:()=>dU,ZodMap:()=>HJ,ZodNaN:()=>jJ,ZodNativeEnum:()=>pU,ZodNever:()=>d5,ZodNull:()=>aU,ZodNullable:()=>TS,ZodNumber:()=>rU,ZodObject:()=>B3,ZodOptional:()=>cb,ZodParsedType:()=>kn,ZodPipeline:()=>ehe,ZodPromise:()=>YB,ZodReadonly:()=>gU,ZodRecord:()=>ENe,ZodSchema:()=>Cs,ZodSet:()=>GJ,ZodString:()=>WB,ZodSymbol:()=>QJ,ZodTransformer:()=>ub,ZodTuple:()=>wS,ZodType:()=>Cs,ZodUndefined:()=>sU,ZodUnion:()=>cU,ZodUnknown:()=>RT,ZodVoid:()=>qJ,addIssueToContext:()=>En,any:()=>Who,array:()=>Jho,bigint:()=>Hho,boolean:()=>gMr,coerce:()=>bmo,custom:()=>pMr,date:()=>Gho,datetimeRegex:()=>dMr,defaultErrorMap:()=>IT,discriminatedUnion:()=>tmo,effect:()=>pmo,enum:()=>umo,function:()=>amo,getErrorMap:()=>LJ,getParsedType:()=>SS,instanceof:()=>Qho,intersection:()=>rmo,isAborted:()=>gNe,isAsync:()=>FJ,isDirty:()=>ANe,isValid:()=>$B,late:()=>Uho,lazy:()=>cmo,literal:()=>lmo,makeIssue:()=>Xpe,map:()=>omo,nan:()=>qho,nativeEnum:()=>dmo,never:()=>Yho,null:()=>$ho,nullable:()=>mmo,number:()=>mMr,object:()=>Xho,objectUtil:()=>E4t,oboolean:()=>vmo,onumber:()=>Emo,optional:()=>hmo,ostring:()=>ymo,pipeline:()=>Amo,preprocess:()=>gmo,promise:()=>fmo,quotelessJson:()=>pho,record:()=>imo,set:()=>smo,setErrorMap:()=>mho,strictObject:()=>Zho,string:()=>hMr,symbol:()=>jho,transformer:()=>pmo,tuple:()=>nmo,undefined:()=>Vho,union:()=>emo,unknown:()=>zho,util:()=>Js,void:()=>Kho});var x4t=Z(()=>{mNe();b4t();oMr();Jpe();AMr();hNe()});var KB=Z(()=>{x4t();x4t()});var VJ,yMr,bNe,EMr,vMr,_mo,pb,N3,the,IS,hb,CNe,bMr,_Ne,CMr,_Mr,xMr,rhe,db,SMr,wMr,JB,AU,xNe,xmo,nhe,ihe,TMr,Smo,wmo,Tmo,S4t,IMr,DMr,SNe,Imo,wNe,TNe,INe,RMr,BMr,w4t,NMr,OMr,Dmo,Rmo,T4t,Bmo,I4t,Nmo,D4t,Omo,kmo,Pmo,Mmo,Lmo,Fmo,Umo,ohe,Qmo,R4t,B4t,N4t,qmo,Hmo,kMr,Gmo,she,jmo,Vmo,$mo,Wmo,O4t,DNe,rQa,zmo,Ymo,PMr,Kmo,Jmo,Xmo,Zmo,ego,tgo,rgo,ngo,igo,ogo,sgo,ago,cgo,lgo,ugo,dgo,fgo,k4t,pgo,RNe,hgo,mgo,nQa,iQa,oQa,sQa,aQa,cQa,fb,XB=Z(()=>{KB();VJ="2025-06-18",yMr=[VJ,"2025-03-26","2024-11-05","2024-10-07"],bNe="2.0",EMr=oe.union([oe.string(),oe.number().int()]),vMr=oe.string(),_mo=oe.object({progressToken:oe.optional(EMr)}).passthrough(),pb=oe.object({_meta:oe.optional(_mo)}).passthrough(),N3=oe.object({method:oe.string(),params:oe.optional(pb)}),the=oe.object({_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),IS=oe.object({method:oe.string(),params:oe.optional(the)}),hb=oe.object({_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),CNe=oe.union([oe.string(),oe.number().int()]),bMr=oe.object({jsonrpc:oe.literal(bNe),id:CNe}).merge(N3).strict(),_Ne=t=>bMr.safeParse(t).success,CMr=oe.object({jsonrpc:oe.literal(bNe)}).merge(IS).strict(),_Mr=t=>CMr.safeParse(t).success,xMr=oe.object({jsonrpc:oe.literal(bNe),id:CNe,result:hb}).strict(),rhe=t=>xMr.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(db||(db={}));SMr=oe.object({jsonrpc:oe.literal(bNe),id:CNe,error:oe.object({code:oe.number().int(),message:oe.string(),data:oe.optional(oe.unknown())})}).strict(),wMr=t=>SMr.safeParse(t).success,JB=oe.union([bMr,CMr,xMr,SMr]),AU=hb.strict(),xNe=IS.extend({method:oe.literal("notifications/cancelled"),params:the.extend({requestId:CNe,reason:oe.string().optional()})}),xmo=oe.object({src:oe.string(),mimeType:oe.optional(oe.string()),sizes:oe.optional(oe.array(oe.string()))}).passthrough(),nhe=oe.object({icons:oe.array(xmo).optional()}).passthrough(),ihe=oe.object({name:oe.string(),title:oe.optional(oe.string())}).passthrough(),TMr=ihe.extend({version:oe.string(),websiteUrl:oe.optional(oe.string())}).merge(nhe),Smo=oe.object({experimental:oe.optional(oe.object({}).passthrough()),sampling:oe.optional(oe.object({}).passthrough()),elicitation:oe.optional(oe.object({}).passthrough()),roots:oe.optional(oe.object({listChanged:oe.optional(oe.boolean())}).passthrough())}).passthrough(),wmo=N3.extend({method:oe.literal("initialize"),params:pb.extend({protocolVersion:oe.string(),capabilities:Smo,clientInfo:TMr})}),Tmo=oe.object({experimental:oe.optional(oe.object({}).passthrough()),logging:oe.optional(oe.object({}).passthrough()),completions:oe.optional(oe.object({}).passthrough()),prompts:oe.optional(oe.object({listChanged:oe.optional(oe.boolean())}).passthrough()),resources:oe.optional(oe.object({subscribe:oe.optional(oe.boolean()),listChanged:oe.optional(oe.boolean())}).passthrough()),tools:oe.optional(oe.object({listChanged:oe.optional(oe.boolean())}).passthrough())}).passthrough(),S4t=hb.extend({protocolVersion:oe.string(),capabilities:Tmo,serverInfo:TMr,instructions:oe.optional(oe.string())}),IMr=IS.extend({method:oe.literal("notifications/initialized")}),DMr=t=>IMr.safeParse(t).success,SNe=N3.extend({method:oe.literal("ping")}),Imo=oe.object({progress:oe.number(),total:oe.optional(oe.number()),message:oe.optional(oe.string())}).passthrough(),wNe=IS.extend({method:oe.literal("notifications/progress"),params:the.merge(Imo).extend({progressToken:EMr})}),TNe=N3.extend({params:pb.extend({cursor:oe.optional(vMr)}).optional()}),INe=hb.extend({nextCursor:oe.optional(vMr)}),RMr=oe.object({uri:oe.string(),mimeType:oe.optional(oe.string()),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),BMr=RMr.extend({text:oe.string()}),w4t=oe.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),NMr=RMr.extend({blob:w4t}),OMr=ihe.extend({uri:oe.string(),description:oe.optional(oe.string()),mimeType:oe.optional(oe.string()),_meta:oe.optional(oe.object({}).passthrough())}).merge(nhe),Dmo=ihe.extend({uriTemplate:oe.string(),description:oe.optional(oe.string()),mimeType:oe.optional(oe.string()),_meta:oe.optional(oe.object({}).passthrough())}).merge(nhe),Rmo=TNe.extend({method:oe.literal("resources/list")}),T4t=INe.extend({resources:oe.array(OMr)}),Bmo=TNe.extend({method:oe.literal("resources/templates/list")}),I4t=INe.extend({resourceTemplates:oe.array(Dmo)}),Nmo=N3.extend({method:oe.literal("resources/read"),params:pb.extend({uri:oe.string()})}),D4t=hb.extend({contents:oe.array(oe.union([BMr,NMr]))}),Omo=IS.extend({method:oe.literal("notifications/resources/list_changed")}),kmo=N3.extend({method:oe.literal("resources/subscribe"),params:pb.extend({uri:oe.string()})}),Pmo=N3.extend({method:oe.literal("resources/unsubscribe"),params:pb.extend({uri:oe.string()})}),Mmo=IS.extend({method:oe.literal("notifications/resources/updated"),params:the.extend({uri:oe.string()})}),Lmo=oe.object({name:oe.string(),description:oe.optional(oe.string()),required:oe.optional(oe.boolean())}).passthrough(),Fmo=ihe.extend({description:oe.optional(oe.string()),arguments:oe.optional(oe.array(Lmo)),_meta:oe.optional(oe.object({}).passthrough())}).merge(nhe),Umo=TNe.extend({method:oe.literal("prompts/list")}),ohe=INe.extend({prompts:oe.array(Fmo)}),Qmo=N3.extend({method:oe.literal("prompts/get"),params:pb.extend({name:oe.string(),arguments:oe.optional(oe.record(oe.string()))})}),R4t=oe.object({type:oe.literal("text"),text:oe.string(),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),B4t=oe.object({type:oe.literal("image"),data:w4t,mimeType:oe.string(),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),N4t=oe.object({type:oe.literal("audio"),data:w4t,mimeType:oe.string(),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),qmo=oe.object({type:oe.literal("resource"),resource:oe.union([BMr,NMr]),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),Hmo=OMr.extend({type:oe.literal("resource_link")}),kMr=oe.union([R4t,B4t,N4t,Hmo,qmo]),Gmo=oe.object({role:oe.enum(["user","assistant"]),content:kMr}).passthrough(),she=hb.extend({description:oe.optional(oe.string()),messages:oe.array(Gmo)}),jmo=IS.extend({method:oe.literal("notifications/prompts/list_changed")}),Vmo=oe.object({title:oe.optional(oe.string()),readOnlyHint:oe.optional(oe.boolean()),destructiveHint:oe.optional(oe.boolean()),idempotentHint:oe.optional(oe.boolean()),openWorldHint:oe.optional(oe.boolean())}).passthrough(),$mo=ihe.extend({description:oe.optional(oe.string()),inputSchema:oe.object({type:oe.literal("object"),properties:oe.optional(oe.object({}).passthrough()),required:oe.optional(oe.array(oe.string()))}).passthrough(),outputSchema:oe.optional(oe.object({type:oe.literal("object"),properties:oe.optional(oe.object({}).passthrough()),required:oe.optional(oe.array(oe.string()))}).passthrough()),annotations:oe.optional(Vmo),_meta:oe.optional(oe.object({}).passthrough())}).merge(nhe),Wmo=TNe.extend({method:oe.literal("tools/list")}),O4t=INe.extend({tools:oe.array($mo)}),DNe=hb.extend({content:oe.array(kMr).default([]),structuredContent:oe.object({}).passthrough().optional(),isError:oe.optional(oe.boolean())}),rQa=DNe.or(hb.extend({toolResult:oe.unknown()})),zmo=N3.extend({method:oe.literal("tools/call"),params:pb.extend({name:oe.string(),arguments:oe.optional(oe.record(oe.unknown()))})}),Ymo=IS.extend({method:oe.literal("notifications/tools/list_changed")}),PMr=oe.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Kmo=N3.extend({method:oe.literal("logging/setLevel"),params:pb.extend({level:PMr})}),Jmo=IS.extend({method:oe.literal("notifications/message"),params:the.extend({level:PMr,logger:oe.optional(oe.string()),data:oe.unknown()})}),Xmo=oe.object({name:oe.string().optional()}).passthrough(),Zmo=oe.object({hints:oe.optional(oe.array(Xmo)),costPriority:oe.optional(oe.number().min(0).max(1)),speedPriority:oe.optional(oe.number().min(0).max(1)),intelligencePriority:oe.optional(oe.number().min(0).max(1))}).passthrough(),ego=oe.object({role:oe.enum(["user","assistant"]),content:oe.union([R4t,B4t,N4t])}).passthrough(),tgo=N3.extend({method:oe.literal("sampling/createMessage"),params:pb.extend({messages:oe.array(ego),systemPrompt:oe.optional(oe.string()),includeContext:oe.optional(oe.enum(["none","thisServer","allServers"])),temperature:oe.optional(oe.number()),maxTokens:oe.number().int(),stopSequences:oe.optional(oe.array(oe.string())),metadata:oe.optional(oe.object({}).passthrough()),modelPreferences:oe.optional(Zmo)})}),rgo=hb.extend({model:oe.string(),stopReason:oe.optional(oe.enum(["endTurn","stopSequence","maxTokens"]).or(oe.string())),role:oe.enum(["user","assistant"]),content:oe.discriminatedUnion("type",[R4t,B4t,N4t])}),ngo=oe.object({type:oe.literal("boolean"),title:oe.optional(oe.string()),description:oe.optional(oe.string()),default:oe.optional(oe.boolean())}).passthrough(),igo=oe.object({type:oe.literal("string"),title:oe.optional(oe.string()),description:oe.optional(oe.string()),minLength:oe.optional(oe.number()),maxLength:oe.optional(oe.number()),format:oe.optional(oe.enum(["email","uri","date","date-time"]))}).passthrough(),ogo=oe.object({type:oe.enum(["number","integer"]),title:oe.optional(oe.string()),description:oe.optional(oe.string()),minimum:oe.optional(oe.number()),maximum:oe.optional(oe.number())}).passthrough(),sgo=oe.object({type:oe.literal("string"),title:oe.optional(oe.string()),description:oe.optional(oe.string()),enum:oe.array(oe.string()),enumNames:oe.optional(oe.array(oe.string()))}).passthrough(),ago=oe.union([ngo,igo,ogo,sgo]),cgo=N3.extend({method:oe.literal("elicitation/create"),params:pb.extend({message:oe.string(),requestedSchema:oe.object({type:oe.literal("object"),properties:oe.record(oe.string(),ago),required:oe.optional(oe.array(oe.string()))}).passthrough()})}),lgo=hb.extend({action:oe.enum(["accept","decline","cancel"]),content:oe.optional(oe.record(oe.string(),oe.unknown()))}),ugo=oe.object({type:oe.literal("ref/resource"),uri:oe.string()}).passthrough(),dgo=oe.object({type:oe.literal("ref/prompt"),name:oe.string()}).passthrough(),fgo=N3.extend({method:oe.literal("completion/complete"),params:pb.extend({ref:oe.union([dgo,ugo]),argument:oe.object({name:oe.string(),value:oe.string()}).passthrough(),context:oe.optional(oe.object({arguments:oe.optional(oe.record(oe.string(),oe.string()))}))})}),k4t=hb.extend({completion:oe.object({values:oe.array(oe.string()).max(100),total:oe.optional(oe.number().int()),hasMore:oe.optional(oe.boolean())}).passthrough()}),pgo=oe.object({uri:oe.string().startsWith("file://"),name:oe.optional(oe.string()),_meta:oe.optional(oe.object({}).passthrough())}).passthrough(),RNe=N3.extend({method:oe.literal("roots/list")}),hgo=hb.extend({roots:oe.array(pgo)}),mgo=IS.extend({method:oe.literal("notifications/roots/list_changed")}),nQa=oe.union([SNe,wmo,fgo,Kmo,Qmo,Umo,Rmo,Bmo,Nmo,kmo,Pmo,zmo,Wmo]),iQa=oe.union([xNe,wNe,IMr,mgo]),oQa=oe.union([AU,rgo,lgo,hgo]),sQa=oe.union([SNe,tgo,cgo,RNe]),aQa=oe.union([xNe,wNe,Jmo,Mmo,Omo,Ymo,jmo]),cQa=oe.union([AU,S4t,k4t,she,ohe,T4t,I4t,D4t,DNe,O4t]),fb=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function MMr(t,e){return Object.entries(e).reduce((r,[n,i])=>(i&&typeof i=="object"?r[n]=r[n]?{...r[n],...i}:i:r[n]=i,r),{...t})}var ggo,BNe,LMr=Z(()=>{XB();ggo=6e4,BNe=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(xNe,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(wNe,r=>{this._onprogress(r)}),this.setRequestHandler(SNe,r=>({}))}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new fb(db.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let s=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{s?.(c),this._onerror(c)};let a=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{a?.(c,u),rhe(c)||wMr(c)?this._onresponse(c):_Ne(c)?this._onrequest(c,u):_Mr(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new fb(db.ConnectionClosed,"Connection closed");for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i;let o=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,s=this._transport;if(o===void 0){s?.send({jsonrpc:"2.0",id:e.id,error:{code:db.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c={signal:a.signal,sessionId:s?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,d,f)=>this.request(u,d,{...f,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>o(e,c)).then(u=>{if(!a.signal.aborted)return s?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var d;if(!a.signal.aborted)return s?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:db.InternalError,message:(d=u.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){s(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),rhe(e))n(e);else{let i=new fb(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}=n??{};return new Promise((a,c)=>{var u,d,f,p,h,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=n?.signal)===null||d===void 0||d.throwIfAborted();let g=this._requestMessageId++,A={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),A.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:g}});let y=C=>{var S;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(C)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`))),c(C)};this._responseHandlers.set(g,C=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(C instanceof Error)return c(C);try{let D=r.parse(C.result);a(D)}catch(D){c(D)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var C;y((C=n?.signal)===null||C===void 0?void 0:C.reason)});let E=(h=n?.timeout)!==null&&h!==void 0?h:ggo,v=()=>y(new fb(db.RequestTimeout,"Request timed out",{timeout:E}));this._setupTimeout(g,E,n?.maxTotalTimeout,v,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(A,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(C=>{this._cleanupTimeout(g),c(C)})})}async notification(e,r){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(d=>this._onerror(d))});return}let a={...e,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>Promise.resolve(r(e.parse(i),o)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var lhe=w(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.regexpCode=Ua.getEsmExportName=Ua.getProperty=Ua.safeStringify=Ua.stringify=Ua.strConcat=Ua.addCodeArg=Ua.str=Ua._=Ua.nil=Ua._Code=Ua.Name=Ua.IDENTIFIER=Ua._CodeOrName=void 0;var ahe=class{};Ua._CodeOrName=ahe;Ua.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var yU=class extends ahe{constructor(e){if(super(),!Ua.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ua.Name=yU;var mb=class extends ahe{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof yU&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ua._Code=mb;Ua.nil=new mb("");function FMr(t,...e){let r=[t[0]],n=0;for(;n<e.length;)M4t(r,e[n]),r.push(t[++n]);return new mb(r)}Ua._=FMr;var P4t=new mb("+");function UMr(t,...e){let r=[che(t[0])],n=0;for(;n<e.length;)r.push(P4t),M4t(r,e[n]),r.push(P4t,che(t[++n]));return Ago(r),new mb(r)}Ua.str=UMr;function M4t(t,e){e instanceof mb?t.push(...e._items):e instanceof yU?t.push(e):t.push(vgo(e))}Ua.addCodeArg=M4t;function Ago(t){let e=1;for(;e<t.length-1;){if(t[e]===P4t){let r=ygo(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function ygo(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof yU||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof yU))return`"${t}${e.slice(1)}`}function Ego(t,e){return e.emptyStr()?t:t.emptyStr()?e:UMr`${t}${e}`}Ua.strConcat=Ego;function vgo(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:che(Array.isArray(t)?t.join(","):t)}function bgo(t){return new mb(che(t))}Ua.stringify=bgo;function che(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ua.safeStringify=che;function Cgo(t){return typeof t=="string"&&Ua.IDENTIFIER.test(t)?new mb(`.${t}`):FMr`[${t}]`}Ua.getProperty=Cgo;function _go(t){if(typeof t=="string"&&Ua.IDENTIFIER.test(t))return new mb(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ua.getEsmExportName=_go;function xgo(t){return new mb(t.toString())}Ua.regexpCode=xgo});var U4t=w(k3=>{"use strict";Object.defineProperty(k3,"__esModule",{value:!0});k3.ValueScope=k3.ValueScopeName=k3.Scope=k3.varKinds=k3.UsedValueState=void 0;var O3=lhe(),L4t=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},NNe;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(NNe||(k3.UsedValueState=NNe={}));k3.varKinds={const:new O3.Name("const"),let:new O3.Name("let"),var:new O3.Name("var")};var ONe=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof O3.Name?e:this.name(e)}name(e){return new O3.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};k3.Scope=ONe;var kNe=class extends O3.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,O3._)`.${new O3.Name(r)}[${n}]`}};k3.ValueScopeName=kNe;var Sgo=(0,O3._)`\n`,F4t=class extends ONe{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Sgo:O3.nil}}get(){return this._scope}name(e){return new kNe(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(s);if(d)return d}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,i.setValue(r,{property:o,itemIndex:u}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,O3._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=O3.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,NNe.Started);let d=r(u);if(d){let f=this.opts.es5?k3.varKinds.var:k3.varKinds.const;o=(0,O3._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=i?.(u))o=(0,O3._)`${o}${d}${this.opts._n}`;else throw new L4t(u);c.set(u,NNe.Completed)})}return o}};k3.ValueScope=F4t});var _s=w(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.or=Ms.and=Ms.not=Ms.CodeGen=Ms.operators=Ms.varKinds=Ms.ValueScopeName=Ms.ValueScope=Ms.Scope=Ms.Name=Ms.regexpCode=Ms.stringify=Ms.getProperty=Ms.nil=Ms.strConcat=Ms.str=Ms._=void 0;var ma=lhe(),f5=U4t(),ZB=lhe();Object.defineProperty(Ms,"_",{enumerable:!0,get:function(){return ZB._}});Object.defineProperty(Ms,"str",{enumerable:!0,get:function(){return ZB.str}});Object.defineProperty(Ms,"strConcat",{enumerable:!0,get:function(){return ZB.strConcat}});Object.defineProperty(Ms,"nil",{enumerable:!0,get:function(){return ZB.nil}});Object.defineProperty(Ms,"getProperty",{enumerable:!0,get:function(){return ZB.getProperty}});Object.defineProperty(Ms,"stringify",{enumerable:!0,get:function(){return ZB.stringify}});Object.defineProperty(Ms,"regexpCode",{enumerable:!0,get:function(){return ZB.regexpCode}});Object.defineProperty(Ms,"Name",{enumerable:!0,get:function(){return ZB.Name}});var FNe=U4t();Object.defineProperty(Ms,"Scope",{enumerable:!0,get:function(){return FNe.Scope}});Object.defineProperty(Ms,"ValueScope",{enumerable:!0,get:function(){return FNe.ValueScope}});Object.defineProperty(Ms,"ValueScopeName",{enumerable:!0,get:function(){return FNe.ValueScopeName}});Object.defineProperty(Ms,"varKinds",{enumerable:!0,get:function(){return FNe.varKinds}});Ms.operators={GT:new ma._Code(">"),GTE:new ma._Code(">="),LT:new ma._Code("<"),LTE:new ma._Code("<="),EQ:new ma._Code("==="),NEQ:new ma._Code("!=="),NOT:new ma._Code("!"),OR:new ma._Code("||"),AND:new ma._Code("&&"),ADD:new ma._Code("+")};var NT=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Q4t=class extends NT{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?f5.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=WJ(this.rhs,e,r)),this}get names(){return this.rhs instanceof ma._CodeOrName?this.rhs.names:{}}},PNe=class extends NT{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ma.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=WJ(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ma.Name?{}:{...this.lhs.names};return LNe(e,this.rhs)}},q4t=class extends PNe{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},H4t=class extends NT{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},G4t=class extends NT{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},j4t=class extends NT{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},V4t=class extends NT{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=WJ(this.code,e,r),this}get names(){return this.code instanceof ma._CodeOrName?this.code.names:{}}},uhe=class extends NT{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(wgo(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>bU(e,r.names),{})}},OT=class extends uhe{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$4t=class extends uhe{},$J=class extends OT{};$J.kind="else";var EU=class t extends OT{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new $J(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(QMr(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=WJ(this.condition,e,r),this}get names(){let e=super.names;return LNe(e,this.condition),this.else&&bU(e,this.else.names),e}};EU.kind="if";var vU=class extends OT{};vU.kind="for";var W4t=class extends vU{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=WJ(this.iteration,e,r),this}get names(){return bU(super.names,this.iteration.names)}},z4t=class extends vU{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?f5.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=LNe(super.names,this.from);return LNe(e,this.to)}},MNe=class extends vU{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=WJ(this.iterable,e,r),this}get names(){return bU(super.names,this.iterable.names)}},dhe=class extends OT{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};dhe.kind="func";var fhe=class extends uhe{render(e){return"return "+super.render(e)}};fhe.kind="return";var Y4t=class extends OT{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&bU(e,this.catch.names),this.finally&&bU(e,this.finally.names),e}},phe=class extends OT{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};phe.kind="catch";var hhe=class extends OT{render(e){return"finally"+super.render(e)}};hhe.kind="finally";var K4t=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
952
952
|
`:""},this._extScope=e,this._scope=new f5.Scope({parent:e}),this._nodes=[new $4t]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new Q4t(e,o,n)),o}const(e,r,n){return this._def(f5.varKinds.const,e,r,n)}let(e,r,n){return this._def(f5.varKinds.let,e,r,n)}var(e,r,n){return this._def(f5.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new PNe(e,r,n))}add(e,r){return this._leafNode(new q4t(e,Ms.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ma.nil&&this._leafNode(new V4t(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,ma.addCodeArg)(r,i));return r.push("}"),new ma._Code(r)}if(e,r,n){if(this._blockNode(new EU(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new EU(e))}else(){return this._elseNode(new $J)}endIf(){return this._endBlockNode(EU,$J)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new W4t(e),r)}forRange(e,r,n,i,o=this.opts.es5?f5.varKinds.var:f5.varKinds.let){let s=this._scope.toName(e);return this._for(new z4t(o,s,r,n),()=>i(s))}forOf(e,r,n,i=f5.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof ma.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ma._)`${s}.length`,a=>{this.var(o,(0,ma._)`${s}[${a}]`),n(o)})}return this._for(new MNe("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?f5.varKinds.var:f5.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ma._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new MNe("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(vU)}label(e){return this._leafNode(new H4t(e))}break(e){return this._leafNode(new G4t(e))}return(e){let r=new fhe;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fhe)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Y4t;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new phe(o),r(o)}return n&&(this._currNode=i.finally=new hhe,this.code(n)),this._endBlockNode(phe,hhe)}throw(e){return this._leafNode(new j4t(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ma.nil,n,i){return this._blockNode(new dhe(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(dhe)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof EU))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Ms.CodeGen=K4t;function bU(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function LNe(t,e){return e instanceof ma._CodeOrName?bU(t,e.names):t}function WJ(t,e,r){if(t instanceof ma.Name)return n(t);if(!i(t))return t;return new ma._Code(t._items.reduce((o,s)=>(s instanceof ma.Name&&(s=n(s)),s instanceof ma._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof ma._Code&&o._items.some(s=>s instanceof ma.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function wgo(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function QMr(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ma._)`!${J4t(t)}`}Ms.not=QMr;var Tgo=qMr(Ms.operators.AND);function Igo(...t){return t.reduce(Tgo)}Ms.and=Igo;var Dgo=qMr(Ms.operators.OR);function Rgo(...t){return t.reduce(Dgo)}Ms.or=Rgo;function qMr(t){return(e,r)=>e===ma.nil?r:r===ma.nil?e:(0,ma._)`${J4t(e)} ${t} ${J4t(r)}`}function J4t(t){return t instanceof ma.Name?t:(0,ma._)`(${t})`}});var Qa=w(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.checkStrictMode=Hs.getErrorPath=Hs.Type=Hs.useFunc=Hs.setEvaluated=Hs.evaluatedPropsToName=Hs.mergeEvaluated=Hs.eachItem=Hs.unescapeJsonPointer=Hs.escapeJsonPointer=Hs.escapeFragment=Hs.unescapeFragment=Hs.schemaRefOrVal=Hs.schemaHasRulesButRef=Hs.schemaHasRules=Hs.checkUnknownRules=Hs.alwaysValidSchema=Hs.toHash=void 0;var Ql=_s(),Bgo=lhe();function Ngo(t){let e={};for(let r of t)e[r]=!0;return e}Hs.toHash=Ngo;function Ogo(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(jMr(t,e),!VMr(e,t.self.RULES.all))}Hs.alwaysValidSchema=Ogo;function jMr(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||zMr(t,`unknown keyword: "${o}"`)}Hs.checkUnknownRules=jMr;function VMr(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Hs.schemaHasRules=VMr;function kgo(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Hs.schemaHasRulesButRef=kgo;function Pgo({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ql._)`${r}`}return(0,Ql._)`${t}${e}${(0,Ql.getProperty)(n)}`}Hs.schemaRefOrVal=Pgo;function Mgo(t){return $Mr(decodeURIComponent(t))}Hs.unescapeFragment=Mgo;function Lgo(t){return encodeURIComponent(Z4t(t))}Hs.escapeFragment=Lgo;function Z4t(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Hs.escapeJsonPointer=Z4t;function $Mr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Hs.unescapeJsonPointer=$Mr;function Fgo(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Hs.eachItem=Fgo;function HMr({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof Ql.Name?(o instanceof Ql.Name?t(i,o,s):e(i,o,s),s):o instanceof Ql.Name?(e(i,s,o),o):r(o,s);return a===Ql.Name&&!(c instanceof Ql.Name)?n(i,c):c}}Hs.mergeEvaluated={props:HMr({mergeNames:(t,e,r)=>t.if((0,Ql._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ql._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ql._)`${r} || {}`).code((0,Ql._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ql._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ql._)`${r} || {}`),evt(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:WMr}),items:HMr({mergeNames:(t,e,r)=>t.if((0,Ql._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ql._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ql._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ql._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function WMr(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ql._)`{}`);return e!==void 0&&evt(t,r,e),r}Hs.evaluatedPropsToName=WMr;function evt(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ql._)`${e}${(0,Ql.getProperty)(n)}`,!0))}Hs.setEvaluated=evt;var GMr={};function Ugo(t,e){return t.scopeValue("func",{ref:e,code:GMr[e.code]||(GMr[e.code]=new Bgo._Code(e.code))})}Hs.useFunc=Ugo;var X4t;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(X4t||(Hs.Type=X4t={}));function Qgo(t,e,r){if(t instanceof Ql.Name){let n=e===X4t.Num;return r?n?(0,Ql._)`"[" + ${t} + "]"`:(0,Ql._)`"['" + ${t} + "']"`:n?(0,Ql._)`"/" + ${t}`:(0,Ql._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ql.getProperty)(t).toString():"/"+Z4t(t)}Hs.getErrorPath=Qgo;function zMr(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Hs.checkStrictMode=zMr});var kT=w(tvt=>{"use strict";Object.defineProperty(tvt,"__esModule",{value:!0});var S2=_s(),qgo={data:new S2.Name("data"),valCxt:new S2.Name("valCxt"),instancePath:new S2.Name("instancePath"),parentData:new S2.Name("parentData"),parentDataProperty:new S2.Name("parentDataProperty"),rootData:new S2.Name("rootData"),dynamicAnchors:new S2.Name("dynamicAnchors"),vErrors:new S2.Name("vErrors"),errors:new S2.Name("errors"),this:new S2.Name("this"),self:new S2.Name("self"),scope:new S2.Name("scope"),json:new S2.Name("json"),jsonPos:new S2.Name("jsonPos"),jsonLen:new S2.Name("jsonLen"),jsonPart:new S2.Name("jsonPart")};tvt.default=qgo});var mhe=w(w2=>{"use strict";Object.defineProperty(w2,"__esModule",{value:!0});w2.extendErrors=w2.resetErrorsCount=w2.reportExtraError=w2.reportError=w2.keyword$DataError=w2.keywordError=void 0;var Da=_s(),UNe=Qa(),z1=kT();w2.keywordError={message:({keyword:t})=>(0,Da.str)`must pass "${t}" keyword validation`};w2.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Da.str)`"${t}" keyword must be ${e} ($data)`:(0,Da.str)`"${t}" keyword is invalid ($data)`};function Hgo(t,e=w2.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,c=JMr(t,e,r);n??(s||a)?YMr(o,c):KMr(i,(0,Da._)`[${c}]`)}w2.reportError=Hgo;function Ggo(t,e=w2.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=JMr(t,e,r);YMr(i,a),o||s||KMr(n,z1.default.vErrors)}w2.reportExtraError=Ggo;function jgo(t,e){t.assign(z1.default.errors,e),t.if((0,Da._)`${z1.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Da._)`${z1.default.vErrors}.length`,e),()=>t.assign(z1.default.vErrors,null)))}w2.resetErrorsCount=jgo;function Vgo({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,z1.default.errors,a=>{t.const(s,(0,Da._)`${z1.default.vErrors}[${a}]`),t.if((0,Da._)`${s}.instancePath === undefined`,()=>t.assign((0,Da._)`${s}.instancePath`,(0,Da.strConcat)(z1.default.instancePath,o.errorPath))),t.assign((0,Da._)`${s}.schemaPath`,(0,Da.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,Da._)`${s}.schema`,r),t.assign((0,Da._)`${s}.data`,n))})}w2.extendErrors=Vgo;function YMr(t,e){let r=t.const("err",e);t.if((0,Da._)`${z1.default.vErrors} === null`,()=>t.assign(z1.default.vErrors,(0,Da._)`[${r}]`),(0,Da._)`${z1.default.vErrors}.push(${r})`),t.code((0,Da._)`${z1.default.errors}++`)}function KMr(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,Da._)`new ${t.ValidationError}(${e})`):(r.assign((0,Da._)`${n}.errors`,e),r.return(!1))}var CU={keyword:new Da.Name("keyword"),schemaPath:new Da.Name("schemaPath"),params:new Da.Name("params"),propertyName:new Da.Name("propertyName"),message:new Da.Name("message"),schema:new Da.Name("schema"),parentSchema:new Da.Name("parentSchema")};function JMr(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Da._)`{}`:$go(t,e,r)}function $go(t,e,r={}){let{gen:n,it:i}=t,o=[Wgo(i,r),zgo(t,r)];return Ygo(t,e,o),n.object(...o)}function Wgo({errorPath:t},{instancePath:e}){let r=e?(0,Da.str)`${t}${(0,UNe.getErrorPath)(e,UNe.Type.Str)}`:t;return[z1.default.instancePath,(0,Da.strConcat)(z1.default.instancePath,r)]}function zgo({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,Da.str)`${e}/${t}`;return r&&(i=(0,Da.str)`${i}${(0,UNe.getErrorPath)(r,UNe.Type.Str)}`),[CU.schemaPath,i]}function Ygo(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:f}=a;n.push([CU.keyword,i],[CU.params,typeof e=="function"?e(t):e||(0,Da._)`{}`]),c.messages&&n.push([CU.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([CU.schema,s],[CU.parentSchema,(0,Da._)`${d}${f}`],[z1.default.data,o]),u&&n.push([CU.propertyName,u])}});var ZMr=w(zJ=>{"use strict";Object.defineProperty(zJ,"__esModule",{value:!0});zJ.boolOrEmptySchema=zJ.topBoolOrEmptySchema=void 0;var Kgo=mhe(),Jgo=_s(),Xgo=kT(),Zgo={message:"boolean schema is false"};function e0o(t){let{gen:e,schema:r,validateName:n}=t;r===!1?XMr(t,!1):typeof r=="object"&&r.$async===!0?e.return(Xgo.default.data):(e.assign((0,Jgo._)`${n}.errors`,null),e.return(!0))}zJ.topBoolOrEmptySchema=e0o;function t0o(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),XMr(t)):r.var(e,!0)}zJ.boolOrEmptySchema=t0o;function XMr(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Kgo.reportError)(i,Zgo,void 0,e)}});var rvt=w(YJ=>{"use strict";Object.defineProperty(YJ,"__esModule",{value:!0});YJ.getRules=YJ.isJSONType=void 0;var r0o=["string","number","integer","boolean","null","object","array"],n0o=new Set(r0o);function i0o(t){return typeof t=="string"&&n0o.has(t)}YJ.isJSONType=i0o;function o0o(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}YJ.getRules=o0o});var nvt=w(eN=>{"use strict";Object.defineProperty(eN,"__esModule",{value:!0});eN.shouldUseRule=eN.shouldUseGroup=eN.schemaHasRulesForType=void 0;function s0o({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&eLr(t,n)}eN.schemaHasRulesForType=s0o;function eLr(t,e){return e.rules.some(r=>tLr(t,r))}eN.shouldUseGroup=eLr;function tLr(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}eN.shouldUseRule=tLr});var ghe=w(T2=>{"use strict";Object.defineProperty(T2,"__esModule",{value:!0});T2.reportTypeError=T2.checkDataTypes=T2.checkDataType=T2.coerceAndCheckDataType=T2.getJSONTypes=T2.getSchemaTypes=T2.DataType=void 0;var a0o=rvt(),c0o=nvt(),l0o=mhe(),ms=_s(),rLr=Qa(),KJ;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(KJ||(T2.DataType=KJ={}));function u0o(t){let e=nLr(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}T2.getSchemaTypes=u0o;function nLr(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(a0o.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}T2.getJSONTypes=nLr;function d0o(t,e){let{gen:r,data:n,opts:i}=t,o=f0o(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,c0o.schemaHasRulesForType)(t,e[0]));if(s){let a=ovt(e,n,i.strictNumbers,KJ.Wrong);r.if(a,()=>{o.length?p0o(t,e,o):svt(t)})}return s}T2.coerceAndCheckDataType=d0o;var iLr=new Set(["string","number","integer","boolean","null"]);function f0o(t,e){return e?t.filter(r=>iLr.has(r)||e==="array"&&r==="array"):[]}function p0o(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,ms._)`typeof ${i}`),a=n.let("coerced",(0,ms._)`undefined`);o.coerceTypes==="array"&&n.if((0,ms._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ms._)`${i}[0]`).assign(s,(0,ms._)`typeof ${i}`).if(ovt(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,ms._)`${a} !== undefined`);for(let u of r)(iLr.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),svt(t),n.endIf(),n.if((0,ms._)`${a} !== undefined`,()=>{n.assign(i,a),h0o(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ms._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,ms._)`"" + ${i}`).elseIf((0,ms._)`${i} === null`).assign(a,(0,ms._)`""`);return;case"number":n.elseIf((0,ms._)`${s} == "boolean" || ${i} === null
|
|
953
953
|
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,ms._)`+${i}`);return;case"integer":n.elseIf((0,ms._)`${s} === "boolean" || ${i} === null
|
|
@@ -961,7 +961,7 @@ ${e}
|
|
|
961
961
|
`;break;case"id":a=A.includes("\0")?void 0:A;break;case"retry":/^\d+$/.test(A)?n(parseInt(A,10)):r(new EOe(`Invalid \`retry\` value: "${A}"`,{type:"invalid-retry",value:A,line:y}));break;default:r(new EOe(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:A,line:y}));break}}function h(){c.length>0&&e({id:a,event:u||void 0,data:c.endsWith(`
|
|
962
962
|
`)?c.slice(0,-1):c}),a=void 0,c="",u=""}function m(g={}){o&&g.consume&&f(o),s=!0,a=void 0,c="",u="",o=""}return{feed:d,reset:m}}function Fyo(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
963
963
|
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?i===t.length-1?s=-1:s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
964
|
-
`&&n++}}return[e,r]}var EOe,Lbt=Z(()=>{EOe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function Uyo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Fbt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Fbt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Fbt(t.cause)}`:t.message:`${t}`}function AQr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Qyo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var COe,EQr,$bt,Xs,Uh,Bd,LT,L3,IU,fX,bOe,_Oe,Fhe,mX,Uhe,aN,pX,gX,hX,Mhe,A5,Ubt,Qbt,qbt,yQr,Hbt,Gbt,Lhe,jbt,Vbt,DU,vQr=Z(()=>{Lbt();COe=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(AQr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(AQr(this),r)}};EQr=t=>{throw TypeError(t)},$bt=(t,e,r)=>e.has(t)||EQr("Cannot "+r),Xs=(t,e,r)=>($bt(t,e,"read from private field"),r?r.call(t):e.get(t)),Uh=(t,e,r)=>e.has(t)?EQr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Bd=(t,e,r,n)=>($bt(t,e,"write to private field"),e.set(t,r),r),LT=(t,e,r)=>($bt(t,e,"access private method"),r),DU=class extends EventTarget{constructor(e,r){var n,i;super(),Uh(this,A5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Uh(this,L3),Uh(this,IU),Uh(this,fX),Uh(this,bOe),Uh(this,_Oe),Uh(this,Fhe),Uh(this,mX),Uh(this,Uhe,null),Uh(this,aN),Uh(this,pX),Uh(this,gX,null),Uh(this,hX,null),Uh(this,Mhe,null),Uh(this,Qbt,async o=>{var s;Xs(this,pX).reset();let{body:a,redirected:c,status:u,headers:d}=o;if(u===204){LT(this,A5,Lhe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Bd(this,fX,new URL(o.url)):Bd(this,fX,void 0),u!==200){LT(this,A5,Lhe).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){LT(this,A5,Lhe).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Xs(this,L3)===this.CLOSED)return;Bd(this,L3,this.OPEN);let f=new Event("open");if((s=Xs(this,Mhe))==null||s.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){LT(this,A5,Lhe).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),m=!0;do{let{done:g,value:A}=await h.read();A&&Xs(this,pX).feed(p.decode(A,{stream:!g})),g&&(m=!1,Xs(this,pX).reset(),LT(this,A5,jbt).call(this))}while(m)}),Uh(this,qbt,o=>{Bd(this,aN,void 0),!(o.name==="AbortError"||o.type==="aborted")&<(this,A5,jbt).call(this,Fbt(o))}),Uh(this,Hbt,o=>{typeof o.id=="string"&&Bd(this,Uhe,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Xs(this,fX)?Xs(this,fX).origin:Xs(this,IU).origin,lastEventId:o.id||""});Xs(this,hX)&&(!o.event||o.event==="message")&&Xs(this,hX).call(this,s),this.dispatchEvent(s)}),Uh(this,Gbt,o=>{Bd(this,Fhe,o)}),Uh(this,Vbt,()=>{Bd(this,mX,void 0),Xs(this,L3)===this.CONNECTING&<(this,A5,Ubt).call(this)});try{if(e instanceof URL)Bd(this,IU,e);else if(typeof e=="string")Bd(this,IU,new URL(e,Qyo()));else throw new Error("Invalid URL")}catch{throw Uyo("An invalid or illegal string was specified")}Bd(this,pX,vOe({onEvent:Xs(this,Hbt),onRetry:Xs(this,Gbt)})),Bd(this,L3,this.CONNECTING),Bd(this,Fhe,3e3),Bd(this,_Oe,(n=r?.fetch)!=null?n:globalThis.fetch),Bd(this,bOe,(i=r?.withCredentials)!=null?i:!1),LT(this,A5,Ubt).call(this)}get readyState(){return Xs(this,L3)}get url(){return Xs(this,IU).href}get withCredentials(){return Xs(this,bOe)}get onerror(){return Xs(this,gX)}set onerror(e){Bd(this,gX,e)}get onmessage(){return Xs(this,hX)}set onmessage(e){Bd(this,hX,e)}get onopen(){return Xs(this,Mhe)}set onopen(e){Bd(this,Mhe,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Xs(this,mX)&&clearTimeout(Xs(this,mX)),Xs(this,L3)!==this.CLOSED&&(Xs(this,aN)&&Xs(this,aN).abort(),Bd(this,L3,this.CLOSED),Bd(this,aN,void 0))}};L3=new WeakMap,IU=new WeakMap,fX=new WeakMap,bOe=new WeakMap,_Oe=new WeakMap,Fhe=new WeakMap,mX=new WeakMap,Uhe=new WeakMap,aN=new WeakMap,pX=new WeakMap,gX=new WeakMap,hX=new WeakMap,Mhe=new WeakMap,A5=new WeakSet,Ubt=function(){Bd(this,L3,this.CONNECTING),Bd(this,aN,new AbortController),Xs(this,_Oe)(Xs(this,IU),LT(this,A5,yQr).call(this)).then(Xs(this,Qbt)).catch(Xs(this,qbt))},Qbt=new WeakMap,qbt=new WeakMap,yQr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Xs(this,Uhe)?{"Last-Event-ID":Xs(this,Uhe)}:void 0},cache:"no-store",signal:(t=Xs(this,aN))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Hbt=new WeakMap,Gbt=new WeakMap,Lhe=function(t,e){var r;Xs(this,L3)!==this.CLOSED&&Bd(this,L3,this.CLOSED);let n=new COe("error",{code:e,message:t});(r=Xs(this,gX))==null||r.call(this,n),this.dispatchEvent(n)},jbt=function(t,e){var r;if(Xs(this,L3)===this.CLOSED)return;Bd(this,L3,this.CONNECTING);let n=new COe("error",{code:e,message:t});(r=Xs(this,gX))==null||r.call(this,n),this.dispatchEvent(n),Bd(this,mX,setTimeout(Xs(this,Vbt),Xs(this,Fhe)))},Vbt=new WeakMap,DU.CONNECTING=0,DU.OPEN=1,DU.CLOSED=2});async function qyo(t){return(await Wbt).getRandomValues(new Uint8Array(t))}async function Hyo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await qyo(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function Gyo(t){return await Hyo(t)}async function jyo(t){let e=await(await Wbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function zbt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Gyo(t),r=await jyo(e);return{code_verifier:e,code_challenge:r}}var Wbt,bQr=Z(()=>{Wbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var i0,_Qr,Ybt,Vyo,xQr,Kbt,SQr,CQr,$yo,Wyo,wQr,nHa,iHa,Jbt=Z(()=>{KB();i0=oe.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:oe.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),oe.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),_Qr=oe.object({resource:oe.string().url(),authorization_servers:oe.array(i0).optional(),jwks_uri:oe.string().url().optional(),scopes_supported:oe.array(oe.string()).optional(),bearer_methods_supported:oe.array(oe.string()).optional(),resource_signing_alg_values_supported:oe.array(oe.string()).optional(),resource_name:oe.string().optional(),resource_documentation:oe.string().optional(),resource_policy_uri:oe.string().url().optional(),resource_tos_uri:oe.string().url().optional(),tls_client_certificate_bound_access_tokens:oe.boolean().optional(),authorization_details_types_supported:oe.array(oe.string()).optional(),dpop_signing_alg_values_supported:oe.array(oe.string()).optional(),dpop_bound_access_tokens_required:oe.boolean().optional()}).passthrough(),Ybt=oe.object({issuer:oe.string(),authorization_endpoint:i0,token_endpoint:i0,registration_endpoint:i0.optional(),scopes_supported:oe.array(oe.string()).optional(),response_types_supported:oe.array(oe.string()),response_modes_supported:oe.array(oe.string()).optional(),grant_types_supported:oe.array(oe.string()).optional(),token_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),service_documentation:i0.optional(),revocation_endpoint:i0.optional(),revocation_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),introspection_endpoint:oe.string().optional(),introspection_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),code_challenge_methods_supported:oe.array(oe.string()).optional()}).passthrough(),Vyo=oe.object({issuer:oe.string(),authorization_endpoint:i0,token_endpoint:i0,userinfo_endpoint:i0.optional(),jwks_uri:i0,registration_endpoint:i0.optional(),scopes_supported:oe.array(oe.string()).optional(),response_types_supported:oe.array(oe.string()),response_modes_supported:oe.array(oe.string()).optional(),grant_types_supported:oe.array(oe.string()).optional(),acr_values_supported:oe.array(oe.string()).optional(),subject_types_supported:oe.array(oe.string()),id_token_signing_alg_values_supported:oe.array(oe.string()),id_token_encryption_alg_values_supported:oe.array(oe.string()).optional(),id_token_encryption_enc_values_supported:oe.array(oe.string()).optional(),userinfo_signing_alg_values_supported:oe.array(oe.string()).optional(),userinfo_encryption_alg_values_supported:oe.array(oe.string()).optional(),userinfo_encryption_enc_values_supported:oe.array(oe.string()).optional(),request_object_signing_alg_values_supported:oe.array(oe.string()).optional(),request_object_encryption_alg_values_supported:oe.array(oe.string()).optional(),request_object_encryption_enc_values_supported:oe.array(oe.string()).optional(),token_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),display_values_supported:oe.array(oe.string()).optional(),claim_types_supported:oe.array(oe.string()).optional(),claims_supported:oe.array(oe.string()).optional(),service_documentation:oe.string().optional(),claims_locales_supported:oe.array(oe.string()).optional(),ui_locales_supported:oe.array(oe.string()).optional(),claims_parameter_supported:oe.boolean().optional(),request_parameter_supported:oe.boolean().optional(),request_uri_parameter_supported:oe.boolean().optional(),require_request_uri_registration:oe.boolean().optional(),op_policy_uri:i0.optional(),op_tos_uri:i0.optional()}).passthrough(),xQr=Vyo.merge(Ybt.pick({code_challenge_methods_supported:!0})),Kbt=oe.object({access_token:oe.string(),id_token:oe.string().optional(),token_type:oe.string(),expires_in:oe.number().optional(),scope:oe.string().optional(),refresh_token:oe.string().optional()}).strip(),SQr=oe.object({error:oe.string(),error_description:oe.string().optional(),error_uri:oe.string().optional()}),CQr=i0.optional().or(oe.literal("").transform(()=>{})),$yo=oe.object({redirect_uris:oe.array(i0),token_endpoint_auth_method:oe.string().optional(),grant_types:oe.array(oe.string()).optional(),response_types:oe.array(oe.string()).optional(),client_name:oe.string().optional(),client_uri:i0.optional(),logo_uri:CQr,scope:oe.string().optional(),contacts:oe.array(oe.string()).optional(),tos_uri:CQr,policy_uri:oe.string().optional(),jwks_uri:i0.optional(),jwks:oe.any().optional(),software_id:oe.string().optional(),software_version:oe.string().optional(),software_statement:oe.string().optional()}).strip(),Wyo=oe.object({client_id:oe.string(),client_secret:oe.string().optional(),client_id_issued_at:oe.number().optional(),client_secret_expires_at:oe.number().optional()}).strip(),wQr=$yo.merge(Wyo),nHa=oe.object({error:oe.string(),error_description:oe.string().optional()}).strip(),iHa=oe.object({token:oe.string(),token_type_hint:oe.string().optional()}).strip()});function TQr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function IQr({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var DQr=Z(()=>{});var th,Qhe,RU,BU,NU,qhe,Hhe,Ghe,FT,jhe,Vhe,$he,Whe,zhe,Yhe,Khe,Jhe,RQr,BQr=Z(()=>{th=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Qhe=class extends th{};Qhe.errorCode="invalid_request";RU=class extends th{};RU.errorCode="invalid_client";BU=class extends th{};BU.errorCode="invalid_grant";NU=class extends th{};NU.errorCode="unauthorized_client";qhe=class extends th{};qhe.errorCode="unsupported_grant_type";Hhe=class extends th{};Hhe.errorCode="invalid_scope";Ghe=class extends th{};Ghe.errorCode="access_denied";FT=class extends th{};FT.errorCode="server_error";jhe=class extends th{};jhe.errorCode="temporarily_unavailable";Vhe=class extends th{};Vhe.errorCode="unsupported_response_type";$he=class extends th{};$he.errorCode="unsupported_token_type";Whe=class extends th{};Whe.errorCode="invalid_token";zhe=class extends th{};zhe.errorCode="method_not_allowed";Yhe=class extends th{};Yhe.errorCode="too_many_requests";Khe=class extends th{};Khe.errorCode="invalid_client_metadata";Jhe=class extends th{};Jhe.errorCode="insufficient_scope";RQr={[Qhe.errorCode]:Qhe,[RU.errorCode]:RU,[BU.errorCode]:BU,[NU.errorCode]:NU,[qhe.errorCode]:qhe,[Hhe.errorCode]:Hhe,[Ghe.errorCode]:Ghe,[FT.errorCode]:FT,[jhe.errorCode]:jhe,[Vhe.errorCode]:Vhe,[$he.errorCode]:$he,[Whe.errorCode]:Whe,[zhe.errorCode]:zhe,[Yhe.errorCode]:Yhe,[Khe.errorCode]:Khe,[Jhe.errorCode]:Jhe}});function zyo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function OQr(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&zyo(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function kQr(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":Yyo(i,o,r);return;case"client_secret_post":Kyo(i,o,n);return;case"none":Jyo(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Yyo(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Kyo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Jyo(t,e){e.set("client_id",t)}async function t6t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=SQr.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=RQr[i]||FT;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new FT(i)}}async function cN(t,e){var r,n;try{return await e6t(t,e)}catch(i){if(i instanceof RU||i instanceof NU)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await e6t(t,e);if(i instanceof BU)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await e6t(t,e);throw i}}async function e6t(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await Zyo(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await Xyo(e,t,s),u=await iEo(a,{fetchFn:o}),d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let g=await sEo(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(g),d=g}if(r!==void 0){let g=await t.codeVerifier(),A=await n6t(a,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:g,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let g=await i6t(a,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof th)||g instanceof FT))throw g}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:m}=await oEo(a,{metadata:u,clientInformation:d,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(h),"REDIRECT"}async function Xyo(t,e,r){let n=TQr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!IQr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Xhe(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=/resource_metadata="([^"]*)"/.exec(e),a=/scope="([^"]*)"/.exec(e),c;if(o)try{c=new URL(o[1])}catch{}let u=a?.[1]||void 0;return{resourceMetadataUrl:c,scope:u}}async function Zyo(t,e,r=fetch){let n=await rEo(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return _Qr.parse(await n.json())}async function r6t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?r6t(t,void 0,r):void 0;throw n}}function eEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function NQr(t,e,r=fetch){return await r6t(t,{"MCP-Protocol-Version":e},r)}function tEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function rEo(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:VJ,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let d=eEo(e,s.pathname);c=new URL(d,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await NQr(c,a,r);if(!n?.metadataUrl&&tEo(u,s.pathname)){let d=new URL(`/.well-known/${e}`,s);u=await NQr(d,a,r)}return u}function nEo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function iEo(t,{fetchFn:e=fetch,protocolVersion:r=VJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=nEo(t);for(let{url:o,type:s}of i){let a=await r6t(o,n,e);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return s==="oauth"?Ybt.parse(await a.json()):xQr.parse(await a.json())}}}async function oEo(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Xbt))throw new Error(`Incompatible auth server: does not support response type ${Xbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Zbt))throw new Error(`Incompatible auth server: does not support code challenge method ${Zbt}`)}else a=new URL("/authorize",t);let c=await zbt(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Xbt),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Zbt),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:u}}async function n6t(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let d="authorization_code",f=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:d,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let g=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],A=OQr(r,g);kQr(A,r,p,h)}s&&h.set("resource",s.href);let m=await(c??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await t6t(m);return Kbt.parse(await m.json())}async function i6t(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,f,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],m=OQr(r,h);kQr(m,r,d,f)}i&&f.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:d,body:f});if(!p.ok)throw await t6t(p);return Kbt.parse({refresh_token:n,...await p.json()})}async function sEo(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await t6t(o);return wQr.parse(await o.json())}var F3,Xbt,Zbt,xOe=Z(()=>{bQr();XB();Jbt();Jbt();DQr();BQr();F3=class extends Error{constructor(e){super(e??"Unauthorized")}};Xbt="code",Zbt="S256"});var o6t,AX,PQr=Z(()=>{vQr();XB();xOe();o6t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},AX=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new F3("No auth provider");let r;try{r=await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new F3;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new DU(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let d=await i(a,{...c,headers:u});if(d.status===401&&d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:p}=Xhe(d);this._resourceMetadataUrl=f,this._scope=p}return d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new o6t(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){s(d),(c=this.onerror)===null||c===void 0||c.call(this,d),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let d=a,f;try{f=JB.parse(JSON.parse(d.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new F3("No auth provider");if(await cN(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Xhe(a);if(this._resourceMetadataUrl=u,this._scope=d,await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var SOe,MQr=Z(()=>{Lbt();SOe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=vOe({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var aEo,yX,lN,s6t=Z(()=>{XB();xOe();MQr();aEo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},yX=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},lN=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:aEo}async _authThenStart(){var e;if(!this._authProvider)throw new F3("No auth provider");let r;try{r=await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new F3;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new yX(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,d,f;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new SOe).getReader();for(;;){let{value:h,done:m}=await p.read();if(m)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let g=JB.parse(JSON.parse(h.data));o!==void 0&&rhe(g)&&(g.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,g)}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g)}}}catch(p){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new F3("No auth provider");if(await cN(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:_Ne(e)?e.id:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,d),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new yX(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:E}=Xhe(f);if(this._resourceMetadataUrl=y,this._scope=E,await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3;return this._hasCompletedAuthFlow=!0,this.send(e)}let A=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${A}`)}if(this._hasCompletedAuthFlow=!1,f.status===202){DMr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let m=(Array.isArray(e)?e:[e]).filter(A=>"method"in A&&"id"in A&&A.id!==void 0).length>0,g=f.headers.get("content-type");if(m)if(g?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(g?.includes("application/json")){let A=await f.json(),y=Array.isArray(A)?A.map(E=>JB.parse(E)):[JB.parse(A)];for(let E of y)(o=this.onmessage)===null||o===void 0||o.call(this,E)}else throw new yX(-1,`Unexpected content type: ${g}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new yX(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as cEo}from"node:fs/promises";var Zhe,eme,OU,a6t=Z(()=>{"use strict";Ple();xOe();di();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(Zhe||(Zhe={}));eme=class extends Error{code;constructor(e,r){super(r),this.code=e}},OU=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||ZM.default}async start(){if(this._isClosed)throw new Error(R.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await i6t(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(R.t("websocketClient.errors.unauthorizedOAuth"))}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new eme(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new eme(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(R.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await n6t(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error(R.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===ZM.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(R.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(R.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==ZM.default.OPEN)throw new Error(R.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new eme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:Zhe.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.24-beta.0",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:Zhe.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await cEo(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:Zhe.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var LQr,wOe,FQr=Z(()=>{"use strict";LQr=Te(h_e(),1);di();wOe=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(R.t("mcp.auth.scopesRequired"));this.auth=new LQr.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(R.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as lEo}from"node:child_process";import{promisify as uEo}from"node:util";import{platform as dEo}from"node:os";import{URL as fEo}from"node:url";function pEo(t){let e;try{e=new fEo(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function QQr(t){pEo(t);let e=dEo(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await UQr(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await UQr(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var UQr,qQr=Z(()=>{"use strict";UQr=uEo(lEo)});function No(t){return t instanceof Error&&"code"in t}function gr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function c6t(t){if(t&&typeof t=="object"&&"response"in t){let r=hEo(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new IOe(r.error.message);case 401:return new uN(r.error.message);case 403:return new TOe(r.error.message);default:}}return t}function hEo(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var TOe,uN,IOe,Vu=Z(()=>{"use strict";TOe=class extends Error{},uN=class extends Error{},IOe=class extends Error{}});import{promises as EX}from"node:fs";import*as DOe from"node:path";import*as HQr from"node:os";var Hm,ROe=Z(()=>{"use strict";Vu();di();Hm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=HQr.homedir();return DOe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=DOe.dirname(this.getTokenFilePath());await EX.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await EX.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(R.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:gr(r)}))}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await EX.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(d){throw console.error(R.t("mcp.tokenStorage.errors.failedToSaveToken",{error:gr(d)})),d}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await EX.unlink(i):await EX.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(R.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:gr(o)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await EX.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(R.t("mcp.tokenStorage.errors.failedToClearTokens",{error:gr(e)}))}}}});var Gm,BOe=Z(()=>{"use strict";Vu();di();Gm=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${gr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${gr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log(R.t("mcp.oauth.discovery.dynamicRegistrationSupported"),a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log(R.t("mcp.oauth.discovery.dynamicRegistrationSupported"),i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${gr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(R.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log(R.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as GQr from"node:http";import*as tme from"node:crypto";import{URL as l6t}from"node:url";var CE,u6t=Z(()=>{"use strict";qQr();ROe();Vu();BOe();di();CE=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(R.t("mcp.auth.clientRegistrationFailed",{status:o.status,statusText:o.statusText,error:s}))}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Gm.extractBaseUrl(e);return Gm.discoverOAuthConfig(r)}static generatePKCEParams(){let e=tme.randomBytes(32).toString("base64url"),r=tme.createHash("sha256").update(e).digest("base64url"),n=tme.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=GQr.createServer(async(o,s)=>{try{let a=new l6t(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end(R.t("mcp.ui.notFound"));return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),d=a.searchParams.get("error");if(d){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
|
|
964
|
+
`&&n++}}return[e,r]}var EOe,Lbt=Z(()=>{EOe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function Uyo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Fbt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Fbt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Fbt(t.cause)}`:t.message:`${t}`}function AQr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Qyo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var COe,EQr,$bt,Xs,Uh,Bd,LT,L3,IU,fX,bOe,_Oe,Fhe,mX,Uhe,aN,pX,gX,hX,Mhe,A5,Ubt,Qbt,qbt,yQr,Hbt,Gbt,Lhe,jbt,Vbt,DU,vQr=Z(()=>{Lbt();COe=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(AQr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(AQr(this),r)}};EQr=t=>{throw TypeError(t)},$bt=(t,e,r)=>e.has(t)||EQr("Cannot "+r),Xs=(t,e,r)=>($bt(t,e,"read from private field"),r?r.call(t):e.get(t)),Uh=(t,e,r)=>e.has(t)?EQr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Bd=(t,e,r,n)=>($bt(t,e,"write to private field"),e.set(t,r),r),LT=(t,e,r)=>($bt(t,e,"access private method"),r),DU=class extends EventTarget{constructor(e,r){var n,i;super(),Uh(this,A5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Uh(this,L3),Uh(this,IU),Uh(this,fX),Uh(this,bOe),Uh(this,_Oe),Uh(this,Fhe),Uh(this,mX),Uh(this,Uhe,null),Uh(this,aN),Uh(this,pX),Uh(this,gX,null),Uh(this,hX,null),Uh(this,Mhe,null),Uh(this,Qbt,async o=>{var s;Xs(this,pX).reset();let{body:a,redirected:c,status:u,headers:d}=o;if(u===204){LT(this,A5,Lhe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Bd(this,fX,new URL(o.url)):Bd(this,fX,void 0),u!==200){LT(this,A5,Lhe).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){LT(this,A5,Lhe).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Xs(this,L3)===this.CLOSED)return;Bd(this,L3,this.OPEN);let f=new Event("open");if((s=Xs(this,Mhe))==null||s.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){LT(this,A5,Lhe).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=a.getReader(),m=!0;do{let{done:g,value:A}=await h.read();A&&Xs(this,pX).feed(p.decode(A,{stream:!g})),g&&(m=!1,Xs(this,pX).reset(),LT(this,A5,jbt).call(this))}while(m)}),Uh(this,qbt,o=>{Bd(this,aN,void 0),!(o.name==="AbortError"||o.type==="aborted")&<(this,A5,jbt).call(this,Fbt(o))}),Uh(this,Hbt,o=>{typeof o.id=="string"&&Bd(this,Uhe,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Xs(this,fX)?Xs(this,fX).origin:Xs(this,IU).origin,lastEventId:o.id||""});Xs(this,hX)&&(!o.event||o.event==="message")&&Xs(this,hX).call(this,s),this.dispatchEvent(s)}),Uh(this,Gbt,o=>{Bd(this,Fhe,o)}),Uh(this,Vbt,()=>{Bd(this,mX,void 0),Xs(this,L3)===this.CONNECTING&<(this,A5,Ubt).call(this)});try{if(e instanceof URL)Bd(this,IU,e);else if(typeof e=="string")Bd(this,IU,new URL(e,Qyo()));else throw new Error("Invalid URL")}catch{throw Uyo("An invalid or illegal string was specified")}Bd(this,pX,vOe({onEvent:Xs(this,Hbt),onRetry:Xs(this,Gbt)})),Bd(this,L3,this.CONNECTING),Bd(this,Fhe,3e3),Bd(this,_Oe,(n=r?.fetch)!=null?n:globalThis.fetch),Bd(this,bOe,(i=r?.withCredentials)!=null?i:!1),LT(this,A5,Ubt).call(this)}get readyState(){return Xs(this,L3)}get url(){return Xs(this,IU).href}get withCredentials(){return Xs(this,bOe)}get onerror(){return Xs(this,gX)}set onerror(e){Bd(this,gX,e)}get onmessage(){return Xs(this,hX)}set onmessage(e){Bd(this,hX,e)}get onopen(){return Xs(this,Mhe)}set onopen(e){Bd(this,Mhe,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Xs(this,mX)&&clearTimeout(Xs(this,mX)),Xs(this,L3)!==this.CLOSED&&(Xs(this,aN)&&Xs(this,aN).abort(),Bd(this,L3,this.CLOSED),Bd(this,aN,void 0))}};L3=new WeakMap,IU=new WeakMap,fX=new WeakMap,bOe=new WeakMap,_Oe=new WeakMap,Fhe=new WeakMap,mX=new WeakMap,Uhe=new WeakMap,aN=new WeakMap,pX=new WeakMap,gX=new WeakMap,hX=new WeakMap,Mhe=new WeakMap,A5=new WeakSet,Ubt=function(){Bd(this,L3,this.CONNECTING),Bd(this,aN,new AbortController),Xs(this,_Oe)(Xs(this,IU),LT(this,A5,yQr).call(this)).then(Xs(this,Qbt)).catch(Xs(this,qbt))},Qbt=new WeakMap,qbt=new WeakMap,yQr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Xs(this,Uhe)?{"Last-Event-ID":Xs(this,Uhe)}:void 0},cache:"no-store",signal:(t=Xs(this,aN))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Hbt=new WeakMap,Gbt=new WeakMap,Lhe=function(t,e){var r;Xs(this,L3)!==this.CLOSED&&Bd(this,L3,this.CLOSED);let n=new COe("error",{code:e,message:t});(r=Xs(this,gX))==null||r.call(this,n),this.dispatchEvent(n)},jbt=function(t,e){var r;if(Xs(this,L3)===this.CLOSED)return;Bd(this,L3,this.CONNECTING);let n=new COe("error",{code:e,message:t});(r=Xs(this,gX))==null||r.call(this,n),this.dispatchEvent(n),Bd(this,mX,setTimeout(Xs(this,Vbt),Xs(this,Fhe)))},Vbt=new WeakMap,DU.CONNECTING=0,DU.OPEN=1,DU.CLOSED=2});async function qyo(t){return(await Wbt).getRandomValues(new Uint8Array(t))}async function Hyo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await qyo(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function Gyo(t){return await Hyo(t)}async function jyo(t){let e=await(await Wbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function zbt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Gyo(t),r=await jyo(e);return{code_verifier:e,code_challenge:r}}var Wbt,bQr=Z(()=>{Wbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var i0,_Qr,Ybt,Vyo,xQr,Kbt,SQr,CQr,$yo,Wyo,wQr,nHa,iHa,Jbt=Z(()=>{KB();i0=oe.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:oe.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),oe.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),_Qr=oe.object({resource:oe.string().url(),authorization_servers:oe.array(i0).optional(),jwks_uri:oe.string().url().optional(),scopes_supported:oe.array(oe.string()).optional(),bearer_methods_supported:oe.array(oe.string()).optional(),resource_signing_alg_values_supported:oe.array(oe.string()).optional(),resource_name:oe.string().optional(),resource_documentation:oe.string().optional(),resource_policy_uri:oe.string().url().optional(),resource_tos_uri:oe.string().url().optional(),tls_client_certificate_bound_access_tokens:oe.boolean().optional(),authorization_details_types_supported:oe.array(oe.string()).optional(),dpop_signing_alg_values_supported:oe.array(oe.string()).optional(),dpop_bound_access_tokens_required:oe.boolean().optional()}).passthrough(),Ybt=oe.object({issuer:oe.string(),authorization_endpoint:i0,token_endpoint:i0,registration_endpoint:i0.optional(),scopes_supported:oe.array(oe.string()).optional(),response_types_supported:oe.array(oe.string()),response_modes_supported:oe.array(oe.string()).optional(),grant_types_supported:oe.array(oe.string()).optional(),token_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),service_documentation:i0.optional(),revocation_endpoint:i0.optional(),revocation_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),introspection_endpoint:oe.string().optional(),introspection_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),code_challenge_methods_supported:oe.array(oe.string()).optional()}).passthrough(),Vyo=oe.object({issuer:oe.string(),authorization_endpoint:i0,token_endpoint:i0,userinfo_endpoint:i0.optional(),jwks_uri:i0,registration_endpoint:i0.optional(),scopes_supported:oe.array(oe.string()).optional(),response_types_supported:oe.array(oe.string()),response_modes_supported:oe.array(oe.string()).optional(),grant_types_supported:oe.array(oe.string()).optional(),acr_values_supported:oe.array(oe.string()).optional(),subject_types_supported:oe.array(oe.string()),id_token_signing_alg_values_supported:oe.array(oe.string()),id_token_encryption_alg_values_supported:oe.array(oe.string()).optional(),id_token_encryption_enc_values_supported:oe.array(oe.string()).optional(),userinfo_signing_alg_values_supported:oe.array(oe.string()).optional(),userinfo_encryption_alg_values_supported:oe.array(oe.string()).optional(),userinfo_encryption_enc_values_supported:oe.array(oe.string()).optional(),request_object_signing_alg_values_supported:oe.array(oe.string()).optional(),request_object_encryption_alg_values_supported:oe.array(oe.string()).optional(),request_object_encryption_enc_values_supported:oe.array(oe.string()).optional(),token_endpoint_auth_methods_supported:oe.array(oe.string()).optional(),token_endpoint_auth_signing_alg_values_supported:oe.array(oe.string()).optional(),display_values_supported:oe.array(oe.string()).optional(),claim_types_supported:oe.array(oe.string()).optional(),claims_supported:oe.array(oe.string()).optional(),service_documentation:oe.string().optional(),claims_locales_supported:oe.array(oe.string()).optional(),ui_locales_supported:oe.array(oe.string()).optional(),claims_parameter_supported:oe.boolean().optional(),request_parameter_supported:oe.boolean().optional(),request_uri_parameter_supported:oe.boolean().optional(),require_request_uri_registration:oe.boolean().optional(),op_policy_uri:i0.optional(),op_tos_uri:i0.optional()}).passthrough(),xQr=Vyo.merge(Ybt.pick({code_challenge_methods_supported:!0})),Kbt=oe.object({access_token:oe.string(),id_token:oe.string().optional(),token_type:oe.string(),expires_in:oe.number().optional(),scope:oe.string().optional(),refresh_token:oe.string().optional()}).strip(),SQr=oe.object({error:oe.string(),error_description:oe.string().optional(),error_uri:oe.string().optional()}),CQr=i0.optional().or(oe.literal("").transform(()=>{})),$yo=oe.object({redirect_uris:oe.array(i0),token_endpoint_auth_method:oe.string().optional(),grant_types:oe.array(oe.string()).optional(),response_types:oe.array(oe.string()).optional(),client_name:oe.string().optional(),client_uri:i0.optional(),logo_uri:CQr,scope:oe.string().optional(),contacts:oe.array(oe.string()).optional(),tos_uri:CQr,policy_uri:oe.string().optional(),jwks_uri:i0.optional(),jwks:oe.any().optional(),software_id:oe.string().optional(),software_version:oe.string().optional(),software_statement:oe.string().optional()}).strip(),Wyo=oe.object({client_id:oe.string(),client_secret:oe.string().optional(),client_id_issued_at:oe.number().optional(),client_secret_expires_at:oe.number().optional()}).strip(),wQr=$yo.merge(Wyo),nHa=oe.object({error:oe.string(),error_description:oe.string().optional()}).strip(),iHa=oe.object({token:oe.string(),token_type_hint:oe.string().optional()}).strip()});function TQr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function IQr({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var DQr=Z(()=>{});var th,Qhe,RU,BU,NU,qhe,Hhe,Ghe,FT,jhe,Vhe,$he,Whe,zhe,Yhe,Khe,Jhe,RQr,BQr=Z(()=>{th=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Qhe=class extends th{};Qhe.errorCode="invalid_request";RU=class extends th{};RU.errorCode="invalid_client";BU=class extends th{};BU.errorCode="invalid_grant";NU=class extends th{};NU.errorCode="unauthorized_client";qhe=class extends th{};qhe.errorCode="unsupported_grant_type";Hhe=class extends th{};Hhe.errorCode="invalid_scope";Ghe=class extends th{};Ghe.errorCode="access_denied";FT=class extends th{};FT.errorCode="server_error";jhe=class extends th{};jhe.errorCode="temporarily_unavailable";Vhe=class extends th{};Vhe.errorCode="unsupported_response_type";$he=class extends th{};$he.errorCode="unsupported_token_type";Whe=class extends th{};Whe.errorCode="invalid_token";zhe=class extends th{};zhe.errorCode="method_not_allowed";Yhe=class extends th{};Yhe.errorCode="too_many_requests";Khe=class extends th{};Khe.errorCode="invalid_client_metadata";Jhe=class extends th{};Jhe.errorCode="insufficient_scope";RQr={[Qhe.errorCode]:Qhe,[RU.errorCode]:RU,[BU.errorCode]:BU,[NU.errorCode]:NU,[qhe.errorCode]:qhe,[Hhe.errorCode]:Hhe,[Ghe.errorCode]:Ghe,[FT.errorCode]:FT,[jhe.errorCode]:jhe,[Vhe.errorCode]:Vhe,[$he.errorCode]:$he,[Whe.errorCode]:Whe,[zhe.errorCode]:zhe,[Yhe.errorCode]:Yhe,[Khe.errorCode]:Khe,[Jhe.errorCode]:Jhe}});function zyo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function OQr(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&zyo(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function kQr(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":Yyo(i,o,r);return;case"client_secret_post":Kyo(i,o,n);return;case"none":Jyo(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Yyo(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Kyo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Jyo(t,e){e.set("client_id",t)}async function t6t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=SQr.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=RQr[i]||FT;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new FT(i)}}async function cN(t,e){var r,n;try{return await e6t(t,e)}catch(i){if(i instanceof RU||i instanceof NU)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await e6t(t,e);if(i instanceof BU)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await e6t(t,e);throw i}}async function e6t(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await Zyo(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=e);let c=await Xyo(e,t,s),u=await iEo(a,{fetchFn:o}),d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let g=await sEo(a,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(g),d=g}if(r!==void 0){let g=await t.codeVerifier(),A=await n6t(a,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:g,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(A),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let g=await i6t(a,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof th)||g instanceof FT))throw g}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:m}=await oEo(a,{metadata:u,clientInformation:d,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(h),"REDIRECT"}async function Xyo(t,e,r){let n=TQr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!IQr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Xhe(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=/resource_metadata="([^"]*)"/.exec(e),a=/scope="([^"]*)"/.exec(e),c;if(o)try{c=new URL(o[1])}catch{}let u=a?.[1]||void 0;return{resourceMetadataUrl:c,scope:u}}async function Zyo(t,e,r=fetch){let n=await rEo(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return _Qr.parse(await n.json())}async function r6t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?r6t(t,void 0,r):void 0;throw n}}function eEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function NQr(t,e,r=fetch){return await r6t(t,{"MCP-Protocol-Version":e},r)}function tEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function rEo(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:VJ,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let d=eEo(e,s.pathname);c=new URL(d,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),c.search=s.search}let u=await NQr(c,a,r);if(!n?.metadataUrl&&tEo(u,s.pathname)){let d=new URL(`/.well-known/${e}`,s);u=await NQr(d,a,r)}return u}function nEo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function iEo(t,{fetchFn:e=fetch,protocolVersion:r=VJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=nEo(t);for(let{url:o,type:s}of i){let a=await r6t(o,n,e);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return s==="oauth"?Ybt.parse(await a.json()):xQr.parse(await a.json())}}}async function oEo(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Xbt))throw new Error(`Incompatible auth server: does not support response type ${Xbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Zbt))throw new Error(`Incompatible auth server: does not support code challenge method ${Zbt}`)}else a=new URL("/authorize",t);let c=await zbt(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Xbt),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Zbt),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:u}}async function n6t(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var u;let d="authorization_code",f=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:d,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(p,h,t,e);else{let g=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],A=OQr(r,g);kQr(A,r,p,h)}s&&h.set("resource",s.href);let m=await(c??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await t6t(m);return Kbt.parse(await m.json())}async function i6t(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,f,t,e);else{let h=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],m=OQr(r,h);kQr(m,r,d,f)}i&&f.set("resource",i.href);let p=await(s??fetch)(u,{method:"POST",headers:d,body:f});if(!p.ok)throw await t6t(p);return Kbt.parse({refresh_token:n,...await p.json()})}async function sEo(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await t6t(o);return wQr.parse(await o.json())}var F3,Xbt,Zbt,xOe=Z(()=>{bQr();XB();Jbt();Jbt();DQr();BQr();F3=class extends Error{constructor(e){super(e??"Unauthorized")}};Xbt="code",Zbt="S256"});var o6t,AX,PQr=Z(()=>{vQr();XB();xOe();o6t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},AX=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new F3("No auth provider");let r;try{r=await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new F3;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new DU(this._url.href,{...this._eventSourceInit,fetch:async(a,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let d=await i(a,{...c,headers:u});if(d.status===401&&d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:p}=Xhe(d);this._resourceMetadataUrl=f,this._scope=p}return d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var c;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let u=new o6t(a.code,a.message,a);s(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var c;let u=a;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){s(d),(c=this.onerror)===null||c===void 0||c.call(this,d),this.close();return}o()}),this._eventSource.onmessage=a=>{var c,u;let d=a,f;try{f=JB.parse(JSON.parse(d.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new F3("No auth provider");if(await cN(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,s);if(!a.ok){if(a.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Xhe(a);if(this._resourceMetadataUrl=u,this._scope=d,await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3;return this.send(e)}let c=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${c}`)}}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}});var SOe,MQr=Z(()=>{Lbt();SOe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=vOe({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}}});var aEo,yX,lN,s6t=Z(()=>{XB();xOe();MQr();aEo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},yX=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},lN=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:aEo}async _authThenStart(){var e;if(!this._authProvider)throw new F3("No auth provider");let r;try{r=await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new F3;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new yX(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s;(async()=>{var c,u,d,f;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new SOe).getReader();for(;;){let{value:h,done:m}=await p.read();if(m)break;if(h.id&&(s=h.id,i?.(h.id)),!h.event||h.event==="message")try{let g=JB.parse(JSON.parse(h.data));o!==void 0&&rhe(g)&&(g.id=o),(c=this.onmessage)===null||c===void 0||c.call(this,g)}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g)}}}catch(p){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(h){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new F3("No auth provider");if(await cN(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s;try{let{resumptionToken:a,onresumptiontoken:c}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:_Ne(e)?e.id:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,d),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new yX(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:E}=Xhe(f);if(this._resourceMetadataUrl=y,this._scope=E,await cN(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new F3;return this._hasCompletedAuthFlow=!0,this.send(e)}let A=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${A}`)}if(this._hasCompletedAuthFlow=!1,f.status===202){DMr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(A=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,A)});return}let m=(Array.isArray(e)?e:[e]).filter(A=>"method"in A&&"id"in A&&A.id!==void 0).length>0,g=f.headers.get("content-type");if(m)if(g?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(g?.includes("application/json")){let A=await f.json(),y=Array.isArray(A)?A.map(E=>JB.parse(E)):[JB.parse(A)];for(let E of y)(o=this.onmessage)===null||o===void 0||o.call(this,E)}else throw new yX(-1,`Unexpected content type: ${g}`)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!s.ok&&s.status!==405)throw new yX(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as cEo}from"node:fs/promises";var Zhe,eme,OU,a6t=Z(()=>{"use strict";Ple();xOe();di();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(Zhe||(Zhe={}));eme=class extends Error{code;constructor(e,r){super(r),this.code=e}},OU=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||ZM.default}async start(){if(this._isClosed)throw new Error(R.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let i=await this._authProvider.tokens();i?.access_token&&(e=i.access_token)}catch(i){try{let o=await this._authProvider.clientInformation();if(o){let s=await this._authProvider.tokens();if(s?.refresh_token){let a=await i6t(this._url,{clientInformation:o,refreshToken:s.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(a),a?.access_token&&(e=a.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(R.t("websocketClient.errors.unauthorizedOAuth"))}throw i}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((i,o)=>{try{let s={headers:r};this._websocket=new this._WebSocket(n.toString(),s),this._websocket.on("open",()=>{i()}),this._websocket.on("error",a=>{let c=a.code!==void 0?a.code:void 0;o(new eme(c,`WebSocket error: ${a.message}`))}),this._websocket.on("message",async a=>{try{let c=a.toString(),u=JSON.parse(c);if(this._specialIds.has(Number(u.id))||u.type==="welcome")return;this.onmessage?.(await this._transformResponse(u))}catch(c){this.onerror?.(new Error(`Failed to parse WebSocket message: ${c instanceof Error?c.message:String(c)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(s){o(new eme(void 0,`Failed to create WebSocket: ${s}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(R.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),i=await n6t(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(i)}else throw new Error(R.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===ZM.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(R.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(R.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==ZM.default.OPEN)throw new Error(R.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new eme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:Zhe.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.24",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:i}=r||{};return{type:Zhe.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{originalText:await cEo(n,"utf8"),modifiedText:i}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:Zhe.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",i=>{try{let o=JSON.parse(i.toString());Number(o.id)===e&&(this._specialIds.delete(e),o.payload.success?r(o.payload.data.text):n(o.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var LQr,wOe,FQr=Z(()=>{"use strict";LQr=Te(h_e(),1);di();wOe=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(R.t("mcp.auth.scopesRequired"));this.auth=new LQr.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(R.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as lEo}from"node:child_process";import{promisify as uEo}from"node:util";import{platform as dEo}from"node:os";import{URL as fEo}from"node:url";function pEo(t){let e;try{e=new fEo(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function QQr(t){pEo(t);let e=dEo(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let i={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await UQr(r,n,i)}catch(o){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let s=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let a of s)try{await UQr(a,[t],i);return}catch{continue}}throw new Error(`Failed to open browser: ${o instanceof Error?o.message:"Unknown error"}`)}}var UQr,qQr=Z(()=>{"use strict";UQr=uEo(lEo)});function No(t){return t instanceof Error&&"code"in t}function gr(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function c6t(t){if(t&&typeof t=="object"&&"response"in t){let r=hEo(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new IOe(r.error.message);case 401:return new uN(r.error.message);case 403:return new TOe(r.error.message);default:}}return t}function hEo(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var TOe,uN,IOe,Vu=Z(()=>{"use strict";TOe=class extends Error{},uN=class extends Error{},IOe=class extends Error{}});import{promises as EX}from"node:fs";import*as DOe from"node:path";import*as HQr from"node:os";var Hm,ROe=Z(()=>{"use strict";Vu();di();Hm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=HQr.homedir();return DOe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=DOe.dirname(this.getTokenFilePath());await EX.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await EX.readFile(r,"utf-8"),i=JSON.parse(n);for(let o of i)e.set(o.serverName,o)}catch(r){r.code!=="ENOENT"&&console.error(R.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:gr(r)}))}return e}static async saveToken(e,r,n,i,o){await this.ensureConfigDir();let s=await this.loadTokens(),a={serverName:e,token:r,clientId:n,tokenUrl:i,mcpServerUrl:o,updatedAt:Date.now()};s.set(e,a);let c=Array.from(s.values()),u=this.getTokenFilePath();try{await EX.writeFile(u,JSON.stringify(c,null,2),{mode:384})}catch(d){throw console.error(R.t("mcp.tokenStorage.errors.failedToSaveToken",{error:gr(d)})),d}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),i=this.getTokenFilePath();try{n.length===0?await EX.unlink(i):await EX.writeFile(i,JSON.stringify(n,null,2),{mode:384})}catch(o){console.error(R.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:gr(o)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await EX.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(R.t("mcp.tokenStorage.errors.failedToClearTokens",{error:gr(e)}))}}}});var Gm,BOe=Z(()=>{"use strict";Vu();di();Gm=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${gr(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${gr(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);if(a){let c=this.metadataToOAuthConfig(a);return a.registration_endpoint&&console.log(R.t("mcp.oauth.discovery.dynamicRegistrationSupported"),a.registration_endpoint),c}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let i=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(i){let o=this.metadataToOAuthConfig(i);return i.registration_endpoint&&console.log(R.t("mcp.oauth.discovery.dynamicRegistrationSupported"),i.registration_endpoint),o}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${gr(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(R.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let i=n.authorization_servers[0],o=new URL("/.well-known/oauth-authorization-server",i).toString(),s=await this.fetchAuthorizationServerMetadata(o);return s?(console.log(R.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(s)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as GQr from"node:http";import*as tme from"node:crypto";import{URL as l6t}from"node:url";var CE,u6t=Z(()=>{"use strict";qQr();ROe();Vu();BOe();di();CE=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let i={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let s=await o.text();throw new Error(R.t("mcp.auth.clientRegistrationFailed",{status:o.status,statusText:o.statusText,error:s}))}return await o.json()}static async discoverOAuthFromMCPServer(e){let r=Gm.extractBaseUrl(e);return Gm.discoverOAuthConfig(r)}static generatePKCEParams(){let e=tme.randomBytes(32).toString("base64url"),r=tme.createHash("sha256").update(e).digest("base64url"),n=tme.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let i=GQr.createServer(async(o,s)=>{try{let a=new l6t(o.url,`http://localhost:${this.REDIRECT_PORT}`);if(a.pathname!==this.REDIRECT_PATH){s.writeHead(404),s.end(R.t("mcp.ui.notFound"));return}let c=a.searchParams.get("code"),u=a.searchParams.get("state"),d=a.searchParams.get("error");if(d){s.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),s.end(`
|
|
965
965
|
<html>
|
|
966
966
|
<body>
|
|
967
967
|
<h1>${R.t("mcp.ui.authenticationFailed")}</h1>
|
|
@@ -4556,7 +4556,7 @@ ${Fe.description}`:Fe.subject||Fe.description||"Thinking...",[]),Ee=(0,oa.useCal
|
|
|
4556
4556
|
`,e-1),[i,o]=dra(r);return{line:n===-1?i:t.slice(0,n+1).match(/\n/g).length+i,column:e-n-1+o}}function zJt(t,e,r){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");return fra(t,e,r)}var pra=t=>`\\u{${t.codePointAt(0).toString(16)}}`,YJt=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#i;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:i}=e;super(void 0,{cause:r}),this.#e=i,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${mra(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
|
|
4557
4557
|
|
|
4558
4558
|
${e}
|
|
4559
|
-
`:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=hra(r,this.#t.message);if(n)return(0,dei.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#o(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#o(!1),this.#i}},hra=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:zJt(t,Number(n),{oneBased:!0})},mra=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${pra(n)})`);function KJt(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new YJt({jsonParseError:n,fileName:r,input:t})}}var bti=Te(Eti(),1);import{fileURLToPath as Fna}from"node:url";function vti(t){return t instanceof URL?Fna(t):t}var qna=t=>Qna.resolve(vti(t)??".","package.json"),Hna=(t,e)=>{let r=typeof t=="string"?KJt(t):t;return e&&(0,bti.default)(r),r};async function Cti({cwd:t,normalize:e=!0}={}){let r=await Una.readFile(qna(t),"utf8");return Hna(r,e)}async function _ti(t){let e=await QZn("package.json",t);if(e)return{packageJson:await Cti({...t,cwd:Gna.dirname(e)}),path:e}}import{fileURLToPath as jna}from"url";import Vna from"path";var $na=jna(import.meta.url),Wna=Vna.dirname($na),itt;async function kP(){if(itt)return itt;let t=await _ti({cwd:Wna});if(t)return itt=t.packageJson,itt}async function PP(){let t=await kP();return"0.3.24
|
|
4559
|
+
`:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=hra(r,this.#t.message);if(n)return(0,dei.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#o(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#o(!1),this.#i}},hra=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:zJt(t,Number(n),{oneBased:!0})},mra=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${pra(n)})`);function KJt(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new YJt({jsonParseError:n,fileName:r,input:t})}}var bti=Te(Eti(),1);import{fileURLToPath as Fna}from"node:url";function vti(t){return t instanceof URL?Fna(t):t}var qna=t=>Qna.resolve(vti(t)??".","package.json"),Hna=(t,e)=>{let r=typeof t=="string"?KJt(t):t;return e&&(0,bti.default)(r),r};async function Cti({cwd:t,normalize:e=!0}={}){let r=await Una.readFile(qna(t),"utf8");return Hna(r,e)}async function _ti(t){let e=await QZn("package.json",t);if(e)return{packageJson:await Cti({...t,cwd:Gna.dirname(e)}),path:e}}import{fileURLToPath as jna}from"url";import Vna from"path";var $na=jna(import.meta.url),Wna=Vna.dirname($na),itt;async function kP(){if(itt)return itt;let t=await _ti({cwd:Wna});if(t)return itt=t.packageJson,itt}async function PP(){let t=await kP();return"0.3.24"}vs();Ut();import zj from"node:process";var xti={name:"about",description:R.t("command.about"),kind:"built-in",action:async t=>{let e=zj.platform,r=R.t("aboutCommand.noSandbox");zj.env.SANDBOX&&zj.env.SANDBOX!=="sandbox-exec"?r=zj.env.SANDBOX:zj.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${zj.env.SEATBELT_PROFILE||R.t("aboutCommand.unknown")})`);let n=t.services.config?.getModel()||R.t("aboutCommand.unknown"),i=await PP(),o=t.services.settings.merged.selectedAuthType||"",s=zj.env.GOOGLE_CLOUD_PROJECT||"",a={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s};t.ui.addItem(a,Date.now())}};Ut();Ut();vs();var stt="\x1B[32m";var wti="\x1B[31m",MP="\x1B[36m",F0="\x1B[90m";var Ic="\x1B[0m";function ott(t,e,r,n=!1){let i="";if(t.length===0)return i="\u{1F534} ",`${i}${e}
|
|
4560
4560
|
${wti}${R.t("agentsCommand.list.noAgentsFound")}${Ic}
|
|
4561
4561
|
`;i="\u{1F7E2} ";let o=`${i}${e}
|
|
4562
4562
|
`;for(let s of t)n?o+=zna(s):o+=`${stt}- ${s.agentType}${Ic}
|
|
@@ -5679,7 +5679,7 @@ ${R.t("gemini.errors.criticalUnhandledRejection")}
|
|
|
5679
5679
|
=========================================
|
|
5680
5680
|
${R.t("gemini.errors.reason",{reason:e})}${e instanceof Error&&e.stack?`
|
|
5681
5681
|
${R.t("gemini.errors.stackTrace")}
|
|
5682
|
-
${e.stack}`:""}`;Fs.emit("log-error",n),t||(t=!0,Fs.emit("open-debug-console"))})}function j1a(){console.log(R.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.3.24
|
|
5682
|
+
${e.stack}`:""}`;Fs.emit("log-error",n),t||(t=!0,Fs.emit("open-debug-console"))})}function j1a(){console.log(R.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.3.24"}},r=`crash-${Date.now()}-${process.pid}.json`,n=k1a.join(process.cwd(),r);try{U1a.writeFileSync(n,JSON.stringify(e,null,2)),console.error(R.t("gemini.crashDetected",{crashFilePath:n})),console.error(R.t("gemini.coreDumpWillBeGenerated"))}catch(i){console.error(R.t("gemini.failedToWriteCrashFile"),i)}process.abort()}),process.on("warning",t=>{console.warn(R.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(R.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function L0i(){G1a();let t=process.cwd(),e=fl(t);if(!e.user.settings.cna){let m=await QBe();m&&e.setValue("User","cna",m)}if(await Nhi(),e.errors.length>0){for(let m of e.errors){let g=R.t("gemini.errorInFile",{path:m.path,message:m.message});process.env.NO_COLOR||(g=`\x1B[31m${g}\x1B[0m`),console.error(g),console.error(R.t("gemini.pleaseFixFileAndTryAgain",{path:m.path}))}process.exit(1)}let r=await Rnt(),n=typeof r.resume=="string";(!!r.prompt&&!r.promptInteractive&&!r.continue&&(!r.resume||n)||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let o=JP(t),s=n&&typeof r.resume=="string"?r.resume:Eg.generateSessionId(),a=await QV(e.merged,o,s,r);if(R.changeLanguage(a.getLanguage()),a.getDebugMode()&&j1a(),L1a.setDefaultResultOrder(Q1a(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(R.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),a.getListExtensions()){console.debug(R.t("gemini.installedExtensions"));for(let m of o)console.debug(`- ${m.config.name}`);process.exit(0)}if(r._&&r._[0]==="agent"){let{agentCommand:m}=await Promise.resolve().then(()=>(urr(),Shi)),g=(await Promise.resolve().then(()=>(Dnr(),Inr))).default;await g().scriptName("iflow").command(m).help().version(!1).parse(),process.exit(0)}if(r._&&r._[0]==="commands"){let{commandsCommand:m}=await Promise.resolve().then(()=>(crr(),dhi)),g=(await Promise.resolve().then(()=>(Dnr(),Inr))).default;await g().scriptName("iflow").command(m).help().version(!1).parse(),process.exit(0)}if(e.merged.selectedAuthType||process.env.CLOUD_SHELL==="true"&&e.setValue("User","selectedAuthType",zt.CLOUD_SHELL),xui(a.getDebugMode()),await a.initialize(),a.getExperimentalAcp()?a.setUsageMode("sdk"):a.setUsageMode("interactive"),$s.loadCustomThemes(e.merged.customThemes),e.merged.theme&&($s.setActiveTheme(e.merged.theme)||console.warn(R.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let m=e.merged.autoConfigureMaxOldSpaceSize?q1a(a):[],g=a.getSandbox();if(g){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let A=wV(e.merged.selectedAuthType);if(A)throw new Error(A);await a.refreshAuth(e.merged.selectedAuthType,{apiKey:e.merged.apiKey,baseUrl:e.merged.baseUrl,modelName:e.merged.modelName})}catch(A){console.error(R.t("gemini.errorAuthenticating"),A),process.exit(1)}await Sgi(g,m,a),process.exit(0)}else m.length>0&&(await H1a(m),process.exit(0))}if(e.merged.selectedAuthType===zt.LOGIN_WITH_IFLOW&&a.isBrowserLaunchSuppressed()&&await yL(e.merged.selectedAuthType,a),a.getExperimentalAcp())return a.getAcpPort()?await zgi(a,e,o,r,a.getAcpPort()):qgi(a,e,o,r);let c=a.getQuestion(),u=[...await wgi(),...await Igi(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume&&!n||process.stdin.isTTY&&c?.length===0){console.clear();let m=await PP();M0i(P0i(t),e);try{await hri()}catch(C){a.getDebugMode()&&console.warn("Failed to detect/enable Kitty protocol:",C)}try{await a.setIdeModeAndSyncConnection(!0)}catch(C){console.error(R.t("gemini.failedToConnectToIdeServer"),C)}let g,A=async()=>{try{if(console.clear(),M0i(P0i(t),e),g)try{g.unmount(),await new Promise(D=>process.nextTick(D))}catch(D){console.error(R.t("gemini.errorDuringUnmount"),D)}let{executeSessionStartHooks:C}=await Promise.resolve().then(()=>(Jj(),Kj)),S=await C(a,"resume");g=GCe((0,mbe.jsx)(Rnr.default.StrictMode,{children:(0,mbe.jsx)(Urr,{instance:()=>g,config:a,settings:e,startupWarnings:u,version:m,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,fgMode:!0,sessionStartContext:S})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1,stdout:wXt(),maxFps:20})}catch(C){console.error(R.t("gemini.errorDuringResume"),C)}};process.on("SIGCONT",A),rbe(()=>{process.off("SIGCONT",A)});let y="startup";(r.continue||r.resume)&&(y="resume");let{executeSessionStartHooks:E}=await Promise.resolve().then(()=>(Jj(),Kj)),v=await E(a,y);g=GCe((0,mbe.jsx)(Rnr.default.StrictMode,{children:(0,mbe.jsx)(Urr,{instance:()=>g,config:a,settings:e,startupWarnings:u,version:m,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,sessionStartContext:v})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1,stdout:wXt()}),e.merged.disableAutoUpdate||trt().then(C=>{Umi(C,e,a.getProjectRoot())}).catch(C=>{a.getDebugMode()&&console.error(R.t("gemini.updateCheckFailed"),C)}),rbe(()=>g.unmount());return}!process.stdin.isTTY&&!c&&(c+=await bgi()),c||(console.error(R.t("gemini.noInputProvidedViaStdin")),process.exit(1));let f=Math.random().toString(16).slice(2);BJ(a,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:c,prompt_id:f,auth_type:a.getContentGeneratorConfig()?.authType,prompt_length:c.length});let p=await V1a(a,o,e,r),h=r.outputFile||r.output_file;await Bgi(p,c,f,h),process.exit(0)}function M0i(t,e){if(!e.merged.hideWindowTitle){let r=(process.env.CLI_TITLE||`iFlow - ${t}`).replace(/[\x00-\x1F\x7F]/g,"");process.stdout.write(`\x1B]2;${r}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}async function V1a(t,e,r,n){let i=t;if(t.getApprovalMode()!==Kn.YOLO){let o=r.merged.excludeTools||[],s=[Md.Name,uh.Name,Ff.Name],a=[...new Set([...o,...s])],c={...r.merged,excludeTools:a},u={...n};i=await QV(c,e,t.getSessionId(),u),await i.initialize()}return await $1a(r.merged.selectedAuthType,i,r)}async function $1a(t,e,r){!t&&!process.env.GEMINI_API_KEY&&!dNe()&&(console.error(R.t("gemini.pleaseSetAuthMethod",{userSettingsPath:Hj})),process.exit(1)),t||(dNe()?t=zt.IFLOW:t=zt.IFLOW);let n=wV(t);return n!=null&&(console.error(n),process.exit(1)),await e.refreshAuth(t,{apiKey:r.merged.apiKey,baseUrl:r.merged.baseUrl,modelName:r.merged.modelName}),e}L0i().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
|
|
5683
5683
|
/**
|
|
5684
5684
|
* @license
|
|
5685
5685
|
* Copyright 2025 Google LLC
|